Files
Mikei386andClaude Opus 5.5 0117670ede feat: .env-Varianten und Kopien mit Zusatzendung im Editor
.env, .env.local, .env.production, app.env usw. gelten immer als Text.
Zusatzendungen wie .example, .sample, .dist, .bak, .orig, .local werden
bei der Typerkennung abgeschnitten (nginx.conf.sample, config.yml.dist).
Gleiche Regeln in preview.php und app.js. Paket 2026.11.21.r007.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 13:46:56 +01:00

242 lines
15 KiB
PHP

<?php
// Integration tests for the Unraid PHP API. Run: php tests/php/api_test.php
// Starts PHP's built-in server against plugin-root/.../api with a fake /mnt layout.
declare(strict_types=1);
$apiDir = realpath(__DIR__ . '/../../plugin-root/usr/local/emhttp/plugins/u-navigator/api');
$base = sys_get_temp_dir() . '/u-nav-test-' . bin2hex(random_bytes(4));
$mnt = $base . '/mnt';
$user = $mnt . '/user';
$outside = $base . '/outside';
foreach ([$user . '/media/movies', $mnt . '/disk1/media/movies', $mnt . '/disk2/media', $mnt . '/cache/media/movies', $outside, $base . '/jobs'] as $dir) {
mkdir($dir, 0777, true);
}
$mnt = realpath($mnt);
$user = $mnt . '/user';
$base = dirname($mnt);
file_put_contents($mnt . '/disk1/media/movies/a.mkv', 'x');
file_put_contents($mnt . '/cache/media/movies/b.mkv', 'y');
file_put_contents($outside . '/secret.txt', 'secret');
$env = [
'U_NAV_DEFAULT_ROOT' => $user,
'U_NAV_READ_ONLY' => '0',
'U_NAV_SETTINGS_FILE' => $base . '/settings.json',
'U_NAV_JOB_DIR' => $base . '/jobs',
'U_NAV_MNT' => $mnt,
'U_NAV_SYNC_JOBS' => '1',
];
foreach ($env as $key => $value) {
putenv("$key=$value");
}
$port = random_int(20000, 40000);
$server = proc_open([PHP_BINARY, '-S', "127.0.0.1:$port", '-t', $apiDir], [1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes, null, array_merge(getenv(), $env));
register_shutdown_function(function () use ($server, $base) {
proc_terminate($server);
exec('rm -rf ' . escapeshellarg($base));
});
for ($i = 0; $i < 50 && !@fsockopen('127.0.0.1', $port); $i++) {
usleep(100000);
}
$failures = 0;
$count = 0;
function check(string $name, bool $ok, string $detail = ''): void {
global $failures, $count;
$count++;
if ($ok) {
echo "ok $name\n";
return;
}
$failures++;
echo "FAIL $name" . ($detail !== '' ? " — $detail" : '') . "\n";
}
function call(string $method, string $endpoint, array $data = []): array {
global $port;
$options = ['http' => ['method' => $method, 'ignore_errors' => true, 'header' => '']];
if ($method === 'POST') {
$options['http']['header'] = "Content-Type: application/x-www-form-urlencoded\r\n";
$options['http']['content'] = http_build_query($data);
}
$body = file_get_contents("http://127.0.0.1:$port/$endpoint", false, stream_context_create($options));
preg_match('#HTTP/\S+ (\d+)#', $http_response_header[0] ?? '', $match);
return ['status' => (int)($match[1] ?? 0), 'json' => json_decode((string)$body, true), 'body' => (string)$body, 'headers' => $http_response_header ?? []];
}
function job(string $action, array $data): array {
return call('POST', 'job.php?action=' . $action, $data);
}
$share = $user . '/share';
mkdir($share);
file_put_contents($share . '/alpha.txt', 'alpha');
file_put_contents($share . '/beta.txt', 'beta');
symlink($outside, $share . '/escape');
// Root protection
$r = job('delete', ['source' => $user]);
check('delete on root is rejected', $r['status'] === 403 && is_dir($user), (string)$r['status']);
$r = job('move', ['source' => $user, 'destination' => $user . '/x']);
check('move of root is rejected', $r['status'] === 403);
$r = job('fixperms', ['source' => $user]);
check('fixperms on root is rejected', $r['status'] === 403);
$r = call('GET', 'list.php?path=' . urlencode($share . '/escape'));
check('symlink escape is blocked', $r['status'] === 403);
// mkdir
$r = call('POST', 'mkdir.php', ['path' => $share, 'name' => 'Neu']);
check('mkdir creates folder', $r['status'] === 201 && is_dir($share . '/Neu'));
$r = call('POST', 'mkdir.php', ['path' => $share, 'name' => 'Neu']);
check('mkdir conflict is 409', $r['status'] === 409);
$r = call('POST', 'mkdir.php', ['path' => $share, 'name' => '../evil']);
check('mkdir rejects slashes', $r['status'] === 400 && !is_dir($user . '/evil'));
// copy / conflicts
$r = job('copy', ['source' => $share . '/alpha.txt', 'destination' => $share . '/beta.txt']);
check('copy onto existing file is 409 by default', $r['status'] === 409);
$r = job('copy', ['source' => $share . '/alpha.txt', 'destination' => $share . '/alpha.txt', 'conflict' => 'rename']);
check('copy with rename keeps both', $r['json']['status'] === 'completed' && file_get_contents($share . '/alpha (2).txt') === 'alpha', json_encode($r['json']));
$r = job('copy', ['source' => $share . '/alpha.txt', 'destination' => $share . '/beta.txt', 'conflict' => 'overwrite']);
check('copy with overwrite replaces', $r['json']['status'] === 'completed' && file_get_contents($share . '/beta.txt') === 'alpha');
check('copy tracks bytes', ($r['json']['bytesTotal'] ?? null) === 5 && ($r['json']['bytesDone'] ?? null) === 5);
check('no temporary files left', !glob($share . '/.u-nav-*'));
mkdir($share . '/dir/sub', 0777, true);
file_put_contents($share . '/dir/sub/f.txt', 'f');
$r = job('copy', ['source' => $share . '/dir', 'destination' => $share . '/Neu/dir']);
check('directory copy', $r['json']['status'] === 'completed' && file_get_contents($share . '/Neu/dir/sub/f.txt') === 'f');
$r = job('move', ['source' => $share . '/Neu/dir', 'destination' => $share . '/Neu', 'conflict' => 'overwrite']);
check('overwrite cannot target a folder that contains the source', $r['status'] === 400 && is_file($share . '/Neu/dir/sub/f.txt'), json_encode($r['json']));
$r = job('move', ['source' => $share . '/Neu', 'destination' => $share . '/dir', 'conflict' => 'overwrite']);
check('move with overwrite replaces folder', $r['json']['status'] === 'completed' && is_dir($share . '/dir/dir') && !is_dir($share . '/Neu'), json_encode($r['json']));
// search
$r = job('search', ['source' => $share, 'query' => 'F.TXT']);
$names = array_column($r['json']['result']['results'] ?? [], 'name');
check('search is recursive and case-insensitive', $names === ['f.txt'], json_encode($names));
$r = job('search', ['source' => $share, 'query' => '*.txt']);
check('wildcard search', count($r['json']['result']['results'] ?? []) >= 4);
check('search does not follow symlinks', !in_array('secret.txt', array_column($r['json']['result']['results'] ?? [], 'name'), true));
// checksum / compare
$r = job('checksum', ['source' => $share . '/alpha.txt']);
check('checksum md5+sha256', ($r['json']['result']['md5'] ?? '') === md5('alpha') && ($r['json']['result']['sha256'] ?? '') === hash('sha256', 'alpha'));
$r = job('compare', ['source' => $share . '/alpha.txt', 'target' => $share . '/beta.txt']);
check('compare identical files', ($r['json']['result']['identical'] ?? null) === true);
file_put_contents($share . '/gamma.txt', 'alphX');
$r = job('compare', ['source' => $share . '/alpha.txt', 'target' => $share . '/gamma.txt']);
check('compare reports first difference', ($r['json']['result']['identical'] ?? null) === false && ($r['json']['result']['firstDifference'] ?? null) === 4);
// compress / extract
$r = job('compress', ['sources' => json_encode([$share . '/alpha.txt', $share . '/dir']), 'destination' => $share . '/pack.zip']);
check('compress to zip', $r['json']['status'] === 'completed' && is_file($share . '/pack.zip'), json_encode($r['json']));
$r = job('extract', ['source' => $share . '/pack.zip', 'destination' => $share . '/pack']);
check('extract zip', $r['json']['status'] === 'completed' && file_get_contents($share . '/pack/alpha.txt') === 'alpha' && is_file($share . '/pack/dir/dir/sub/f.txt'), json_encode(glob($share . '/pack/*/*')));
$r = job('extract', ['source' => $share . '/pack.zip', 'destination' => $share . '/pack']);
check('extract picks a free folder name', $r['json']['status'] === 'completed' && is_dir($share . '/pack (2)'));
$zip = new ZipArchive();
$zip->open($share . '/evil.zip', ZipArchive::CREATE);
$zip->addFromString('../../outside-zip.txt', 'evil');
$zip->close();
$r = job('extract', ['source' => $share . '/evil.zip', 'destination' => $share . '/evil']);
check('zip slip is rejected', ($r['json']['status'] ?? '') === 'failed' && !file_exists($user . '/outside-zip.txt') && !is_dir($share . '/evil'), json_encode($r['json']));
exec('tar -czf ' . escapeshellarg($share . '/t.tar.gz') . ' -C ' . escapeshellarg($share) . ' alpha.txt');
$r = job('extract', ['source' => $share . '/t.tar.gz', 'destination' => $share . '/t']);
check('extract tar.gz', $r['json']['status'] === 'completed' && file_get_contents($share . '/t/alpha.txt') === 'alpha', json_encode($r['json']));
// permissions
chmod($share . '/alpha.txt', 0700);
$r = job('fixperms', ['source' => $share . '/pack']);
clearstatcache();
check('fixperms sets Unraid modes', $r['json']['status'] === 'completed' && (fileperms($share . '/pack/alpha.txt') & 0777) === 0666 && (fileperms($share . '/pack/dir') & 0777) === 0777, decoct(fileperms($share . '/pack/alpha.txt') & 0777));
// delete
$r = job('delete', ['source' => $share . '/pack (2)']);
check('delete folder', $r['json']['status'] === 'completed' && !file_exists($share . '/pack (2)'));
// storage / location
$r = call('GET', 'storage.php?path=' . urlencode($user . '/media/movies'));
$where = array_column($r['json']['locations'] ?? [], 'name');
check('physical location lists disks and pools', $where === ['cache', 'disk1'], json_encode($where));
check('storage reports free space', is_int($r['json']['free'] ?? null) && is_int($r['json']['total'] ?? null));
// thumbnails
$img = imagecreatetruecolor(400, 200);
imagepng($img, $share . '/pic.png');
$r = call('GET', 'thumb.php?size=100&path=' . urlencode($share . '/pic.png'));
$thumbInfo = @getimagesizefromstring($r['body']);
check('thumbnail is a scaled jpeg', $r['status'] === 200 && $thumbInfo && $thumbInfo[0] === 100 && $thumbInfo[2] === IMAGETYPE_JPEG);
$r = call('GET', 'thumb.php?path=' . urlencode($share . '/alpha.txt'));
check('no thumbnail for text', $r['status'] === 415);
// svg sandbox
file_put_contents($share . '/x.svg', '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>');
$r = call('GET', 'preview.php?raw=1&path=' . urlencode($share . '/x.svg'));
check('raw svg is sandboxed', (bool)preg_grep('/^Content-Security-Policy: sandbox/i', $r['headers']));
// favorites
$r = call('POST', 'config.php', ['favorites' => json_encode([$share, $outside, $share . '/missing'])]);
check('favorites keep only folders inside roots', ($r['json']['favorites'] ?? null) === [$share], json_encode($r['json']['favorites'] ?? null));
// text editor: types, sniffing, encodings
file_put_contents($share . '/go', "#!/bin/bash\n/usr/local/sbin/emhttp &\n");
$r = call('GET', 'preview.php?path=' . urlencode($share . '/go'));
check('file without extension opens as editable text', ($r['json']['type'] ?? '') === 'text' && ($r['json']['editable'] ?? false) === true);
file_put_contents($share . '/compose.yaml', "services:\n app:\n image: x\n");
$r = call('GET', 'preview.php?path=' . urlencode($share . '/compose.yaml'));
check('yaml is editable', ($r['json']['editable'] ?? false) === true);
file_put_contents($share . '/blob.dat', random_bytes(64) . "\0");
$r = call('GET', 'preview.php?path=' . urlencode($share . '/blob.dat'));
check('binary files are not opened as text', $r['status'] === 415);
file_put_contents($share . '/latin.cfg', "Gr\xfc\xdfe=1\r\n");
$r = call('GET', 'preview.php?path=' . urlencode($share . '/latin.cfg'));
check('windows-1252 is decoded for the editor', ($r['json']['content'] ?? '') === "Grüße=1\r\n" && ($r['json']['encoding'] ?? '') === 'windows-1252');
$r = call('POST', 'preview.php?path=' . urlencode($share . '/latin.cfg'), ['content' => "Grüße=2\r\n", 'revision' => $r['json']['revision']]);
check('windows-1252 is written back in its encoding', $r['status'] === 200 && file_get_contents($share . '/latin.cfg') === "Gr\xfc\xdfe=2\r\n");
$r = call('POST', 'preview.php?path=' . urlencode($share . '/latin.cfg'), ['content' => "€ ok, ✓ nicht\r\n", 'revision' => $r['json']['revision']]);
check('characters outside windows-1252 are refused', $r['status'] === 422 && file_get_contents($share . '/latin.cfg') === "Gr\xfc\xdfe=2\r\n");
foreach (['.env', '.env.local', '.env.production', 'app.env', 'nginx.conf.sample', 'config.yml.dist', 'settings.json.bak'] as $variant) {
file_put_contents($share . '/' . $variant, "KEY=1\n");
$r = call('GET', 'preview.php?path=' . urlencode($share . '/' . $variant));
check("$variant is editable", ($r['json']['editable'] ?? false) === true, (string)$r['status']);
}
// whole system root (opt-in)
$r = call('GET', 'list.php?path=/');
check('system root is hidden by default', $r['status'] === 403);
$r = call('POST', 'config.php', ['systemRoot' => '1']);
check('system root can be enabled', ($r['json']['systemRoot'] ?? null) === true && in_array('/', array_column($r['json']['roots'] ?? [], 'path'), true));
$r = call('GET', 'list.php?path=/');
check('system root lists /', $r['status'] === 200 && in_array('usr', array_column($r['json']['entries'] ?? [], 'name'), true), $r['status'] . ' ' . substr($r['body'], 0, 300));
$r = job('size', ['source' => '/dev']);
check('pseudo filesystems are rejected for jobs', $r['status'] === 400);
$r = call('GET', 'download.php?path=' . urlencode('/dev/null'));
check('pseudo filesystem files cannot be downloaded', $r['status'] === 400);
$r = job('copy', ['source' => $share . '/alpha.txt', 'destination' => $share . '/alpha-sys.txt']);
check('shares still work with system root', ($r['json']['status'] ?? '') === 'completed');
call('POST', 'config.php', ['systemRoot' => '0']);
// cancellation (worker in-process with a pre-set cancel marker)
require_once $apiDir . '/job_worker.php';
$big = $share . '/big.bin';
file_put_contents($big, str_repeat('0', 9 * 1024 * 1024));
$jobId = 'copy-canceltest';
unav_job_write(['id' => $jobId, 'type' => 'copy', 'status' => 'queued', 'source' => $big, 'destination' => $share . '/big-copy.bin', 'conflict' => 'fail', 'progress' => 0, 'bytesDone' => 0]);
touch(unav_job_cancel_path($jobId));
unav_run_job($jobId);
$cancelled = unav_job_read($jobId);
putenv('U_NAV_SETTINGS_FILE=' . $base . '/settings-system.json');
file_put_contents($base . '/settings-system.json', json_encode(['systemRoot' => true]));
unav_roots(true);
check('top-level system folders are protected', unav_is_protected('/usr') && unav_is_protected('/boot') && unav_is_protected('/') && !unav_is_protected('/usr/local'));
check('Unraid mount points are protected', unav_is_protected($mnt . '/disk1') && unav_is_protected($user) && unav_is_protected($mnt) && !unav_is_protected($share));
check('pseudo filesystems are protected', unav_is_protected('/proc/1') && unav_is_pseudo_fs('/sys/kernel') && !unav_is_pseudo_fs('/system'));
putenv('U_NAV_SETTINGS_FILE=' . $base . '/settings.json');
unav_roots(true);
check('cancelled copy leaves nothing behind', $cancelled['status'] === 'cancelled' && !file_exists($share . '/big-copy.bin') && !glob($share . '/.u-nav-*'), json_encode($cancelled));
echo "\n$count checks, $failures failed\n";
exit($failures ? 1 : 0);