Files
2026-11-05 21:22:03 +00:00

182 lines
12 KiB
PHP

<?php
declare(strict_types=1);
/**
* Prüft die Übergabe aus den Apps an die Weboberfläche: wer welche Seiten sieht, einmalige und kurzlebige Anmelde-Adressen,
* abgelehnte Pfade und dass die Weboberfläche die Rechte weiterhin selbst prüft.
*/
date_default_timezone_set('Europe/Berlin'); // wie in der Test-Installation
$root = dirname(__DIR__);
$work = sys_get_temp_dir() . '/deskhub-handoff-' . bin2hex(random_bytes(4));
$tmp = $work . '/inst';
mkdir($tmp, 0755, true);
$webPort = random_int(36000, 36499);
$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 . '/database/deskhub.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'], 'path' => $tmp . '/uploads'],
], true) . ';');
putenv('DESKHUB_CONFIG_JSON');
putenv('DESKHUB_SQLITE_PATH');
putenv('DESKHUB_TESTING');
putenv('DESKHUB_API_ALLOW_INSECURE=1');
require_once $root . '/database/sqlite_schema.php';
require_once $root . '/database/migrate.php';
$db = new PDO('sqlite:' . $tmp . '/database/deskhub.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->exec('PRAGMA foreign_keys = ON');
$db->exec(convert_schema_to_sqlite((string) file_get_contents($root . '/database/schema.sql')));
$mig = run_migrations($db, true);
$now = date('Y-m-d H:i:s');
$dept = (int) $db->query('SELECT id FROM departments ORDER BY id LIMIT 1')->fetchColumn();
$db->exec('DELETE FROM staff');
$ins = $db->prepare('INSERT INTO staff (name, email, password_hash, role, department_id, is_active, created_at) VALUES (?,?,?,?,?,1,?)');
$ids = [];
foreach ([['Chef', 'chef@test.de', 'admin'], ['Agent', 'agent@test.de', 'agent'], ['Pfleger', 'pfleger@test.de', 'agent']] as [$n, $e, $r]) {
$ins->execute([$n, $e, password_hash('Sehr-Sicher-1234', PASSWORD_DEFAULT), $r, $dept, $now]);
$ids[$n] = (int) $db->lastInsertId();
}
$db = null;
$failures = [];
$total = 0;
$check = function (bool $ok, string $what) use (&$failures, &$total): void { $total++; if (!$ok) $failures[] = $what; };
$webProc = proc_open([PHP_BINARY, '-S', "127.0.0.1:$webPort", '-t', $tmp], [['pipe', 'r'], ['file', $work . '/web.out', 'w'], ['file', $work . '/web.out', 'a']], $wp, $tmp);
try {
for ($i = 0; $i < 50; $i++) { if (@fsockopen('127.0.0.1', $webPort)) break; usleep(100000); }
$pdo = function () use ($tmp): PDO {
$p = new PDO('sqlite:' . $tmp . '/database/deskhub.sqlite');
$p->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$p->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $p;
};
$api = function (string $method, string $path, ?array $json = null, ?string $bearer = null) use ($webPort): array {
$ch = curl_init("http://127.0.0.1:$webPort$path");
$h = ['Content-Type: application/json'];
if ($bearer) $h[] = 'Authorization: Bearer ' . $bearer;
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_HTTPHEADER => $h, CURLOPT_CUSTOMREQUEST => $method]);
if ($json !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
$b = (string) curl_exec($ch);
$s = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$s, json_decode($b, true) ?? $b];
};
$web = function (string $path, string $jar) use ($webPort): array {
$ch = curl_init("http://127.0.0.1:$webPort$path");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => 60, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar, CURLOPT_HTTPHEADER => ['Sec-Fetch-Mode: navigate', 'Sec-Fetch-User: ?1']]);
$b = (string) curl_exec($ch);
$s = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$hs = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
$head = substr($b, 0, $hs);
preg_match('/^Location: (.+)$/mi', $head, $m);
return [$s, trim($m[1] ?? ''), substr($b, $hs)];
};
$loginApi = function (string $email) use ($api): string {
[, $r] = $api('POST', '/api/staff/v1/login.php', ['email' => $email, 'password' => 'Sehr-Sicher-1234', 'deviceName' => 'Test']);
return (string) ($r['token'] ?? '');
};
$db = $pdo();
$db->prepare('INSERT INTO roles (name, permissions) VALUES (?,?)')->execute(['Assistent-Pfleger', json_encode(['reply_ticket' => true, 'manage_assistant' => true])]);
$roleId = (int) $db->lastInsertId();
$db->prepare('UPDATE staff SET role_id = ? WHERE email = ?')->execute([$roleId, 'pfleger@test.de']);
$now = date('Y-m-d H:i:s');
$dept = (int) $db->query('SELECT id FROM departments ORDER BY id LIMIT 1')->fetchColumn();
$prio = (int) $db->query('SELECT id FROM priorities ORDER BY sort_order LIMIT 1')->fetchColumn();
$db->prepare('INSERT INTO tickets (ticket_number, subject, requester_name, requester_email, department_id, priority_id, status, source, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)')
->execute(['T7001', 'Testticket', 'Kunde', 'kunde@example.org', $dept, $prio, 'open', 'web', $now, $now]);
$chef = $loginApi('chef@test.de');
$agent = $loginApi('agent@test.de');
$pfleger = $loginApi('pfleger@test.de');
$check($chef !== '' && $agent !== '' && $pfleger !== '', 'Anmeldung der drei Mitarbeiter in der App-Schnittstelle');
// ── Welche Seiten sieht wer? ───────────────────────────────────────────
$keys = fn(string $t): array => array_column(($api('GET', '/api/staff/v1/web_pages.php', null, $t)[1]['pages'] ?? []), 'key');
$kc = $keys($chef); $ka = $keys($agent); $kp = $keys($pfleger);
$check(count($kc) === 27 && in_array('settings', $kc, true) && in_array('backup', $kc, true) && in_array('assistant', $kc, true), 'Administrator sieht alle 27 Seiten');
$check($ka === ['mentions', 'agent_directory', 'apps', 'banlist'], 'Mitarbeiter ohne Rechte sehen nur Erwähnungen, Verzeichnis, Apps und die Sperrliste (Standardrecht) ' . json_encode($ka));
$check(in_array('assistant', $kp, true) && !in_array('settings', $kp, true) && !in_array('backup', $kp, true) && !in_array('plugins', $kp, true), 'Mit dem Recht „Assistent“ kommt genau diese Seite dazu, aber keine Systemseiten ' . json_encode($kp));
// ── Übergabe ───────────────────────────────────────────────────────────
[$s] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/settings.php'], $agent);
$check($s === 403, 'Mitarbeiter ohne Recht bekommt keine Adresse für die Einstellungen (HTTP ' . $s . ')');
[$s] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/assistant.php'], $agent);
$check($s === 403, '… und auch nicht für den Assistenten');
[$s] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/staff_manage.php'], $chef);
$check($s === 403, 'Seiten, die nicht in der Liste stehen, werden auch Administratoren nicht übergeben');
[$s] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/ticket_view.php?n=T7001&x=<script>'], $chef);
$check($s === 403, 'Ticket-Adressen mit Zusätzen werden abgelehnt');
[$s] = $api('GET', '/api/staff/v1/web_pages.php');
$check($s === 401, 'Ohne Anmeldung gibt es nichts (HTTP ' . $s . ')');
[$s, $r] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/settings.php'], $chef);
$url = (string) ($r['url'] ?? '');
$check($s === 200 && preg_match('#/staff/app_login\.php\?t=[a-f0-9]{64}$#', $url) === 1, 'Administrator bekommt eine einmalige Adresse (HTTP ' . $s . ')');
$tokenPath = (string) parse_url($url, PHP_URL_PATH) . '?' . (string) parse_url($url, PHP_URL_QUERY);
$jar = tempnam(sys_get_temp_dir(), 'hof');
[$s, $loc] = $web('/staff/settings.php', $jar);
$check($s === 302, 'Vorher: ohne Anmeldung leitet die Einstellungsseite weg');
[$s, $loc] = $web($tokenPath, $jar);
$check($s === 302 && str_ends_with($loc, '/staff/settings.php'), 'Die Adresse meldet an und leitet auf die gewünschte Seite (HTTP ' . $s . ' ' . $loc . ')');
[$s, , $body] = $web('/staff/settings.php', $jar);
$check($s === 200 && str_contains($body, 'Einstellungen'), 'Danach ist man in der Weboberfläche angemeldet');
$jar2 = tempnam(sys_get_temp_dir(), 'hof');
[$s, $loc] = $web($tokenPath, $jar2);
$check($s === 302 && str_contains($loc, '/staff/login.php'), 'Die Adresse funktioniert nur einmal');
[$s, , $body] = $web('/staff/settings.php', $jar2);
$check($s === 302, 'Zweiter Versuch bleibt abgemeldet');
// abgelaufen
[, $r] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/backup.php'], $chef);
$pdo()->exec("UPDATE web_login_tokens SET expires_at = '2000-01-01 00:00:00' WHERE used_at IS NULL");
$tp = (string) parse_url((string) $r['url'], PHP_URL_PATH) . '?' . (string) parse_url((string) $r['url'], PHP_URL_QUERY);
$jar3 = tempnam(sys_get_temp_dir(), 'hof');
[$s, $loc] = $web($tp, $jar3);
$check(str_contains($loc, '/staff/login.php'), 'Abgelaufene Adressen werden abgelehnt');
[$s, $loc] = $web('/staff/app_login.php?t=' . str_repeat('a', 64), $jar3);
$check(str_contains($loc, '/staff/login.php'), 'Erfundene Adressen werden abgelehnt');
[$s, $loc] = $web('/staff/app_login.php?t=../../etc', $jar3);
$check(str_contains($loc, '/staff/login.php'), 'Ungültig aufgebaute Adressen werden abgelehnt');
// Wirkt das Recht auch in der Weboberfläche? Mitarbeiter ohne Recht bleibt auch nach Übergabe eines Tickets draußen bei Admin-Seiten
[, $r] = $api('POST', '/api/staff/v1/web_pages.php', ['path' => '/staff/ticket_view.php?n=T7001'], $agent);
$tp = (string) parse_url((string) ($r['url'] ?? ''), PHP_URL_PATH) . '?' . (string) parse_url((string) ($r['url'] ?? ''), PHP_URL_QUERY);
$jar4 = tempnam(sys_get_temp_dir(), 'hof');
[$s, $loc] = $web($tp, $jar4);
$check($s === 302 && str_contains($loc, 'ticket_view.php?n=T7001'), 'Ein Ticket lässt sich öffnen (zusammenführen, aufteilen, drucken)');
[$s, $loc] = $web('/staff/settings.php', $jar4);
$check($s === 302 && !str_contains($loc, 'settings'), 'Der übergebene Mitarbeiter kommt trotzdem nicht auf Admin-Seiten (Web prüft selbst)');
@unlink($jar); @unlink($jar2); @unlink($jar3); @unlink($jar4);
} finally {
if (isset($webProc) && is_resource($webProc)) { proc_terminate($webProc); proc_close($webProc); }
}
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($work, sys_get_temp_dir() . '/deskhub-handoff-')) $rm($work);
if ($failures) {
fwrite(STDERR, "Fehlgeschlagen:\n - " . implode("\n - ", $failures) . "\n");
exit(1);
}
echo "Web handoff checks passed ({$total} Prüfungen).\n";