r032: fix share capacity and add native scoped administration
This commit is contained in:
1 parent
b9a2f2e309
commit
11786968cb
20 files changed
+754
-23
No files matched your search
@@ -7,7 +7,7 @@ Kompiliertes Bun-Binary (TypeScript), läuft als SysVinit-Service auf Unraid.
|
||||
- **Health-Check:** `http://UNRAID-IP:3002/health` (offen, ohne Auth)
|
||||
- **Config-Server:** `http://127.0.0.1:3013/config` (localhost + separater Admin-Token)
|
||||
- **Auth:** API-Key (Bearer-Token) für `/mcp`
|
||||
- **Tools:** 35 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox)
|
||||
- **Tools:** 47 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox)
|
||||
|
||||
---
|
||||
|
||||
@@ -386,3 +386,12 @@ shasum -a 256 dist/mua-*.txz
|
||||
[r031-Fix, Prüfungen, Installation/Restore und Transfergrenzen](docs/SHELL-CWD-FIX.md).
|
||||
MUA läuft direkt auf dem Unraid-Host. Verbindungstest trennt MCP-Transport/Auth-Dispatch
|
||||
von lokalem Prozessstart; Shell und Dienststart verwenden das stabile cwd `/`.
|
||||
|
||||
|
||||
## r032: native Verwaltung und gezielte Diagnose
|
||||
|
||||
[Funktionsumfang, Grenzen, Beispiele, Migration und Abnahmetests](docs/NATIVE-ADMIN.md).
|
||||
Sieben neue Werkzeuge laufen im vorhandenen MUA auf Unraid; kein weiterer Dienst,
|
||||
kein Container und kein SSH-Proxy. Hermes entdeckt sie über den bestehenden MCP.
|
||||
In verbundenen Desktop-Clients sind dies Agentenwerkzeuge, keine zusätzlichen
|
||||
Dashboard-Tabs. Bestehende Toolfreigaben und Zugangsdaten bleiben unverändert.
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,178 @@
|
||||
# Native Verwaltung und Diagnose — r032
|
||||
|
||||
MUA bleibt ein einzelnes Unraid-Plugin. Alle Funktionen laufen auf dem NAS.
|
||||
Hermes am Gateway nutzt den vorhandenen Streamable-HTTP-Endpunkt. Mac-Apps
|
||||
benötigen keinen Patch; bei einer bestehenden Sitzung muss ggf. die
|
||||
MCP-Werkzeugerkennung neu geladen werden. Dies ergänzt Werkzeuge für Agenten,
|
||||
keine neuen Tabs in einer Desktop-App. Keine Profiländerung und kein neuer MCP.
|
||||
|
||||
## Speicherkorrektur und API-Migration
|
||||
|
||||
`shares.ini` liefert `free` und `used` in KiB. Diese Werte beschreiben das
|
||||
zugrunde liegende Dateisystem, nicht allein den Inhalt eines Shares.
|
||||
Der bisherige Parser übernahm sie unverändert als Bytes. `size=0` lieferte
|
||||
zusätzlich irreführende `0 %`. Der frühere Laufwerksfix r030 erfasste Shares nicht.
|
||||
|
||||
- `free_bytes`: korrekt in Bytes, fehlende Messung `null`.
|
||||
- `filesystem_size_bytes`, `filesystem_used_bytes`,
|
||||
`filesystem_used_percent`: ausdrücklich Dateisystemwerte.
|
||||
- `share_size_bytes` / kompatibles `size_bytes`: hier `null`, weil der
|
||||
tatsächliche Share-Verbrauch nicht gemessen wird. Unraid berechnet ihn separat
|
||||
mit `share_size`; dieser Metadatenaufruf löst bewusst keine Vollsuche aus.
|
||||
- `used_bytes` und `used_percent`: `null`; keine angebliche Share-Belegung aus
|
||||
Dateisystemwerten ableiten. Clients müssen `null` als unbekannt behandeln.
|
||||
- `source`, `capacity_scope`, `share_size_source` kennzeichnen die Herkunft.
|
||||
|
||||
Beispiel aus dem freigegebenen appdata-Abgleich: `free=5116038016` entspricht
|
||||
5.238.822.928.384 Bytes, exakt dem unabhängigen `df -B1`. `used=2564191488`
|
||||
entspricht 2.625.732.083.712 Bytes Dateisystembelegung. Der eigene ZFS-Dataset-
|
||||
Verbrauch war dagegen 262.392.180.736 Bytes. Unterschiedliche Ebenen dürfen
|
||||
nicht als dieselbe Größe verglichen werden. Das ist keine Korrekturregel im
|
||||
Hermes-Skill, sondern eine Korrektur im Datenlieferanten.
|
||||
|
||||
`unraid_disk_health.healthy=true` wurde durch `array_io_ok`, `smart_coverage`
|
||||
und `healthy=null` bei unvollständiger Beurteilung ersetzt. Ein fehlender
|
||||
Array-I/O-Fehler beweist keine vollständige SMART-Gesundheit. Der neue
|
||||
Diagnoseaufruf liefert gezielt SMART-JSON einschließlich dessen Exitstatus.
|
||||
|
||||
## Sieben zusätzliche Werkzeuge
|
||||
|
||||
| Werkzeug | Wirkung |
|
||||
|---|---|
|
||||
| `unraid_share_users` | Nur Namen/Indizes der SMB-Nutzer, keine Geheimnisse. |
|
||||
| `unraid_share_permissions` | Ein Share: cfg-Felder und wirksame Samba-Sektion. |
|
||||
| `unraid_share_preview` | Vorschau für create, permissions oder remove. |
|
||||
| `unraid_share_apply` | Exakt die gebundene Vorschau nativ ausführen. |
|
||||
| `unraid_docker_template_preview` | Strukturierte XML-Anlage oder gezielter Rückbau. |
|
||||
| `unraid_docker_template_apply` | Exakt die gebundene Docker-Vorschau ausführen. |
|
||||
| `unraid_storage_diagnostics` | Exakter ZFS-Pool/Dataset/Snapshots, SMART oder Parity-Verlauf. |
|
||||
|
||||
Bestehende eingeschränkte Freigaben werden nicht erweitert. `none` bleibt
|
||||
gesperrt; `all` umfasst wie bisher ausdrücklich sämtliche Werkzeuge. Vorschauen
|
||||
sind als `active`, die beiden Apply-Werkzeuge als `critical`, reine Abfragen als
|
||||
`read` eingestuft. Freigaben über die bestehende MUA-WebGUI verwalten.
|
||||
|
||||
## Share-Ablauf
|
||||
|
||||
Zuerst echte Nutzernamen über `unraid_share_users` bestimmen. Beispielvorschau:
|
||||
|
||||
```json
|
||||
{"action":"create","name":"Projekt-Test","pool":"nvme-storage","description":"Privater Test","access":{"michael":"read-write","sarah":"read-only"}}
|
||||
```
|
||||
|
||||
Vorschau unter der vorhandenen Nutzerautorisierung prüfen. Danach
|
||||
`unraid_share_apply` mit `approval_ticket` und `confirm:true`. Ticket gilt zehn
|
||||
Minuten, einmalig, für normalisierte Parameter und den beobachteten Zielzustand.
|
||||
Änderungen an Konfiguration oder Benutzerzuordnung erfordern eine neue Vorschau.
|
||||
Ein Lock verhindert konkurrierende MUA-Aktionen am gleichen Ziel. Das ersetzt
|
||||
keine globale Sperre gegen parallele Änderungen in Unraids eigener GUI.
|
||||
|
||||
Die native `emcmd`-Schnittstelle benutzt dieselben Aktionen wie ShareEdit und
|
||||
SecuritySMB. Erst ohne Export anlegen, SMB auf Private setzen, ungenannte Nutzer
|
||||
ausschließen, angegebene Rechte setzen, anschließend exportieren. Rücklese prüft
|
||||
cfg und bei aktivem Export wirksame Samba-Listen. Bei reinen Rechteänderungen
|
||||
bleibt der bisherige Exportmodus erhalten; ein deaktivierter Share wird nicht
|
||||
unbemerkt freigegeben. Bei einer fehlgeschlagenen Berechtigungsänderung
|
||||
wird der Export nach Möglichkeit deaktiviert und ein Teilzustand gemeldet;
|
||||
keine fremden Daten löschen und keine spekulative automatische Wiederholung.
|
||||
|
||||
`permissions` ersetzt ausschließlich **SMB**-Rechte, nicht NFS oder lokale
|
||||
Unix-Rechte. `remove` akzeptiert nur einen vorhandenen leeren Share und nutzt
|
||||
die native Löschfunktion. Kein rekursives Löschen, kein SMB-/Array-Neustart.
|
||||
Keine Passwortsuche. Konfigurationsprüfung ist ausdrücklich kein echter
|
||||
authentifizierter SMB-Lese-/Schreibtest.
|
||||
|
||||
## Eigene Docker-XML
|
||||
|
||||
```json
|
||||
{"action":"create","name":"Whoami-Test","image":"traefik/whoami:latest","ports":[{"host_port":18767,"container_port":80}],"memory_mb":64,"cpus":0.25,"description":"Isolierter Funktionstest"}
|
||||
```
|
||||
|
||||
Quelle und Tag vorher prüfen; Digest oder feste Version bevorzugen. Der Helfer
|
||||
baut ausschließlich strukturierte XML v2 und verwendet Unraids unverändertes
|
||||
`xmlToCommand`. Das native `managed=dockerman` entsteht automatisch. Dies
|
||||
bedeutet Verwaltung durch dockerMan, keine Unraid-Zertifizierung des Images.
|
||||
|
||||
Bewusste erste Ausbaustufe: bridge, Loopback-Ports, höchstens acht Freigaben,
|
||||
32–2048 MiB, 0,1–4 CPUs, kein Autostart, keine Mounts/Geräte/zusätzlichen
|
||||
Capabilities, keine freien ExtraParams oder beliebige rohe XML. Es werden
|
||||
keine Geheimnisse als Umgebungsvariablen verwaltet. Namen sind auf 64 einfache
|
||||
Zeichen beschränkt. Vorlagen-Update-URL bleibt leer statt einer falschen HTML-URL.
|
||||
|
||||
Der Container wird **gestoppt angelegt**; bestehendes Startwerkzeug verwenden.
|
||||
Vorhandene Namen/Vorlagen werden nie ersetzt. Pull erfolgt vor XML-Anlage.
|
||||
Fehler nennen erreichte Schritte und mögliche eigene Restartefakte; kein
|
||||
blindes Rollback, Pruning oder Löschen möglicherweise inzwischen genutzter Daten.
|
||||
|
||||
Rückbau: erst ausdrücklich stoppen, dann Vorschau
|
||||
`{"action":"remove","name":"Whoami-Test","remove_template":true}`.
|
||||
Anschließend Apply. Image und Volumes bleiben bewusst erhalten; es gibt kein
|
||||
globales Prune und kein erzwungenes Löschen. Der Zustand und gegebenenfalls die
|
||||
Vorlagenzuordnung müssen vor Apply unverändert sein.
|
||||
|
||||
## Gezielt lesen
|
||||
|
||||
`unraid_storage_diagnostics` unterstützt:
|
||||
|
||||
- `zfs_pool`, `target`: `zpool status -p` für genau den Pool, inklusive Scrubstatus.
|
||||
- `zfs_dataset`, `target`: Dataset-Belegung, Referenz, frei und Snapshot-Belegung.
|
||||
- `zfs_snapshots`, `target`: höchstens 20 neueste Snapshot-Zeilen, Begrenzung markiert.
|
||||
- `smart`, `target`: exakter Unraid-Laufwerksname, auf physisches Gerät aufgelöst;
|
||||
`smartctl -a -j -n standby`, kein Selftest und kein absichtliches Aufwecken.
|
||||
- `parity_history`: höchstens 20 native History-Zeilen; fehlende History ist kein
|
||||
erfolgreicher Check. Kein Start/Abbruch einer Prüfung.
|
||||
|
||||
Keine globalen Containerinventare durch die neuen Werkzeuge. Die Zielnamen
|
||||
OpenVPN-KIT und GluetunVPN werden in den neuen Administrationsfunktionen
|
||||
abgelehnt. Das ist **keine vollständige Zugriffssperre für die bestehende freie
|
||||
Root-Shell oder alle alten Werkzeuge**; Michaels umfassendes VPN-Verbot bleibt
|
||||
zusätzlich verbindliche Arbeitsanweisung.
|
||||
|
||||
## Fehler, Tests und Betrieb
|
||||
|
||||
Prozess-Exitcodes werden beachtet; strukturierte Ergebnisse mit Fehlerstatus
|
||||
werden im MCP als Fehler und im Audit nicht als Erfolg markiert. Ein Shell-
|
||||
Gesamtstatus kann trotzdem keine vorher absichtlich verschluckten Fehler einer
|
||||
beliebigen Befehlsfolge erkennen. Genau dafür sind die neuen nativen Abläufe da.
|
||||
|
||||
Prüfen: `bun test`, `bunx tsc --noEmit`, PHP-Lint; außerdem
|
||||
`php scripts/test-admin.php` und die vorhandenen drei PHP-Regressionstests.
|
||||
Der neue PHP-Test verwendet ausschließlich eigene temporäre Fixtures und
|
||||
ersetzt Hostaktionen durch Testdoubles. Er verändert keine echten Shares.
|
||||
|
||||
`php scripts/test-admin-live.php --authorized-temporary-test` ist ein separater,
|
||||
ausdrücklich schreibender Integrationstest auf Michaels Unraid. Er erstellt
|
||||
nur zufällig benannte eigene Testobjekte auf nvme-storage, Michael RW/Sarah RO,
|
||||
einen loopbackgebundenen whoami auf Port 18767, prüft HTTP und native Zuordnung,
|
||||
und entfernt eigene Artefakte im finally-Pfad. Niemals ungefragt für fremde
|
||||
Systeme ausführen. Keine echten SMB-Anmeldungen im Test.
|
||||
|
||||
Paketbau: `bash scripts/package.sh`. Der neue PHP-Helfer wird regulär mit
|
||||
installiert und bei Plugin-Entfernung mit entfernt. Zugangsdaten/Freigaben in
|
||||
`mua.conf` werden nicht ersetzt. Für ein Update ist nur der MUA-Dienstneustart
|
||||
erforderlich; vorher aktive MCP-Aufrufe auslaufen lassen. Kein Unraid-/Hermes-/
|
||||
Docker-Neustart und keine Änderungen an TTS/STT. Wiederherstellung weiterhin
|
||||
über das reguläre Pluginpaket plus vorhandene private Konfiguration.
|
||||
|
||||
Herstellergrundlage: https://docs.unraid.net/go/shares/ und
|
||||
https://docs.unraid.net/unraid-os/using-unraid-to/run-docker-containers/managing-and-customizing-containers/;
|
||||
installierte ShareEdit/SecuritySMB/Helpers.php bleiben bei Versionswechseln zu
|
||||
prüfen. Es wurden keine Herstellerdateien gepatcht.
|
||||
|
||||
## Abnahme am 24.10.2026
|
||||
|
||||
- 28 Bun-/HTTP-Tests bestanden; TypeScript ohne Fehler.
|
||||
- 23 neue PHP-Fixture-Prüfungen bestanden, plus 29 vorhandene PHP-Checks
|
||||
für Laufwerks-Einheiten, Benachrichtigungen und Docker-Updatecache.
|
||||
- Native Integration mit ausschließlich eigenen zufällig benannten Testobjekten:
|
||||
Share Private, Michael RW/Sarah RO, cfg und wirksame Samba-Listen bestätigt;
|
||||
native XML-Erstellung, dockerMan-Label und Isolation bestätigt; HTTP 200;
|
||||
Entfernung eines laufenden Containers korrekt verweigert. Anschließend eigene
|
||||
Shares/Container/Vorlagen und das neu geladene ungeteilte Image entfernt.
|
||||
- Kein authentifizierter SMB-Clienttest, keine visuelle GUI-Abnahme.
|
||||
- Der neue Dataset-Leseaufruf wurde gezielt gegen nvme-storage/appdata geprüft.
|
||||
Weitere Diagnosevarianten sind typgeprüft/implementiert, aber nicht pauschal
|
||||
für jede Laufwerksart oder jede Unraid-Version praktisch abgenommen.
|
||||
|
||||
Native Herstellerdateien, produktive Shares/Container, VPN, API-Schlüssel,
|
||||
MUA-Freigaben und Hermes-Profile wurden bei diesen Tests nicht geändert.
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0); // Fehler werden als JSON-RPC-Error zurückgegeben, nicht als HTML
|
||||
|
||||
const MUA_VERSION = '2026.10.12.r031';
|
||||
const MUA_VERSION = '2026.10.24.r032';
|
||||
const MUA_SERVER_NAME = 'mua';
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ const MUA_PORT = 3002;
|
||||
const MUA_BIND = '0.0.0.0';
|
||||
const MUA_SESSION_TTL = 3600; // Sekunden
|
||||
const MUA_SERVER_NAME = 'mua';
|
||||
const MUA_VERSION = '2026.10.12.r031';
|
||||
const MUA_VERSION = '2026.10.24.r032';
|
||||
|
||||
// ── Session-Management (in-memory) ───────────────────────────────────────
|
||||
$sessions = []; // session_id => ['created' => time, 'initialized' => bool]
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mua",
|
||||
"version": "2026.10.12.r031",
|
||||
"version": "2026.10.24.r032",
|
||||
"description": "Mikes Unraid Agent - MCP over HTTP (Streamable HTTP) for Unraid",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
@@ -8,7 +8,7 @@
|
||||
"build": "bun build ./src/index.ts --compile --target=bun-linux-x64 --outfile dist/mua",
|
||||
"build:mac": "bun build ./src/index.ts --compile --target=bun-darwin-arm64 --outfile dist/mua-mac",
|
||||
"start": "bun run src/index.ts",
|
||||
"selftest": "bun test src/security.test.ts"
|
||||
"selftest": "bun test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
|
||||
+11
-4
@@ -2,13 +2,13 @@
|
||||
<!DOCTYPE PLUGIN [
|
||||
<!ENTITY name "mua">
|
||||
<!ENTITY author "Michael">
|
||||
<!ENTITY version "2026.10.12.r031">
|
||||
<!ENTITY version "2026.10.24.r032">
|
||||
<!ENTITY launch "Settings/mua">
|
||||
<!ENTITY pluginURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/plugin/mua.plg">
|
||||
<!ENTITY pluginLOC "/boot/config/plugins/&name;">
|
||||
<!ENTITY emhttpLOC "/usr/local/emhttp/plugins/&name;">
|
||||
<!ENTITY txzURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.10.12.r031-x86_64-1.txz">
|
||||
<!ENTITY txzSHA256 "433e6532a47fd8fa527e2cb91aba45fc3d1b0dc446b7f1a0d4431e3b88c1942e">
|
||||
<!ENTITY txzURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.10.24.r032-x86_64-1.txz">
|
||||
<!ENTITY txzSHA256 "0a827fe323b8bea00c2c8fcfa57f6b27cda43db0c583d38a793c2216fa305171">
|
||||
]>
|
||||
|
||||
<PLUGIN name="&name;"
|
||||
@@ -23,6 +23,12 @@
|
||||
>
|
||||
|
||||
<CHANGES>
|
||||
### 2026.10.24.r032
|
||||
- Korrigiert Share-KiB/Bytes, trennt Dateisystembelegung vom Share-Scan und meldet unbekannte Größen als null.
|
||||
- Neue native Vorschau-/Anwenden-Werkzeuge für private SMB-Shares und sichere eigene Docker-XMLs; an Zustand gebundene Einmaltickets.
|
||||
- Neue gezielte ZFS-/SMART-/Parity-Diagnose und SMB-Berechtigungsprüfung ohne Zugangsdaten.
|
||||
- Prüft Prozess-Exitcodes, verweigert Create auf bestehenden Containern und meldet unvollständige SMART-Abdeckung ehrlich.
|
||||
|
||||
### 2026.10.12.r031
|
||||
- Setzt Shell-Prozesse und Dienststart auf das stabile Arbeitsverzeichnis /; behebt ENOENT bei gelöschtem Installationsordner.
|
||||
- Verbindungstest trennt MCP-Transport/Auth-Dispatch von lokaler Befehlsausführung; Fehler nennen Ort, Phase und kontrollierte Ursache ohne Befehle oder Secrets.
|
||||
@@ -186,7 +192,7 @@ Das .txz enthält:
|
||||
install/doinst.sh (läuft nach Installation)
|
||||
===========================================
|
||||
-->
|
||||
<FILE Name="/boot/config/plugins/&name;/mua-2026.10.12.r031-x86_64-1.txz" Run="upgradepkg --install-new" Mode="755" Min="7.0.0">
|
||||
<FILE Name="/boot/config/plugins/&name;/mua-2026.10.24.r032-x86_64-1.txz" Run="upgradepkg --install-new" Mode="755" Min="7.0.0">
|
||||
<URL>&txzURL;</URL>
|
||||
<SHA256>&txzSHA256;</SHA256>
|
||||
</FILE>
|
||||
@@ -276,6 +282,7 @@ rm -f /usr/local/bin/mua
|
||||
# 4. PHP-Helper entfernen
|
||||
rm -f /usr/local/bin/unraid-docker-mcp-helper.php
|
||||
rm -f /usr/local/bin/unraid-mcp-status-helper.php
|
||||
rm -f /usr/local/bin/unraid-admin-helper.php
|
||||
|
||||
# 5. Plugin-Verzeichnis entfernen
|
||||
rm -rf &emhttpLOC;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "mua",
|
||||
"author": "Michael",
|
||||
"version": "2026.10.12.r031",
|
||||
"version": "2026.10.24.r032",
|
||||
"minver": "7.0.0",
|
||||
"pluginDirectory": "/usr/local/emhttp/plugins/mua",
|
||||
"configDirectory": "/boot/config/plugins/mua",
|
||||
|
||||
@@ -69,6 +69,10 @@ chmod 755 "${BUILD_DIR}/usr/local/bin/unraid-docker-mcp-helper.php"
|
||||
cp "${ROOT}/scripts/unraid-mcp-status-helper.php" "${BUILD_DIR}/usr/local/bin/unraid-mcp-status-helper.php"
|
||||
chmod 755 "${BUILD_DIR}/usr/local/bin/unraid-mcp-status-helper.php"
|
||||
|
||||
# Typed share/template administration and targeted diagnostics
|
||||
cp "${ROOT}/scripts/unraid-admin-helper.php" "${BUILD_DIR}/usr/local/bin/unraid-admin-helper.php"
|
||||
chmod 755 "${BUILD_DIR}/usr/local/bin/unraid-admin-helper.php"
|
||||
|
||||
# 3. doinst.sh (läuft nach Installation)
|
||||
cat > "${BUILD_DIR}/install/doinst.sh" << 'DOEOF'
|
||||
#!/bin/bash
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
/** Explicit opt-in integration test, only its own unique temporary objects. */
|
||||
require_once __DIR__.'/unraid-admin-helper.php';
|
||||
if(($argv[1]??'')!=='--authorized-temporary-test')throw new RuntimeException('Explicit opt-in required');
|
||||
$name='MUA-r032-'.bin2hex(random_bytes(4));$container=$name.'-whoami';$image='traefik/whoami:latest';
|
||||
$shareMade=false;$containerMade=false;$imageNew=false;$ok=false;
|
||||
try {
|
||||
// Baseline exact names and image only; no global container inventory.
|
||||
$old=mua_run(['/usr/bin/docker','image','ls','--format','{{.ID}}',$image]);$imageNew=$old==='';
|
||||
$spec=['action'=>'create','name'=>$name,'pool'=>'nvme-storage','description'=>'MUA r032 integration: Michael RW / Sarah RO','access'=>['michael'=>'read-write','sarah'=>'read-only']];
|
||||
$plan=mua_plan('share',$spec);$shareMade=true;
|
||||
$r=mua_apply_plan($plan);if(!$r['ok'])throw new RuntimeException('Share apply failed');
|
||||
echo "PASS native share cfg and effective Samba RW/RO\n";
|
||||
$x=['action'=>'create','name'=>$container,'image'=>$image,'ports'=>[['host_port'=>18767,'container_port'=>80]],'memory_mb'=>64,'cpus'=>0.25,'description'=>'MUA r032 isolated native renderer test'];
|
||||
$plan=mua_plan('docker',$x);$containerMade=true;
|
||||
$r=mua_apply_plan($plan);if(!$r['ok'])throw new RuntimeException('Docker apply failed');
|
||||
$inspect=mua_json(['/usr/bin/docker','inspect',$container])[0];
|
||||
if($inspect['HostConfig']['Privileged']||$inspect['Mounts']||$inspect['HostConfig']['NetworkMode']!=='bridge'||$inspect['HostConfig']['PortBindings']['80/tcp'][0]['HostIp']!=='127.0.0.1')throw new RuntimeException('Isolation mismatch');
|
||||
echo "PASS native XML, dockerman label and exact isolation\n";
|
||||
mua_run(['/usr/bin/docker','start',$container]);
|
||||
$code=mua_run(['/usr/bin/curl','--retry','5','--retry-connrefused','--retry-delay','1','--max-time','5','-s','-o','/dev/null','-w','%{http_code}','http://127.0.0.1:18767/bench']);
|
||||
if($code!=='200')throw new RuntimeException('HTTP test failed');
|
||||
echo "PASS HTTP 200\n";
|
||||
// A running container must not be removable through the typed operation.
|
||||
try {mua_plan('docker',['action'=>'remove','name'=>$container,'remove_template'=>true]);throw new LogicException('Running removal allowed');}
|
||||
catch(RuntimeException $e){if($e instanceof LogicException)throw $e;if(!str_contains($e->getMessage(),'Stop container'))throw $e;}
|
||||
echo "PASS running-container removal refused\n";
|
||||
$ok=true;
|
||||
} finally {
|
||||
if($containerMade){
|
||||
$rows=mua_run(['/usr/bin/docker','ps','-a','--filter','name=^/'.$container.'$','--format','{{.ID}}']);
|
||||
if($rows!==''){
|
||||
$status=mua_run(['/usr/bin/docker','inspect','--format','{{.State.Status}}',$container]);
|
||||
if($status==='running')mua_run(['/usr/bin/docker','stop',$container]);
|
||||
mua_apply_plan(mua_plan('docker',['action'=>'remove','name'=>$container,'remove_template'=>true]));
|
||||
}elseif(is_file(mua_template_path($container)))unlink(mua_template_path($container));
|
||||
}
|
||||
if($shareMade&&is_file(mua_cfg($name)))mua_apply_plan(mua_plan('share',['action'=>'remove','name'=>$name]));
|
||||
if($imageNew && mua_run(['/usr/bin/docker','image','ls','--format','{{.ID}}',$image])!=='')mua_run(['/usr/bin/docker','image','rm',$image]);
|
||||
if(is_file(mua_cfg($name))||file_exists('/mnt/user/'.$name)||file_exists('/mnt/nvme-storage/'.$name)||is_file(mua_template_path($container)))throw new RuntimeException('Own artifacts remain');
|
||||
if(mua_run(['/usr/bin/docker','ps','-a','--filter','name=^/'.$container.'$','--format','{{.ID}}'])!=='')throw new RuntimeException('Container remains');
|
||||
if(mua_run(['/usr/sbin/ss','-Hlnt','sport = :18767'])!=='')throw new RuntimeException('Listener remains');
|
||||
echo "PASS cleanup own share/container/template and new unshared image\n";
|
||||
}
|
||||
if(!$ok)exit(1);
|
||||
echo "LIVE PASS: $name (configuration tested, no authenticated SMB login)\n";
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
require_once __DIR__.'/unraid-admin-helper.php';
|
||||
require_once __DIR__.'/unraid-mcp-status-helper.php';
|
||||
$count=0;
|
||||
function check_admin(string $name,bool $condition): void {global $count;if(!$condition)throw new RuntimeException('FAIL: '.$name);$count++;echo "PASS: $name\n";}
|
||||
function rejects_admin(string $name,callable $f): void {try{$f();}catch(Throwable){check_admin($name,true);return;}check_admin($name,false);}
|
||||
$root=sys_get_temp_dir().'/mua-fixtures-'.bin2hex(random_bytes(8));
|
||||
$GLOBALS['mua_test_root']=$root;
|
||||
foreach(['/var/local/emhttp','/boot/config/shares','/boot/config/plugins/dockerMan/templates-user','/mnt/nvme-test','/mnt/user','/var/lock'] as $dir)mkdir($root.$dir,0700,true);
|
||||
try {
|
||||
file_put_contents($root.'/var/local/emhttp/users.ini',"[root]\nidx=7\npassword=never-output\n[michael]\nidx=3\n[sarah]\nidx=8\n");
|
||||
check_admin('user discovery excludes credentials and root',json_encode(mua_users())==='[{"name":"michael","index":3},{"name":"sarah","index":8}]');
|
||||
rejects_admin('protected targets rejected',fn()=>mua_name('OpenVPN-KIT'));
|
||||
rejects_admin('traversal rejected',fn()=>mua_name('../other'));
|
||||
rejects_admin('unknown SMB user rejected',fn()=>mua_private_spec(['action'=>'create','name'=>'test','pool'=>'nvme-test','access'=>['nobody'=>'read-write']]));
|
||||
$spec=mua_private_spec(['action'=>'create','name'=>'test','pool'=>'nvme-test','access'=>['michael'=>'read-write','sarah'=>'read-only'],'description'=>'Test']);
|
||||
$plan=mua_plan('share',$spec);
|
||||
$queries=[];
|
||||
$GLOBALS['mua_test_run']=function(array $argv)use(&$queries,$root){
|
||||
if(basename($argv[0])==='testparm')return "[test]\nvalid users = michael sarah\nwrite list = michael\nread list = sarah";
|
||||
if(basename($argv[0])!=='emcmd')throw new RuntimeException('Unexpected test command');
|
||||
parse_str($argv[1],$q);$queries[]=$argv[1];
|
||||
if(isset($q['cmdEditShare'])&&$q['cmdEditShare']==='Add Share') {mkdir($root.'/mnt/user/test');file_put_contents(mua_cfg('test'),"shareExport=\"-\"\nshareSecurity=\"public\"\n");}
|
||||
if(isset($q['changeShareSecurity']))file_put_contents(mua_cfg('test'),"shareExport=\"".$q['shareExport']."\"\nshareSecurity=\"private\"\nshareReadList=\"sarah\"\nshareWriteList=\"michael\"\n");
|
||||
return '';
|
||||
};
|
||||
$result=mua_apply_plan($plan);
|
||||
check_admin('share creation verified without real host changes',$result['ok']===true);
|
||||
$joined=implode("\n",$queries);
|
||||
check_admin('current indices used including nonzero root index',str_contains($joined,'userAccess.3=read-write')&&str_contains($joined,'userAccess.8=read-only')&&str_contains($joined,'userAccess.7=no-access'));
|
||||
file_put_contents(mua_cfg('test'),str_replace('shareExport="e"','shareExport="-"',file_get_contents(mua_cfg('test'))));
|
||||
$permissions=mua_plan('share',['action'=>'permissions','name'=>'test','access'=>['michael'=>'read-write','sarah'=>'read-only']]);
|
||||
check_admin('permissions preview preserves disabled export',$permissions['spec']['export']==='-');
|
||||
mua_apply_plan($permissions);
|
||||
check_admin('permissions change does not enable disabled SMB',str_contains(file_get_contents(mua_cfg('test')),'shareExport="-"'));
|
||||
rejects_admin('stale create preview refused',fn()=>mua_apply_plan($plan));
|
||||
file_put_contents($root.'/mnt/user/test/keep.txt','must remain');
|
||||
rejects_admin('nonempty delete refused',fn()=>mua_plan('share',['action'=>'remove','name'=>'test']));
|
||||
check_admin('nonempty share data untouched',file_get_contents($root.'/mnt/user/test/keep.txt')==='must remain');
|
||||
unlink($root.'/mnt/user/test/keep.txt');
|
||||
$remove=mua_plan('share',['action'=>'remove','name'=>'test']);
|
||||
file_put_contents(mua_cfg('test'),"changed=1\n");
|
||||
rejects_admin('changed config invalidates removal preview',fn()=>mua_apply_plan($remove));
|
||||
$row=share_entry(['name'=>'appdata','size'=>'0','free'=>'5116038016','used'=>'2564191488'],true);
|
||||
check_admin('share free matches exact independent df bytes',$row['free_bytes']===5238822928384);
|
||||
check_admin('share backing used matches df not dataset size',$row['filesystem_used_bytes']===2625732083712);
|
||||
check_admin('unknown share size and percentage are null',$row['share_size_bytes']===null&&$row['used_percent']===null&&$row['used_bytes']===null);
|
||||
check_admin('nonzero ambiguous size is not misreported as share contents',share_entry(['size'=>'123','free'=>'100','used'=>'20'],false)['share_size_bytes']===null);
|
||||
$missing=share_entry([],false);check_admin('missing capacity is unknown not zero',$missing['free_bytes']===null&&$missing['filesystem_size_bytes']===null);
|
||||
$d=mua_docker_spec(['action'=>'create','name'=>'native-test','image'=>'traefik/whoami:v1.11','ports'=>[['host_port'=>18766,'container_port'=>80]]]);
|
||||
$xml=mua_template_xml($d);$dom=simplexml_load_string($xml);
|
||||
check_admin('native XML v2 with empty update URL',(string)$dom['version']==='2'&&(string)$dom->TemplateURL==='');
|
||||
check_admin('loopback binding and no manual managed label',str_contains($xml,'127.0.0.1:18766')&&!str_contains($xml,'net.unraid.docker.managed'));
|
||||
check_admin('unprivileged template without mounts',(string)$dom->Privileged==='false'&&count($dom->xpath('//Config[@Type="Path"]'))===0);
|
||||
rejects_admin('image shell injection refused',fn()=>mua_docker_spec(['action'=>'create','name'=>'test','image'=>'alpine;touch /bad']));
|
||||
rejects_admin('duplicate host port refused',fn()=>mua_docker_spec(['action'=>'create','name'=>'test','image'=>'alpine:3','ports'=>[['host_port'=>18766,'container_port'=>80],['host_port'=>18766,'container_port'=>81]]]));
|
||||
rejects_admin('invalid resources refused',fn()=>mua_docker_spec(['action'=>'create','name'=>'test','image'=>'alpine:3','memory_mb'=>0]));
|
||||
echo "TOTAL: $count checks\n";
|
||||
} finally {
|
||||
$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach($it as $f){if($f->isDir())rmdir($f->getPathname());else unlink($f->getPathname());}rmdir($root);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
/** Typed native Unraid administration. No arbitrary XML, shell or passwords. */
|
||||
declare(strict_types=1);
|
||||
|
||||
function mua_path(string $path): string { return ($GLOBALS['mua_test_root'] ?? '') . $path; }
|
||||
function mua_name(mixed $name): string {
|
||||
if (!is_string($name) || !preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $name)) throw new RuntimeException('Invalid exact target name');
|
||||
if (in_array(strtolower($name), ['openvpn-kit', 'gluetunvpn', 'vpn.auth'], true)) throw new RuntimeException('Protected target');
|
||||
return $name;
|
||||
}
|
||||
function mua_run(array $argv, array $allowedCodes = [0]): string {
|
||||
if (isset($GLOBALS['mua_test_run'])) return ($GLOBALS['mua_test_run'])($argv);
|
||||
$p = proc_open($argv, [0=>['pipe','r'],1=>['pipe','w'],2=>['pipe','w']], $pipes, '/');
|
||||
if (!is_resource($p)) throw new RuntimeException('Process start failed');
|
||||
fclose($pipes[0]);
|
||||
// Drain both streams concurrently, bounded in memory. Parent enforces timeout.
|
||||
stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false);
|
||||
$out=''; $err='';
|
||||
while (!feof($pipes[1]) || !feof($pipes[2])) {
|
||||
$r=[]; foreach ([1,2] as $i) if (!feof($pipes[$i])) $r[]=$pipes[$i];
|
||||
if (!$r) break;
|
||||
$w=null;$e=null;stream_select($r,$w,$e,1);
|
||||
foreach ($r as $f) { $v=fread($f,8192); if ($f===$pipes[1]) $out=substr($out.$v,0,131072); else $err=substr($err.$v,0,4096); }
|
||||
}
|
||||
fclose($pipes[1]);fclose($pipes[2]);$rc=proc_close($p);
|
||||
if (!in_array($rc,$allowedCodes,true)) throw new RuntimeException(basename($argv[0]).' failed (exit '.$rc.'): '.substr($err,0,1000));
|
||||
return trim($out);
|
||||
}
|
||||
function mua_json(array $argv): array {
|
||||
$v=json_decode(mua_run($argv),true,512,JSON_THROW_ON_ERROR);
|
||||
if (!is_array($v)) throw new RuntimeException('Unexpected command JSON'); return $v;
|
||||
}
|
||||
function mua_users(bool $includeRoot=false): array {
|
||||
$rows=parse_ini_file(mua_path('/var/local/emhttp/users.ini'),true,INI_SCANNER_RAW);
|
||||
if (!is_array($rows)) throw new RuntimeException('User metadata unavailable');
|
||||
$out=[]; foreach ($rows as $name=>$row) { $name=trim((string)$name,'"'); if (($includeRoot || $name!=='root') && isset($row['idx']) && ctype_digit((string)$row['idx'])) $out[]=['name'=>$name,'index'=>(int)$row['idx']]; }
|
||||
return $out;
|
||||
}
|
||||
function mua_cfg(string $name): string { return mua_path('/boot/config/shares/'.mua_name($name).'.cfg'); }
|
||||
function mua_private_spec(array $x): array {
|
||||
$name=mua_name($x['name']??null);$action=$x['action']??'';
|
||||
if (!in_array($action,['create','permissions','remove'],true)) throw new RuntimeException('Invalid share action');
|
||||
$out=['action'=>$action,'name'=>$name];
|
||||
if ($action==='remove') return $out;
|
||||
$access=$x['access']??null;
|
||||
if (!is_array($access) || !$access || count($access)>64) throw new RuntimeException('Explicit access map required');
|
||||
$users=array_column(mua_users(),'index','name');
|
||||
foreach ($access as $user=>$mode) {
|
||||
if (!isset($users[$user]) || !in_array($mode,['read-write','read-only'],true)) throw new RuntimeException('Unknown user or access mode');
|
||||
}
|
||||
ksort($access);$out['access']=$access;
|
||||
$out['security']='private';
|
||||
$out['export']='e';
|
||||
if ($action==='permissions') {
|
||||
$cfg=mua_cfg($name);if(!is_file($cfg)||is_link($cfg))throw new RuntimeException('Share configuration missing or symlink');
|
||||
$current=parse_ini_file($cfg,false,INI_SCANNER_RAW);$out['export']=$current['shareExport']??'-';
|
||||
if(!in_array($out['export'],['e','eh','-'],true))throw new RuntimeException('Unsupported existing export mode');
|
||||
}
|
||||
if ($action==='create') {
|
||||
$out['pool']=mua_name($x['pool']??null);
|
||||
if (!is_dir(mua_path('/mnt/'.$out['pool'])) || in_array($out['pool'],['user','user0','disks','remotes'],true) || preg_match('/^disk\d+$/',$out['pool'])) throw new RuntimeException('Existing named pool required');
|
||||
$comment=$x['description']??'';
|
||||
if (!is_string($comment) || strlen($comment)>500 || preg_match('/[\x00-\x1f]/',$comment)) throw new RuntimeException('Invalid description');
|
||||
$out['description']=$comment;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
function mua_share_empty(string $path): bool {
|
||||
if (!is_dir($path) || is_link($path)) return false;
|
||||
$it=new FilesystemIterator($path,FilesystemIterator::SKIP_DOTS);return !$it->valid();
|
||||
}
|
||||
function mua_share_state(array $x): array {
|
||||
$cfg=mua_cfg($x['name']);$exists=is_file($cfg);
|
||||
if (is_link($cfg)) throw new RuntimeException('Symlink configuration refused');
|
||||
$state=['config_exists'=>$exists,'config_sha256'=>$exists?hash_file('sha256',$cfg):null];
|
||||
$path=mua_path('/mnt/user/'.$x['name']);
|
||||
$state['path_exists']=file_exists($path);$state['empty']=$state['path_exists']?mua_share_empty($path):null;
|
||||
if ($x['action']==='create' && ($exists||$state['path_exists'])) throw new RuntimeException('Share already exists');
|
||||
if ($x['action']!=='create' && !$exists) throw new RuntimeException('Share configuration missing');
|
||||
if ($x['action']==='remove' && $state['empty']!==true) throw new RuntimeException('Only existing empty shares can be removed');
|
||||
if ($x['action']!=='remove') $state['users']=mua_users(true);
|
||||
return $state;
|
||||
}
|
||||
function mua_share_rights(string $name): array {
|
||||
$p=mua_cfg($name);if (!is_file($p)) throw new RuntimeException('Share configuration missing');
|
||||
$c=parse_ini_file($p,false,INI_SCANNER_RAW);
|
||||
$out=[];foreach (['shareComment','shareExport','shareSecurity','shareReadList','shareWriteList','shareCachePool','shareUseCache'] as $key) $out[$key]=$c[$key]??null;
|
||||
$out['effective_smb_section']=$out['shareExport']==='-'?'':mua_run(['/usr/bin/testparm','-s','--section-name='.$name]);
|
||||
$out['verification']='configuration_only_not_authenticated_smb';return $out;
|
||||
}
|
||||
function mua_emcmd(array $params): void {
|
||||
$q=http_build_query($params);if ($q==='') throw new RuntimeException('Empty native action');
|
||||
mua_run(['/usr/local/sbin/emcmd',$q]);
|
||||
}
|
||||
function mua_share_apply(array $x): array {
|
||||
$name=$x['name'];$stages=[];
|
||||
try {
|
||||
if ($x['action']==='remove') {
|
||||
if (!mua_share_empty(mua_path('/mnt/user/'.$name))) throw new RuntimeException('Share became nonempty');
|
||||
mua_emcmd(['cmdEditShare'=>'Delete','shareName'=>$name,'shareNameOrig'=>$name,'confirmDelete'=>'on']);$stages[]='native_delete';
|
||||
if (file_exists(mua_cfg($name)) || file_exists(mua_path('/mnt/user/'.$name))) throw new RuntimeException('Share removal incomplete');
|
||||
return ['ok'=>true,'name'=>$name,'removed'=>true,'stages'=>$stages];
|
||||
}
|
||||
if ($x['action']==='create') {
|
||||
mua_emcmd(['cmdEditShare'=>'Add Share','shareName'=>$name,'shareNameOrig'=>'','shareComment'=>$x['description'],'shareUseCache'=>'only','shareCachePool'=>$x['pool'],'shareCachePool2'=>'','shareAllocator'=>'highwater','shareSplitLevel'=>'','shareInclude'=>'','shareExclude'=>'','shareCOW'=>'auto','shareFloor'=>'0']);$stages[]='native_create';
|
||||
if (!is_file(mua_cfg($name))) throw new RuntimeException('Native create did not produce configuration');
|
||||
}
|
||||
$security=['changeShareSecurity'=>'Apply','shareName'=>$name,'shareExport'=>'-','shareSecurity'=>'private','shareCaseSensitive'=>'auto','shareVolsizelimit'=>''];
|
||||
mua_emcmd($security);$stages[]='private_export_disabled';
|
||||
$access=['changeShareAccess'=>'Apply','shareName'=>$name];
|
||||
foreach (mua_users(true) as $user) $access['userAccess.'.$user['index']]=$x['access'][$user['name']]??'no-access';
|
||||
mua_emcmd($access);$stages[]='access_set';
|
||||
$security['shareExport']=$x['export'];mua_emcmd($security);$stages[]='export_restored_or_enabled';
|
||||
$v=mua_share_rights($name);
|
||||
$wantRead=array_keys(array_filter($x['access'],fn($v)=>$v==='read-only'));
|
||||
$wantWrite=array_keys(array_filter($x['access'],fn($v)=>$v==='read-write'));
|
||||
$list=fn($v)=>array_values(array_filter(preg_split('/[\s,]+/',trim((string)$v))?:[]));
|
||||
$read=$list($v['shareReadList']);$write=$list($v['shareWriteList']);sort($read);sort($write);sort($wantRead);sort($wantWrite);
|
||||
if ($v['shareSecurity']!=='private'||$v['shareExport']!==$x['export']||$read!==$wantRead||$write!==$wantWrite) throw new RuntimeException('Rights readback mismatch');
|
||||
$effective=[];
|
||||
foreach(explode("\n",$v['effective_smb_section']) as $line)if(preg_match('/^\s*(valid users|read list|write list)\s*=\s*(.*)$/',$line,$m)){$effective[$m[1]]=$list($m[2]);sort($effective[$m[1]]);}
|
||||
$wantUsers=array_keys($x['access']);sort($wantUsers);
|
||||
if($x['export']!=='-' && (($effective['valid users']??[])!==$wantUsers||($effective['write list']??[])!==$wantWrite||($effective['read list']??[])!==$wantRead))throw new RuntimeException('Effective Samba rights do not match request');
|
||||
return ['ok'=>true,'name'=>$name,'stages'=>$stages,'verification'=>$v];
|
||||
} catch (Throwable $e) {
|
||||
// Do not erase data or attempt speculative rollback; fail closed on SMB export.
|
||||
if ($x['action']!=='remove' && is_file(mua_cfg($name))) {
|
||||
try {mua_emcmd(['changeShareSecurity'=>'Apply','shareName'=>$name,'shareExport'=>'-','shareSecurity'=>'private','shareCaseSensitive'=>'auto','shareVolsizelimit'=>'']);$stages[]='failure_export_disabled';} catch (Throwable) {$stages[]='failure_export_disable_failed';}
|
||||
}
|
||||
throw new RuntimeException(json_encode(['ok'=>false,'stages'=>$stages,'error'=>$e->getMessage(),'partial_state'=>'inspect exact target before retry'],JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
function mua_template_path(string $name): string {return mua_path('/boot/config/plugins/dockerMan/templates-user/my-'.mua_name($name).'.xml');}
|
||||
function mua_docker_spec(array $x): array {
|
||||
$action=$x['action']??'';$name=mua_name($x['name']??null);
|
||||
if (!in_array($action,['create','remove'],true)) throw new RuntimeException('Invalid Docker action');
|
||||
if ($action==='remove') return ['action'=>$action,'name'=>$name,'remove_template'=>($x['remove_template']??false)===true];
|
||||
$image=$x['image']??'';
|
||||
if (!is_string($image)||strlen($image)>300||!preg_match('/^[a-z0-9][a-z0-9._:\/\-]*(?:@sha256:[a-f0-9]{64})?$/D',$image)||str_contains($image,'..')) throw new RuntimeException('Invalid image reference');
|
||||
$ports=$x['ports']??[];if (!is_array($ports)||count($ports)>8) throw new RuntimeException('At most 8 ports');
|
||||
$seen=[];
|
||||
foreach ($ports as &$p) {
|
||||
if (!is_array($p)) throw new RuntimeException('Invalid port');
|
||||
foreach (['host_port','container_port'] as $k) { $value=$p[$k]??null; if (!is_int($value)||$value<($k==='host_port'?1024:1)||$value>65535) throw new RuntimeException('Invalid port range'); }
|
||||
$p=['host_port'=>$p['host_port'],'container_port'=>$p['container_port'],'protocol'=>$p['protocol']??'tcp'];
|
||||
if (!in_array($p['protocol'],['tcp','udp'],true)) throw new RuntimeException('Invalid protocol');
|
||||
$key=$p['host_port'].'/'.$p['protocol'];if(isset($seen[$key]))throw new RuntimeException('Duplicate port');$seen[$key]=true;
|
||||
} unset($p);
|
||||
$mem=$x['memory_mb']??128;$cpu=$x['cpus']??0.5;
|
||||
if (!is_int($mem)||$mem<32||$mem>2048||!is_numeric($cpu)||$cpu<0.1||$cpu>4) throw new RuntimeException('Invalid resource limits');
|
||||
$description=$x['description']??'';if(!is_string($description)||strlen($description)>1000||str_contains($description,"\0"))throw new RuntimeException('Invalid description');
|
||||
return ['action'=>$action,'name'=>$name,'image'=>$image,'ports'=>$ports,'memory_mb'=>$mem,'cpus'=>(float)$cpu,'description'=>$description];
|
||||
}
|
||||
function mua_template_xml(array $x): string {
|
||||
$d=new DOMDocument('1.0','utf-8');$r=$d->appendChild($d->createElement('Container'));$r->setAttribute('version','2');
|
||||
foreach (['Name'=>$x['name'],'Repository'=>$x['image'],'Network'=>'bridge','Privileged'=>'false','TailscaleEnabled'=>'false','Overview'=>$x['description'],'TemplateURL'=>'','WebUI'=>'','ExtraParams'=>'--restart=no --memory='.$x['memory_mb'].'m --cpus='.$x['cpus']] as $k=>$v) {$e=$r->appendChild($d->createElement($k));$e->appendChild($d->createTextNode($v));}
|
||||
foreach (['Registry','Icon','Support','Project','ReadMe','Category','MyIP','MyMAC','PostArgs','CPUset','DonateText','DonateLink','Requires'] as $k) $r->appendChild($d->createElement($k));
|
||||
$r->appendChild($d->createElement('Shell','sh'));
|
||||
foreach ($x['ports'] as $p) {
|
||||
$e=$r->appendChild($d->createElement('Config','127.0.0.1:'.$p['host_port']));
|
||||
foreach (['Name'=>'Port '.$p['container_port'],'Target'=>(string)$p['container_port'],'Type'=>'Port','Mode'=>$p['protocol'],'Default'=>'127.0.0.1:'.$p['host_port']] as $k=>$v) $e->setAttribute($k,$v);
|
||||
}
|
||||
return $d->saveXML();
|
||||
}
|
||||
function mua_native_render(string $xml): array {
|
||||
global $docroot,$var,$driver,$subnet;
|
||||
$docroot='/usr/local/emhttp';$var=['timeZone'=>'Europe/Berlin','NAME'=>gethostname()];$driver=['bridge'=>'bridge'];$subnet=['bridge'=>''];
|
||||
require_once "$docroot/plugins/dynamix.docker.manager/include/Helpers.php";
|
||||
return xmlToCommand($xml,false);
|
||||
}
|
||||
function mua_docker_state(array $x): array {
|
||||
$p=mua_template_path($x['name']);if(is_link($p))throw new RuntimeException('Symlink template refused');
|
||||
// Exact-name filtering avoids inspecting unrelated containers.
|
||||
$rows=mua_run(['/usr/bin/docker','ps','-a','--filter','name=^/'.$x['name'].'$','--format','{{.ID}}']);
|
||||
$state=['container_id'=>$rows?:null,'template_sha256'=>is_file($p)?hash_file('sha256',$p):null];
|
||||
if ($x['action']==='create') {
|
||||
if ($rows!==''||is_file($p)) throw new RuntimeException('Target already exists');
|
||||
$xml=mua_template_xml($x);[$cmd,$name,$repo]=mua_native_render($xml);
|
||||
if ($name!==$x['name']||$repo!==$x['image']||!str_contains($cmd,'net.unraid.docker.managed=dockerman')) throw new RuntimeException('Native rendering mismatch');
|
||||
foreach($x['ports'] as $port) {
|
||||
$flags=$port['protocol']==='tcp'?'-Hlnt':'-Hlnu';
|
||||
if(mua_run(['/usr/sbin/ss',$flags,'sport = :'.$port['host_port']])!=='')throw new RuntimeException('Requested loopback host port is occupied');
|
||||
}
|
||||
$state['xml_sha256']=hash('sha256',$xml);
|
||||
$state['rendered_command']=$cmd;
|
||||
} else {
|
||||
if ($rows==='') throw new RuntimeException('Exact container not found');
|
||||
if($x['remove_template'] && is_file($p)) {
|
||||
$template=simplexml_load_file($p);
|
||||
if($template===false || (string)$template->Name!==$x['name'])throw new RuntimeException('Template does not belong to target');
|
||||
}
|
||||
$state['image_id']=mua_run(['/usr/bin/docker','inspect','--format','{{.Image}}',$x['name']]);
|
||||
$state['status']=mua_run(['/usr/bin/docker','inspect','--format','{{.State.Status}}',$x['name']]);
|
||||
if (!in_array($state['status'],['created','exited'],true)) throw new RuntimeException('Stop container explicitly before removal');
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
function mua_docker_apply(array $x): array {
|
||||
$name=$x['name'];$p=mua_template_path($name);$stages=[];
|
||||
try {
|
||||
if($x['action']==='remove') {
|
||||
mua_run(['/usr/bin/docker','rm',$name]);$stages[]='container_removed';
|
||||
if($x['remove_template']&&is_file($p)){if(!unlink($p))throw new RuntimeException('Template deletion failed');$stages[]='template_removed';}
|
||||
return ['ok'=>true,'stages'=>$stages,'image_retained'=>true,'volumes_retained'=>true];
|
||||
}
|
||||
$xml=mua_template_xml($x);[$cmd,$n,$repo]=mua_native_render($xml);
|
||||
if($n!==$name||$repo!==$x['image'])throw new RuntimeException('Render mismatch');
|
||||
// Pull before writing or creating anything. Never delete/rebuild an existing target.
|
||||
mua_run(['/usr/bin/docker','pull',$repo]);$stages[]='image_pulled';
|
||||
$f=fopen($p,'x');if(!$f)throw new RuntimeException('Exclusive template creation failed');
|
||||
if(fwrite($f,$xml)!==strlen($xml)){fclose($f);throw new RuntimeException('Template write incomplete');}fclose($f);chmod($p,0600);$stages[]='template_written';
|
||||
// The command comes exclusively from our structured XML and Unraid's renderer.
|
||||
mua_run(['/bin/sh','-c',$cmd]);$stages[]='container_created';
|
||||
$label=mua_run(['/usr/bin/docker','inspect','--format','{{index .Config.Labels "net.unraid.docker.managed"}}',$name]);
|
||||
if($label!=='dockerman')throw new RuntimeException('Native manager label not confirmed');
|
||||
return ['ok'=>true,'name'=>$name,'stages'=>$stages,'started'=>false,'gui_managed'=>true,'template'=>$p,'image_id'=>mua_run(['/usr/bin/docker','inspect','--format','{{.Image}}',$name]),'verification'=>'native_backend_not_visual_gui'];
|
||||
} catch(Throwable $e){throw new RuntimeException(json_encode(['ok'=>false,'stages'=>$stages,'error'=>$e->getMessage(),'partial_state'=>'own image/template/container may remain; inspect target, do not blindly retry']));}
|
||||
}
|
||||
function mua_plan(string $kind,array $input): array {
|
||||
$x=$kind==='share'?mua_private_spec($input):mua_docker_spec($input);
|
||||
$state=$kind==='share'?mua_share_state($x):mua_docker_state($x);
|
||||
return ['kind'=>$kind,'spec'=>$x,'before'=>$state];
|
||||
}
|
||||
function mua_apply_plan(array $plan): array {
|
||||
$name=mua_name($plan['spec']['name']);$lock=fopen(mua_path('/var/lock/mua-admin-'.hash('sha256',$plan['kind'].':'.$name).'.lock'),'c');
|
||||
if(!$lock||!flock($lock,LOCK_EX|LOCK_NB))throw new RuntimeException('Target busy');
|
||||
try {
|
||||
$now=mua_plan($plan['kind'],$plan['spec']);
|
||||
if($now!==$plan)throw new RuntimeException('Target state changed; request a fresh preview');
|
||||
return $plan['kind']==='share'?mua_share_apply($plan['spec']):mua_docker_apply($plan['spec']);
|
||||
}finally{flock($lock,LOCK_UN);fclose($lock);}
|
||||
}
|
||||
function mua_diagnostics(array $x): array {
|
||||
$action=$x['action']??'';
|
||||
if($action==='parity_history'){
|
||||
$p=mua_path('/boot/config/parity-checks.log');$rows=[];
|
||||
if(is_readable($p)){ $f=new SplFileObject($p);foreach($f as $line){if(trim((string)$line)!=='')$rows[]=substr(trim($line),0,1000);if(count($rows)>20)array_shift($rows);} }
|
||||
return ['source'=>'unraid_parity_history','available'=>is_readable($p),'records'=>$rows,'note'=>'Native records; missing history does not establish a successful check.'];
|
||||
}
|
||||
if($action==='zfs_pool'){$name=mua_name($x['target']??null);return ['source'=>'zpool','target'=>$name,'status'=>mua_run(['/usr/sbin/zpool','status','-p',$name])];}
|
||||
if($action==='zfs_dataset'){
|
||||
$name=$x['target']??'';if(!is_string($name)||!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,200}$/D',$name)||str_contains($name,'..')||str_contains(strtolower($name),'openvpn'))throw new RuntimeException('Invalid dataset');
|
||||
return ['source'=>'zfs','target'=>$name,'properties'=>mua_run(['/usr/sbin/zfs','list','-Hp','-o','name,used,refer,available,usedbysnapshots,mountpoint',$name])];
|
||||
}
|
||||
if($action==='zfs_snapshots'){
|
||||
$name=$x['target']??'';if(!is_string($name)||!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,200}$/D',$name)||str_contains($name,'..')||str_contains(strtolower($name),'openvpn'))throw new RuntimeException('Invalid dataset');
|
||||
$raw=mua_run(['/usr/sbin/zfs','list','-Hp','-r','-d','1','-t','snapshot','-S','creation','-o','name,used,creation',$name]);
|
||||
$rows=$raw===''?[]:explode("\n",$raw);
|
||||
return ['source'=>'zfs_snapshots','target'=>$name,'records'=>array_slice($rows,0,20),'limited'=>count($rows)>20,'order'=>'newest_first'];
|
||||
}
|
||||
if($action==='smart'){
|
||||
$name=mua_name($x['target']??null);$rows=parse_ini_file(mua_path('/var/local/emhttp/disks.ini'),true,INI_SCANNER_RAW);$device=null;
|
||||
foreach($rows?:[] as $key=>$row)if(trim((string)($row['name']??$key),'"')===$name)$device=$row['device']??null;
|
||||
if(!is_string($device)||!preg_match('/^(?:sd[a-z]+|nvme[0-9]+n[0-9]+)$/D',$device))throw new RuntimeException('Known physical disk required');
|
||||
// smartctl uses exit bits 3-7 for health findings, not execution failures.
|
||||
$raw=mua_run(['/usr/sbin/smartctl','-a','-j','-n','standby','/dev/'.$device],range(0,255));
|
||||
$v=json_decode($raw,true,512,JSON_THROW_ON_ERROR);
|
||||
$out=['source'=>'smartctl_json','disk'=>$name,'device'=>$device];
|
||||
foreach(['smartctl','smart_status','temperature','power_on_time','ata_smart_attributes','nvme_smart_health_information_log','ata_smart_self_test_log'] as $k)if(isset($v[$k]))$out[$k]=$v[$k];
|
||||
return $out;
|
||||
}
|
||||
throw new RuntimeException('Unknown diagnostic action');
|
||||
}
|
||||
if(realpath($_SERVER['SCRIPT_FILENAME']??'')===__FILE__){
|
||||
try{
|
||||
$mode=$argv[1]??'';$x=json_decode($argv[2]??'{}',true,512,JSON_THROW_ON_ERROR);
|
||||
$out=match($mode){'share-users'=>mua_users(),'share-rights'=>mua_share_rights(mua_name($x['name']??null)),'share-plan'=>mua_plan('share',$x),'docker-plan'=>mua_plan('docker',$x),'apply'=>mua_apply_plan($x),'diagnostics'=>mua_diagnostics($x),default=>throw new RuntimeException('Unknown admin action')};
|
||||
echo json_encode($out,JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR),"\n";
|
||||
}catch(Throwable $e){fwrite(STDERR,json_encode(['ok'=>false,'error'=>$e->getMessage()],JSON_INVALID_UTF8_SUBSTITUTE)."\n");exit(1);}
|
||||
}
|
||||
@@ -55,7 +55,8 @@ function fail(string $msg): never {
|
||||
function docker_exec(string $cmd): string {
|
||||
$proc = popen("/usr/bin/docker $cmd 2>&1", 'r');
|
||||
$output = stream_get_contents($proc);
|
||||
pclose($proc);
|
||||
$rc = pclose($proc);
|
||||
if ($rc !== 0) throw new RuntimeException("Docker command failed (exit $rc): " . substr(trim($output), 0, 2000));
|
||||
return trim($output);
|
||||
}
|
||||
|
||||
@@ -77,7 +78,7 @@ function rebuild_container(string $name, bool $pull_image = false, bool $force_s
|
||||
// Pull image if requested
|
||||
if ($pull_image) {
|
||||
out("Pulling image: $Repository");
|
||||
$pull_out = docker_exec("pull $Repository");
|
||||
$pull_out = docker_exec('pull ' . escapeshellarg($Repository));
|
||||
if (strpos($pull_out, 'Error') !== false || strpos($pull_out, 'error') !== false) {
|
||||
fail("Image pull failed: $pull_out");
|
||||
}
|
||||
@@ -444,6 +445,8 @@ switch ($action) {
|
||||
case 'create':
|
||||
if (!$arg1) fail("Missing template name");
|
||||
out("Creating container from template: $arg1");
|
||||
$existing = docker_exec('ps -a --filter ' . escapeshellarg('name=^/' . $arg1 . '$') . ' --format ' . escapeshellarg('{{.Names}}'));
|
||||
if ($existing !== '') fail('Container already exists; use explicit rebuild/update instead');
|
||||
rebuild_container($arg1, true);
|
||||
break;
|
||||
|
||||
|
||||
@@ -166,7 +166,10 @@ function disk_health(?string $requested): array {
|
||||
if ($requested !== null && $requested !== '' && $name !== $requested) continue;
|
||||
$entry = selected_disk($disk);
|
||||
$entry['smart_attributes'] = smart_attributes($name);
|
||||
$entry['healthy'] = number_value($disk['numErrors'] ?? 0) === 0 && !in_array($disk['status'] ?? '', ['DISK_DSBL', 'DISK_NP'], true);
|
||||
$entry['array_io_ok'] = isset($disk['numErrors'], $disk['status']) ? (number_value($disk['numErrors']) === 0 && !in_array($disk['status'], ['DISK_DSBL', 'DISK_NP'], true)) : null;
|
||||
$entry['smart_coverage'] = count($entry['smart_attributes']) > 0 ? 'partial_cached_ata_attributes' : 'unavailable';
|
||||
$entry['healthy'] = $entry['array_io_ok'] === false ? false : null;
|
||||
$entry['health_note'] = 'Array state is not a complete SMART assessment; use targeted smart diagnostics.';
|
||||
$result[] = $entry;
|
||||
}
|
||||
if ($requested && count($result) === 0) fail_status('Unknown disk name');
|
||||
@@ -231,16 +234,27 @@ function notification_list(int $limit, ?string $importance): array {
|
||||
}
|
||||
|
||||
function share_entry(array $share, bool $details): array {
|
||||
$size = number_value($share['size'] ?? 0);
|
||||
$used = number_value($share['used'] ?? 0);
|
||||
// shares.ini free/used describe backing filesystem space, in KiB.
|
||||
// The share size is calculated separately by Unraid share_size; do not infer it from these fields.
|
||||
$size = null; // No share-content scan is performed by this metadata-only endpoint.
|
||||
$free = is_numeric($share['free'] ?? null) ? number_value($share['free']) * 1024 : null;
|
||||
$used = is_numeric($share['used'] ?? null) ? number_value($share['used']) * 1024 : null;
|
||||
$total = $free !== null && $used !== null ? $free + $used : null;
|
||||
$entry = [
|
||||
'name' => $share['name'] ?? '',
|
||||
'pool' => $share['cachePool'] ?? '',
|
||||
'secondary_pool' => $share['cachePool2'] ?? '',
|
||||
'size_bytes' => $size,
|
||||
'used_bytes' => $used,
|
||||
'free_bytes' => number_value($share['free'] ?? 0),
|
||||
'used_percent' => $size > 0 ? round(($used / $size) * 100, 1) : 0,
|
||||
'used_bytes' => null,
|
||||
'free_bytes' => $free,
|
||||
'used_percent' => null,
|
||||
'capacity_scope' => 'backing_filesystem',
|
||||
'filesystem_size_bytes' => $total,
|
||||
'filesystem_used_bytes' => $used,
|
||||
'filesystem_used_percent' => $total > 0 ? round($used / $total * 100, 1) : null,
|
||||
'share_size_bytes' => $size,
|
||||
'share_size_source' => 'not_measured',
|
||||
'source' => 'emhttp_shares_ini',
|
||||
'exclusive' => ($share['exclusive'] ?? '') === 'yes',
|
||||
'status_color' => $share['color'] ?? '',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AdminTickets, ADMIN_TOOLS } from "./admin";
|
||||
import { getToolRisk, toolByName } from "./tools";
|
||||
import { parseConfig } from "./auth";
|
||||
import { runLocal } from "./helpers";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
describe("native administration approval boundary", () => {
|
||||
const plan = { kind: "share" as const, spec: { action: "remove", name: "test" }, before: { config_sha256: "abc" } };
|
||||
test("tickets are exact-kind, expiring and single use", () => {
|
||||
const t = new AdminTickets(); const id = t.issue(plan, 1000);
|
||||
expect(() => t.take(id, "docker", true, 1001)).toThrow();
|
||||
expect(() => t.take(id, "share", false, 1001)).toThrow();
|
||||
expect(t.take(id, "share", true, 1001)).toEqual(plan);
|
||||
expect(() => t.take(id, "share", true, 1001)).toThrow();
|
||||
const expired = t.issue(plan, 1000);
|
||||
expect(() => t.take(expired, "share", true, 601000)).toThrow();
|
||||
});
|
||||
test("new writes are critical and not silently enabled", () => {
|
||||
const cfg = parseConfig("MUA_ENABLED_TOOLS=unraid_system_shell_readonly\n");
|
||||
for (const name of ["unraid_share_apply", "unraid_docker_template_apply"]) {
|
||||
expect(getToolRisk(name)).toBe("critical");
|
||||
expect(cfg.enabledTools).not.toContain(name);
|
||||
}
|
||||
expect(getToolRisk("unraid_share_preview")).toBe("active");
|
||||
expect(getToolRisk("unraid_storage_diagnostics")).toBe("read");
|
||||
for (const tool of ADMIN_TOOLS) expect(toolByName(tool.name)).toBeDefined();
|
||||
});
|
||||
test("existing template name example does not suggest an image path", () => {
|
||||
expect(JSON.stringify(toolByName("unraid_docker_create")?.inputSchema)).not.toContain("linuxserver/sonarr");
|
||||
});
|
||||
test("a failed process cannot masquerade as normal tool output", async () => {
|
||||
await expect(runLocal("synthetic_failure", "printf failure >&2; exit 17")).rejects.toThrow();
|
||||
expect(await runLocal("synthetic_success", "printf ready")).toBe("ready");
|
||||
});
|
||||
});
|
||||
|
||||
test("actual MCP transport advertises new tools and marks failed commands as errors", async () => {
|
||||
const root = mkdtempSync(`${tmpdir()}/mua-transport-`);
|
||||
const token = crypto.randomUUID();
|
||||
const child = Bun.spawn([process.execPath, fileURLToPath(new URL("./index.ts", import.meta.url))], {
|
||||
env: { ...process.env, MUA_HOST: "127.0.0.1", MUA_PORT: "39871", MUA_CONFIG_PORT: "39872", MUA_API_KEY: token,
|
||||
MUA_ENABLED_TOOLS: "all", MUA_CONFIG_DIR: root, MUA_ADMIN_TOKEN_FILE: `${root}/admin.token`, MUA_AUDIT_LOG: `${root}/audit.log` },
|
||||
stdout: "ignore", stderr: "ignore",
|
||||
});
|
||||
try {
|
||||
let ready = false;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
try { const r = await fetch("http://127.0.0.1:39871/health"); ready = r.ok; if (ready) break; } catch {}
|
||||
await Bun.sleep(50);
|
||||
}
|
||||
expect(ready).toBe(true);
|
||||
let session = ""; let id = 0;
|
||||
const rpc = async (method: string, params: object) => {
|
||||
const r = await fetch("http://127.0.0.1:39871/mcp", { method: "POST", headers: {
|
||||
Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json",
|
||||
...(session ? { "Mcp-Session-Id": session } : {}),
|
||||
}, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }) });
|
||||
if (r.headers.has("Mcp-Session-Id")) session = r.headers.get("Mcp-Session-Id")!;
|
||||
return await r.json() as any;
|
||||
};
|
||||
const init = await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "isolated-test", version: "1" } });
|
||||
expect(init.result.serverInfo.version).toBe("2026.10.24.r032");
|
||||
const list = await rpc("tools/list", {});
|
||||
expect(list.result.tools.some((t: { name: string }) => t.name === "unraid_share_apply")).toBe(true);
|
||||
const fail = await rpc("tools/call", { name: "unraid_system_shell", arguments: { command: "exit 17" } });
|
||||
expect(fail.result.isError).toBe(true);
|
||||
expect(fail.result.structuredContent.exit_code).toBe(17);
|
||||
const denied = await rpc("tools/call", { name: "unraid_share_apply", arguments: { approval_ticket: "invalid", confirm: true } });
|
||||
expect(denied.result.isError).toBe(true);
|
||||
} finally {
|
||||
child.kill(); await child.exited;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 15000);
|
||||
@@ -0,0 +1,41 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { runAdminHelper } from "./helpers";
|
||||
import type { ToolDef } from "./tools";
|
||||
|
||||
type Plan = { kind: "share" | "docker"; spec: Record<string, unknown>; before: Record<string, unknown> };
|
||||
// Tickets bind normalized parameters AND observed target state, never just a name.
|
||||
export class AdminTickets {
|
||||
private tickets = new Map<string, { plan: Plan; expires: number }>();
|
||||
issue(plan: Plan, now = Date.now()) {
|
||||
for (const [id, value] of this.tickets) if (value.expires <= now) this.tickets.delete(id);
|
||||
if (this.tickets.size >= 256) throw new Error("Too many outstanding previews");
|
||||
const id = randomUUID(); this.tickets.set(id, { plan, expires: now + 600_000 }); return id;
|
||||
}
|
||||
take(id: string, kind: string, confirm: unknown, now = Date.now()): Plan {
|
||||
const item = this.tickets.get(id);
|
||||
if (!item || item.expires <= now || item.plan.kind !== kind || confirm !== true) throw new Error("Exact unexpired preview ticket and confirm=true required");
|
||||
this.tickets.delete(id); return item.plan;
|
||||
}
|
||||
}
|
||||
const tickets = new AdminTickets();
|
||||
const text = (description: string) => ({ type: "string", description });
|
||||
const request = (properties: object, required: string[] = []) => ({ type: "object", properties, required, additionalProperties: false });
|
||||
const applySchema = request({ approval_ticket: text("Ticket returned by the matching preview"), confirm: { type: "boolean" } }, ["approval_ticket", "confirm"]);
|
||||
const preview = async (kind: "share" | "docker", args: Record<string, unknown>) => {
|
||||
const plan = JSON.parse(await runAdminHelper(`${kind}-plan`, args)) as Plan;
|
||||
return JSON.stringify({ action: "preview_only", ...plan, approval_ticket: tickets.issue(plan), expires_in_seconds: 600,
|
||||
next_step: "Review the exact change under the user's authorization, then use the corresponding apply tool. A changed target requires a new preview." });
|
||||
};
|
||||
const apply = async (kind: string, args: Record<string, unknown>) => runAdminHelper("apply", tickets.take(String(args.approval_ticket ?? ""), kind, args.confirm));
|
||||
|
||||
export const ADMIN_TOOLS: ToolDef[] = [
|
||||
{ name: "unraid_share_users", description: "List SMB user names and native indices only, without credentials. Use before assigning explicit share rights.", inputSchema: request({}), handler: () => runAdminHelper("share-users", {}) },
|
||||
{ name: "unraid_share_permissions", description: "Read one exact share's configured rights and effective Samba section. This is not an authenticated SMB access test.", inputSchema: request({ name: text("Exact share name") }, ["name"]), handler: a => runAdminHelper("share-rights", a) },
|
||||
{ name: "unraid_share_preview", description: "Preview native private SMB share creation, rights replacement or EMPTY share removal. Reads target state; never writes. Rights replacement denies all unlisted users.",
|
||||
inputSchema: request({ action: { type: "string", enum: ["create", "permissions", "remove"] }, name: text("Exact share name"), description: text("Share description for create"), pool: text("Existing primary pool for cache-only create"), access: { type: "object", additionalProperties: { type: "string", enum: ["read-write", "read-only"] }, description: "Exact user names to access modes; all unlisted users denied" } }, ["action", "name"]), handler: a => preview("share", a) },
|
||||
{ name: "unraid_share_apply", description: "CRITICAL: Apply exactly a reviewed share preview. Refuses state changes or nonempty deletion; uses native emcmd, verifies rights, disables SMB export on partial permission failure. Never deletes share files recursively.", inputSchema: applySchema, handler: a => apply("share", a) },
|
||||
{ name: "unraid_docker_template_preview", description: "Preview creation from a structured custom Unraid XML or removal of an exact STOPPED container. Native renderer sets dockerman label. No raw XML/shell, mounts, privileges or LAN ports. Image and data retained on removal.",
|
||||
inputSchema: request({ action: { type: "string", enum: ["create", "remove"] }, name: text("Exact container and user-template name"), image: text("Verified image reference, preferably version or digest"), description: text("Template description"), ports: { type: "array", maxItems: 8, items: request({ host_port: { type: "integer", minimum: 1024, maximum: 65535 }, container_port: { type: "integer", minimum: 1, maximum: 65535 }, protocol: { type: "string", enum: ["tcp", "udp"] } }, ["host_port", "container_port"]) }, memory_mb: { type: "integer", minimum: 32, maximum: 2048 }, cpus: { type: "number", minimum: 0.1, maximum: 4 }, remove_template: { type: "boolean", description: "Explicitly remove associated user-template on removal; default false" } }, ["action", "name"]), handler: a => preview("docker", a) },
|
||||
{ name: "unraid_docker_template_apply", description: "CRITICAL: Apply the exact reviewed Docker template preview. Refuses existing targets, creates stopped/unprivileged/loopback-only via native xmlToCommand; or removes the exact stopped container. No image/data pruning, no implicit stop.", inputSchema: applySchema, handler: a => apply("docker", a) },
|
||||
{ name: "unraid_storage_diagnostics", description: "Read targeted ZFS pool status, exact dataset properties/snapshots, physical-disk SMART JSON without waking standby disks, or the last 20 parity-history records. No scrub/selftest/repair or global inventory.", inputSchema: request({ action: { type: "string", enum: ["zfs_pool", "zfs_dataset", "zfs_snapshots", "smart", "parity_history"] }, target: text("Exact pool/dataset or Unraid disk name; not needed for parity_history") }, ["action"]), handler: a => runAdminHelper("diagnostics", a) },
|
||||
];
|
||||
+11
-1
@@ -16,7 +16,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
|
||||
|
||||
// ── Konstanten ──────────────────────────────────────────────────────────
|
||||
export const MUA_SERVER_NAME = "mua";
|
||||
export const MUA_VERSION = "2026.10.12.r031";
|
||||
export const MUA_VERSION = "2026.10.24.r032";
|
||||
export const MUA_PROTOCOL_VERSION = "2025-03-26";
|
||||
export const PHP_HELPER = "/usr/local/bin/unraid-docker-mcp-helper.php";
|
||||
export const STATUS_HELPER = "/usr/local/bin/unraid-mcp-status-helper.php";
|
||||
@@ -99,6 +99,7 @@ export async function runLocal(
|
||||
timeoutSec,
|
||||
label,
|
||||
);
|
||||
if (code !== 0) throw Object.assign(new Error("Command exited unsuccessfully"), { code: `COMMAND_EXIT_${code}` });
|
||||
let result = stdout.trim();
|
||||
if (result === "" && stderr.trim() !== "") result = stderr.trim();
|
||||
return result;
|
||||
@@ -1334,3 +1335,12 @@ export async function installCommunityApp(
|
||||
helper_result: result.slice(0, 3000),
|
||||
});
|
||||
}
|
||||
|
||||
/** Typed native admin helper; JSON is passed as a single argv, never shell-expanded. */
|
||||
export async function runAdminHelper(action: string, args: object): Promise<string> {
|
||||
const helper = "/usr/local/bin/unraid-admin-helper.php";
|
||||
if (!(await Bun.file(helper).exists())) throw new Error("Admin helper is not installed");
|
||||
const payload = JSON.stringify(args);
|
||||
if (payload.length > 65_536) throw new Error("Admin request too large");
|
||||
return runArgv(`admin:${action}`, ["/usr/bin/php", helper, action, payload], 300, 64_000, 8_000);
|
||||
}
|
||||
+4
-1
@@ -234,9 +234,12 @@ async function handleMcpRequest(
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const text = await withHardTimeout(tool.handler(args), timeoutMs, `MCP tool '${toolName}'`);
|
||||
auditTool(toolName, true, Date.now() - startedAt);
|
||||
let failed = false;
|
||||
try { const v = JSON.parse(text); failed = v?.ok === false || (typeof v?.exit_code === "number" && v.exit_code !== 0); } catch { /* textual success */ }
|
||||
auditTool(toolName, !failed, Date.now() - startedAt);
|
||||
const result: Record<string, unknown> = {
|
||||
content: [{ type: "text", text }],
|
||||
...(failed ? { isError: true } : {}),
|
||||
};
|
||||
// JSON-Ausgaben zusätzlich strukturiert bereitstellen. Reiner Text
|
||||
// bleibt unverändert im normalen MCP-Content-Feld.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { parseConfig, SAFE_DEFAULT_TOOLS } from "./auth";
|
||||
import { connectionTest, executionFailure, installCommunityApp, runReadOnlyCommand, sanitizeLogOutput } from "./helpers";
|
||||
@@ -188,7 +189,7 @@ describe("Community Applications approval", () => {
|
||||
|
||||
describe("deleted working directory regression", () => {
|
||||
test("inherited deleted cwd reproduces ENOENT but explicit host cwd works", async () => {
|
||||
const helperPath = new URL("./helpers.ts", import.meta.url).pathname;
|
||||
const helperPath = fileURLToPath(new URL("./helpers.ts", import.meta.url));
|
||||
const source = `
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
+8
-2
@@ -1,3 +1,4 @@
|
||||
import { ADMIN_TOOLS } from "./admin";
|
||||
/**
|
||||
* MUA — Mikes Unraid Agent
|
||||
* tools.ts — MCP Tool-Definitionen
|
||||
@@ -52,6 +53,8 @@ const CRITICAL_TOOLS = new Set([
|
||||
"unraid_system_job_start",
|
||||
"unraid_system_job_cleanup",
|
||||
"unraid_ca_install",
|
||||
"unraid_share_apply",
|
||||
"unraid_docker_template_apply",
|
||||
]);
|
||||
const WRITE_TOOLS = new Set([
|
||||
"unraid_docker_start",
|
||||
@@ -63,6 +66,8 @@ const ACTIVE_TOOLS = new Set([
|
||||
"unraid_network_lan_probe",
|
||||
"unraid_ca_search",
|
||||
"unraid_ca_install_preview",
|
||||
"unraid_share_preview",
|
||||
"unraid_docker_template_preview",
|
||||
]);
|
||||
|
||||
export function getToolRisk(name: string): ToolRisk {
|
||||
@@ -95,6 +100,7 @@ function validateShellCommand(value: unknown): string {
|
||||
}
|
||||
|
||||
export const TOOLS: ToolDef[] = [
|
||||
...ADMIN_TOOLS,
|
||||
// These two tools are exposed dynamically only when a labeled toolbox is
|
||||
// present and the dedicated WebGUI switch is enabled (see index.ts).
|
||||
{
|
||||
@@ -335,7 +341,7 @@ export const TOOLS: ToolDef[] = [
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
template_name: str('Template name (e.g. "linuxserver/sonarr")'),
|
||||
template_name: str('Existing user-template name (e.g. Sonarr), not an image repository'),
|
||||
},
|
||||
required: ["template_name"],
|
||||
},
|
||||
@@ -705,7 +711,7 @@ export const TOOLS: ToolDef[] = [
|
||||
{
|
||||
name: "unraid_system_shell",
|
||||
description:
|
||||
"Direct terminal on the Unraid host as root. When the user explicitly asks to create or edit host files, run Docker commands, install software, or administer Unraid, use this tool directly. Do not inspect MUA internals and do not proxy the command through Hermes' local container terminal. Multi-line shell scripts are accepted. Commands may run for up to 30 minutes; use unraid_system_job_start only for work expected to take longer.",
|
||||
"Direct terminal on the Unraid host as root. Prefer the typed share and Docker-template preview/apply tools for their supported operations. When the user explicitly asks to create or edit host files, run Docker commands, install software, or administer Unraid, use this tool directly. Do not inspect MUA internals and do not proxy the command through Hermes' local container terminal. Multi-line shell scripts are accepted. Commands may run for up to 30 minutes; use unraid_system_job_start only for work expected to take longer.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
|
||||
Reference in new issue
Block a user