Files
deskhub/DeskHub-Webseite/tests/import_upload.php
T
2026-10-19 18:05:51 +00:00

151 lines
9.4 KiB
PHP

<?php
declare(strict_types=1);
/**
* Prüft den Datei-Upload des osTicket-Imports (staff/import_osticket.php) auf einem Server mit kleinem Upload-Limit
* (upload_max_filesize 2M, post_max_size 3M, wie auf vielen Hostings): Die Seite muss die Teilgröße ans Limit anpassen,
* eine große Datei vollständig und unverändert ankommen, zu große Teile verständlich melden und ein leeres Feld bei
* "Verwenden" nicht als "Datei nicht gefunden:" ohne Namen enden.
*/
if (!extension_loaded('pdo_sqlite') || !function_exists('curl_init')) { echo "Import-Upload-Test übersprungen: pdo_sqlite oder curl fehlt.\n"; exit(0); }
$root = dirname(__DIR__);
$tmp = sys_get_temp_dir() . '/deskhub-impup-' . bin2hex(random_bytes(4));
mkdir($tmp, 0755, true);
putenv('DESKHUB_SQLITE_PATH=' . $tmp . '/test.sqlite'); // erlaubt dem Programm im Testserver, die Test-Datenbank selbst anzulegen
putenv('DESKHUB_TESTING=1');
$skip = '#^(config/config\.php|database/[^/]+\.sqlite[^/]*|backups|uploads|tests|plugins/[^/]+|\.git)(/|$)#';
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $f) {
$rel = str_replace(chr(92), '/', substr($f->getPathname(), strlen($root) + 1));
if (preg_match($skip, $rel) && !preg_match('#^(backups|uploads|plugins)/(\.htaccess|README\.md)$#', $rel)) continue;
if ($f->isDir()) { @mkdir($tmp . '/' . $rel, 0755, true); continue; }
@mkdir(dirname($tmp . '/' . $rel), 0755, true);
copy($f->getPathname(), $tmp . '/' . $rel);
}
@mkdir($tmp . '/uploads');
@mkdir($tmp . '/config');
file_put_contents($tmp . '/config/config.php', '<?php return ' . var_export([
'app_key' => bin2hex(random_bytes(32)),
'db' => ['driver' => 'sqlite', 'sqlite_path' => $tmp . '/test.sqlite'],
'site' => ['name' => 'Test', 'url' => 'http://127.0.0.1', 'admin_email' => 'a@test.de', 'timezone' => 'Europe/Berlin'],
'uploads' => ['max_size_bytes' => 10485760, 'allowed_extensions' => ['png', 'pdf'], 'path' => $tmp . '/uploads'],
], true) . ';');
// Datenbank mit Admin-Konto vorbereiten
require_once $root . '/includes/db.php';
require_once $root . '/database/migrate.php';
$pdo = new PDO('sqlite:' . $tmp . '/test.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('PRAGMA foreign_keys = ON');
$pdo->exec(convert_schema_to_sqlite((string) file_get_contents($root . '/database/schema.sql')));
$migrated = run_migrations($pdo, true);
$pdo->exec("DELETE FROM staff");
$pdo->prepare("INSERT INTO staff (name, email, password_hash, role, department_id, is_active, created_at) VALUES ('Admin', 'admin@test.de', ?, 'admin', 1, 1, ?)")
->execute([password_hash('Sehr-Sicher-1234', PASSWORD_DEFAULT), date('Y-m-d H:i:s')]);
$pdo = null;
$failures = [];
$total = 0;
$check = function (bool $ok, string $what) use (&$failures, &$total): void {
$total++;
if (!$ok) $failures[] = $what;
};
$port = random_int(26000, 26999);
$log = tempnam(sys_get_temp_dir(), 'impuplog');
$proc = proc_open([PHP_BINARY, '-d', 'upload_max_filesize=2M', '-d', 'post_max_size=3M', '-S', "127.0.0.1:$port", '-t', $tmp],
[['pipe', 'r'], ['file', $log, 'w'], ['file', $log, 'a']], $pipes, $tmp, ['DESKHUB_SQLITE_PATH' => $tmp . '/test.sqlite', 'DESKHUB_TESTING' => '1'] + getenv());
$jar = tempnam(sys_get_temp_dir(), 'impupjar');
$req = function (string $method, string $path, array $data = []) use ($port, $jar): array {
$ch = curl_init("http://127.0.0.1:$port$path");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 120, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar]);
if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); }
$body = (string) curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$status, $body];
};
$csrf = fn(string $html) => preg_match('/name="csrf_token" value="([a-f0-9]+)"/', $html, $m) ? $m[1] : '';
try {
for ($i = 0; $i < 50; $i++) { if (@fsockopen('127.0.0.1', $port)) break; usleep(100000); }
[, $login] = $req('GET', '/staff/login.php');
$req('POST', '/staff/login.php', ['csrf_token' => $csrf($login), 'email' => 'admin@test.de', 'password' => 'Sehr-Sicher-1234']);
[$s, $page] = $req('GET', '/staff/import_osticket.php');
$check($s === 200 && str_contains($page, 'startChunkedUpload'), 'Import-Seite lädt (HTTP ' . $s . '): ' . substr(trim(preg_replace('/s+/', ' ', strip_tags($page))), 0, 200));
if ($s !== 200 || !str_contains($page, 'startChunkedUpload')) { fwrite(STDERR, 'Seite: ' . substr(trim(preg_replace('/s+/', ' ', strip_tags($page))), 0, 400) . "
" . substr((string) file_get_contents($log), 0, 600) . "
"); exit(1); }
preg_match('/var chunkSize = (\d+)/', $page, $m);
$chunk = (int) ($m[1] ?? 0);
$check($chunk >= 131072 && $chunk < 2 * 1048576, "die Teilgröße passt zum 2-MB-Limit des Servers ({$chunk} Bytes)");
$check(preg_match('/var csrf = "([a-f0-9]+)"/', $page, $cm) === 1, 'Seite liefert das Token für den Upload');
$token = $cm[1] ?? '';
// Eine 7-MB-Datei in Teilen hochladen, wie es die Seite macht
$content = '';
for ($i = 0; $i < 7 * 1024; $i++) $content .= substr(hash('sha256', (string) $i) . str_repeat('x', 960), 0, 1024);
$src = $tmp . '/quelle.sql';
file_put_contents($src, $content);
$totalChunks = (int) ceil(strlen($content) / $chunk);
$last = [];
for ($idx = 0; $idx < $totalChunks; $idx++) {
$piece = $tmp . '/teil.bin';
file_put_contents($piece, substr($content, $idx * $chunk, $chunk));
[, $body] = $req('POST', '/staff/import_osticket.php', ['action' => 'upload_chunk', 'csrf_token' => $token, 'chunk' => new CURLFile($piece, 'application/octet-stream', 'helpdesk.sql'),
'chunk_index' => $idx, 'total_chunks' => $totalChunks, 'filename' => 'helpdesk.sql']);
$last = json_decode($body, true) ?: ['ok' => false, 'error' => 'keine JSON-Antwort: ' . substr($body, 0, 80)];
if (empty($last['ok'])) break;
}
$check(!empty($last['ok']) && !empty($last['done']), "alle {$totalChunks} Teile werden angenommen: " . json_encode($last));
$sid = preg_match('/PHPSESSID\s+(\S+)/', (string) file_get_contents($jar), $sm) ? $sm[1] : '';
$stored = array_filter([sys_get_temp_dir() . '/deskhub_import_' . preg_replace('/[^a-zA-Z0-9]/', '', $sid) . '/upload.sql'], 'is_file');
$stored = array_values($stored);
$check($stored !== [] && hash_file('sha256', $stored[0]) === hash('sha256', $content), 'die zusammengesetzte Datei ist byteweise identisch');
foreach ($stored as $leftover) { @unlink($leftover); @rmdir(dirname($leftover)); }
// Ein zu großes Teil (4 MB bei 2-MB-Limit) wird verständlich abgelehnt
$big = $tmp . '/gross.bin';
file_put_contents($big, str_repeat('a', 2600000));
[, $body] = $req('POST', '/staff/import_osticket.php', ['action' => 'upload_chunk', 'csrf_token' => $token, 'chunk' => new CURLFile($big, 'application/octet-stream', 'x.sql'), 'chunk_index' => 0, 'total_chunks' => 2, 'filename' => 'x.sql']);
$r = json_decode($body, true) ?: [];
$check(empty($r['ok']) && str_contains((string) ($r['error'] ?? ''), 'upload_max_filesize'), 'zu großes Teil: Meldung nennt das Limit: ' . substr((string) ($r['error'] ?? $body), 0, 160));
// Weit über post_max_size verwirft PHP alle Formulardaten und die Seite antwortet ohne JSON: Die Seite muss das verständlich melden
$huge = $tmp . '/riesig.bin';
file_put_contents($huge, str_repeat('a', 4000000));
[, $body] = $req('POST', '/staff/import_osticket.php', ['action' => 'upload_chunk', 'csrf_token' => $token, 'chunk' => new CURLFile($huge, 'application/octet-stream', 'x.sql'), 'chunk_index' => 0, 'total_chunks' => 2, 'filename' => 'x.sql']);
$check(json_decode($body, true) === null, 'weit zu großes Teil: Server antwortet ohne JSON (Formulardaten verworfen)');
$check(str_contains($page, 'post_max_size') && str_contains($page, 'JSON.parse'), 'die Seite erklärt diesen Fall (post_max_size) statt eines JavaScript-Fehlers');
// "Verwenden" mit leerem Feld und mit unbekannter Datei
[, $page2] = $req('GET', '/staff/import_osticket.php');
$t2 = $csrf($page2);
$req('POST', '/staff/import_osticket.php', ['action' => 'use_path', 'csrf_token' => $t2, 'sql_filename' => '']);
[, $after] = $req('GET', '/staff/import_osticket.php');
$check(str_contains($after, 'Bitte den Dateinamen der SQL-Datei eintragen'), 'leeres Feld: klare Aufforderung statt "Datei nicht gefunden:"');
$req('POST', '/staff/import_osticket.php', ['action' => 'use_path', 'csrf_token' => $csrf($after), 'sql_filename' => 'gibt-es-nicht.sql']);
[, $after2] = $req('GET', '/staff/import_osticket.php');
$check(str_contains($after2, 'gibt-es-nicht.sql') && str_contains($after2, 'DeskHub-Hauptordner'), 'unbekannte Datei: Meldung nennt Namen und Ort');
} finally {
proc_terminate($proc);
proc_close($proc);
}
usleep(300000);
$rm = function (string $d) use (&$rm) {
foreach (scandir($d) ?: [] as $e) { if ($e === '.' || $e === '..') continue; is_dir("$d/$e") && !is_link("$d/$e") ? $rm("$d/$e") : @unlink("$d/$e"); }
@rmdir($d);
};
if (str_starts_with($tmp, sys_get_temp_dir() . '/deskhub-impup-')) $rm($tmp);
@unlink($jar);
@unlink($log);
if ($failures) {
fwrite(STDERR, "Fehlgeschlagen:\n - " . implode("\n - ", $failures) . "\n");
exit(1);
}
echo "Import upload checks passed ({$total} Prüfungen).\n";