fix(security, core): Auth-Pflicht für Ingest-APIs, 500er-Ursachen beheben, Agenten-Workflow
Sicherheit
- install_db.php war ohne Authentifizierung erreichbar und setzte bei jedem
Aufruf das Admin-Passwort auf einen fest im Code stehenden Wert zurück.
Jetzt Auth-Pflicht; ein Konto wird nur bei leerer Benutzertabelle angelegt.
- Stored XSS im Bugtracker-Detail-Modal: Titel, Beschreibung, Fehlermeldung,
Stacktrace und Kommentare gingen ungefiltert durch innerHTML.
- report.php, projects.php und das Veröffentlichen von Releases verlangen jetzt
zwingend ein Token. Publish war zuvor völlig ungeschützt.
- CSRF-Token in allen Formularen, Session-Regenerierung nach Login,
Drosselung fehlgeschlagener Anmeldeversuche.
- Zugangsdaten aus der Versionskontrolle entfernt (Serverdaten.txt,
config.php, .htpasswd, deploy_config.json). Historie enthält sie weiterhin,
Rotation erforderlich (siehe docs/UPGRADE.md).
- Token-Validierung nur noch über SHA-256-Hash; expires_at wird ausgewertet.
Behobene 500er
- Audit::log() war in index.php weder eingebunden noch importiert. Jeder
Klick auf "Aktivierung freigeben" endete in einem Fatal Error.
- Derselbe benannte PDO-Platzhalter mehrfach je Statement (:id in
revokeToken/deleteToken, :q siebenfach in der Volltextsuche). Bei
EMULATE_PREPARES=false ist das nicht zulässig und warf HY093.
- Migration 005 nutzte dynamisches SQL, dessen Semikolons in String-Literalen
vom alten explode(';')-Installer als Statement-Ende gelesen wurden. Sie
schlug still fehl, wodurch push_id/target_agent/tags dauerhaft fehlten.
- Monitor-Umbenennung ohne Transaktion, verschachtelte Transaktionen im
RateLimiter.
Funktionale Korrekturen
- Der Watchdog-Evaluator fehlte vollständig: Monitor-Zustände änderten sich nur
beim Eintreffen eines Heartbeats, ein ausgefallenes System blieb dauerhaft
"up". Erster Lauf auf dem Produktivsystem: 7 von 10 Monitoren waren
tatsächlich seit über einem Tag nicht erreichbar.
- Das Feld "os" fehlte im Monitor-Dialog, wurde aber gespeichert und löschte
damit bei jedem Speichern das Betriebssystem.
- Der Resolve-Dialog existierte im HTML nicht; der Button war funktionslos.
- Versionsvergleich erfolgte lexikografisch, wodurch 1.9.0 als neuer galt
als 1.10.0.
- Schreiboperationen meldeten Erfolg auch für nicht existierende IDs.
- Post/Redirect/Get gegen doppelte Einträge beim Neuladen.
Neue Struktur
- src/bootstrap.php mit PSR-4-Autoloader ersetzt die require-Ketten.
- Core: Config, Http, Csrf, ApiAuth, Logger, Migrator, ErrorReporter.
- Migrator mit zeichenweisem SQL-Parser, dc_migrations und Baseline-Verfahren,
damit bestehende Installationen keine Beispieldaten zurückbekommen.
Agenten-Workflow
- Claim/Lease: Items werden exklusiv übernommen, damit nicht zwei Agenten am
selben Problem arbeiten. action=next holt und reserviert in einem Zug.
- Idempotenz über client_ref, Deduplizierung auch für Feature Requests,
Erkennung von Regressionen, automatische Eskalation des Schweregrads.
- Strukturierter Code-Kontext (repo_url, commit_sha, file_path, line_no).
- Delta-Abfragen über updated_since, Pagination, Bulk-Update.
- Beim Veröffentlichen eines Releases schließen sich Items mit passendem
resolved_in_build selbst.
- Ausgehende Webhooks mit HMAC-Signatur, /api/health, /api/openapi.json.
- Unbehandelte Fehler meldet die Plattform in ihren eigenen Bugtracker.
WebUI
- Serverseitige Filterung mit Pagination statt Rendern aller Datensätze.
- Migrations-Schranke, Evaluator-Warnung, Übersicht aktiver Agenten.
Zeitstempel liegen in der Datenbank durchgängig in UTC und werden für die
Anzeige in die App-Zeitzone umgerechnet.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
a21536f495
commit
e7fbc85db4
@@ -1,122 +1,218 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Watchdog API
|
||||
*
|
||||
* POST /api/watchdog/v1/ping Heartbeat (Scope watchdog:ping)
|
||||
* POST /api/watchdog/v1/event Ereignis protokollieren
|
||||
* GET /api/watchdog/v1/status Alle Monitore (Scope watchdog:read)
|
||||
* GET /api/watchdog/v1/events Ereignisprotokoll
|
||||
* GET /api/watchdog/v1/evaluate Evaluationslauf (Shared Key oder Session)
|
||||
*
|
||||
* Der Evaluate-Endpunkt ist neu und die eigentliche Ergaenzung: er stuft
|
||||
* Monitore anhand ihres erwarteten Intervalls auf warning bzw. down. Ohne ihn
|
||||
* blieb ein ausgefallener Server dauerhaft gruen, weil der Zustand sich nur
|
||||
* beim Eintreffen eines Heartbeats aenderte.
|
||||
*
|
||||
* Cron-Eintrag (minuetlich):
|
||||
* * * * * * curl -fsS -H "Authorization: Bearer <SHARED_KEY>" \
|
||||
* https://dc.example.com/api/watchdog/v1/evaluate > /dev/null
|
||||
*
|
||||
* Authentifizierung fuer Agenten: sowohl die zentralen Master-/Sub-Tokens
|
||||
* (dc_tokens, Scope watchdog:ping) als auch die aelteren Agent-Tokens aus
|
||||
* watchdog_agent_tokens werden akzeptiert.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
require_once __DIR__ . '/../../../../src/Core/Db.php';
|
||||
require_once __DIR__ . '/../../../../src/Modules/Watchdog/MonitorRepo.php';
|
||||
require_once __DIR__ . '/../../../../src/Modules/Watchdog/EventLog.php';
|
||||
require_once __DIR__ . '/../../../../src/Modules/Watchdog/TokenManager.php';
|
||||
require_once __DIR__ . '/../../../../src/bootstrap.php';
|
||||
|
||||
use Deploymentcenter\Core\ApiAuth;
|
||||
use Deploymentcenter\Core\Db;
|
||||
use Deploymentcenter\Modules\Watchdog\MonitorRepo;
|
||||
use Deploymentcenter\Core\Http;
|
||||
use Deploymentcenter\Modules\Watchdog\Evaluator;
|
||||
use Deploymentcenter\Modules\Watchdog\EventLog;
|
||||
use Deploymentcenter\Modules\Watchdog\TokenManager;
|
||||
use Deploymentcenter\Modules\Watchdog\MonitorRepo;
|
||||
use Deploymentcenter\Modules\Watchdog\TokenManager as LegacyTokenManager;
|
||||
|
||||
function sendResponse(array $data, int $statusCode = 200): void {
|
||||
http_response_code($statusCode);
|
||||
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
Http::beginJson(['GET', 'POST', 'OPTIONS'], true);
|
||||
|
||||
try {
|
||||
$config = require __DIR__ . '/../../../../config/config.php';
|
||||
$pdo = Db::init($config);
|
||||
$db = Db::init();
|
||||
|
||||
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
|
||||
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
||||
$monitorRepo = new MonitorRepo($db);
|
||||
$eventLog = new EventLog($db);
|
||||
|
||||
$authHeader = $_SERVER['HTTP_X_WATCHDOG_KEY'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['HTTP_X_AGENT_TOKEN'] ?? null;
|
||||
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
|
||||
$authHeader = substr($authHeader, 7);
|
||||
}
|
||||
$action = resolveWatchdogAction();
|
||||
|
||||
$sharedKey = $config['security']['shared_key'] ?? '';
|
||||
$isAdminAuth = ($authHeader && hash_equals($sharedKey, $authHeader));
|
||||
switch ($action) {
|
||||
|
||||
$tokenManager = new TokenManager($pdo);
|
||||
$monitorRepo = new MonitorRepo($pdo);
|
||||
$eventLog = new EventLog($pdo);
|
||||
case 'ping':
|
||||
requirePost();
|
||||
|
||||
$verifyToken = function(string $source) use ($isAdminAuth, $authHeader, $tokenManager) {
|
||||
if ($isAdminAuth) return true;
|
||||
if (empty($authHeader)) {
|
||||
sendResponse(['error' => 'Unauthorized', 'message' => 'Missing authorization token.'], 401);
|
||||
}
|
||||
if (!$tokenManager->validateToken($authHeader, $source)) {
|
||||
sendResponse(['error' => 'Forbidden', 'message' => "Token unauthorized for source '{$source}'."], 403);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
$rawInput = file_get_contents('php://input');
|
||||
$inputData = !empty($rawInput) ? (json_decode($rawInput, true) ?? []) : $_POST;
|
||||
|
||||
// Heartbeat / Ping
|
||||
if ((str_ends_with($uri, '/ping') || str_ends_with($uri, '/heartbeat')) && $method === 'POST') {
|
||||
$source = trim($inputData['source'] ?? '');
|
||||
$instance = trim($inputData['instance'] ?? 'default');
|
||||
$type = trim($inputData['type'] ?? 'heartbeat');
|
||||
$interval = (int)($inputData['interval'] ?? $inputData['expected_interval_sec'] ?? 60);
|
||||
$metrics = $inputData['metrics'] ?? null;
|
||||
$status = strtolower(trim($inputData['status'] ?? 'ok'));
|
||||
$message = $inputData['message'] ?? $inputData['reason'] ?? null;
|
||||
$groupKey = $inputData['group'] ?? $inputData['group_key'] ?? null;
|
||||
$os = $inputData['os'] ?? null;
|
||||
|
||||
if (empty($source)) {
|
||||
sendResponse(['error' => 'Bad Request', 'message' => 'Field "source" is required.'], 400);
|
||||
$source = Http::str('source');
|
||||
if ($source === null) {
|
||||
Http::fail(400, 'missing_source', 'Das Feld "source" wird benoetigt.');
|
||||
}
|
||||
|
||||
$verifyToken($source);
|
||||
authorizeSource($db, $source);
|
||||
|
||||
$monitor = $monitorRepo->upsertHeartbeat($source, $instance, $type, $interval, $metrics, $status, $message, $groupKey, $os);
|
||||
sendResponse([
|
||||
'status' => 'success',
|
||||
'message' => 'Heartbeat received',
|
||||
$monitor = $monitorRepo->upsertHeartbeat(
|
||||
$source,
|
||||
Http::str('instance') ?? 'default',
|
||||
Http::str('type') ?? 'heartbeat',
|
||||
Http::int('interval', 0) ?: Http::int('expected_interval_sec', 60),
|
||||
Http::input('metrics'),
|
||||
strtolower(Http::str('status') ?? 'ok'),
|
||||
Http::str('message') ?? Http::str('reason'),
|
||||
Http::str('group') ?? Http::str('group_key'),
|
||||
Http::str('os')
|
||||
);
|
||||
|
||||
// Zustandswechsel im Ereignisprotokoll festhalten.
|
||||
if (!empty($monitor['_state_changed'])) {
|
||||
$previous = (string)$monitor['_previous_state'];
|
||||
$current = (string)$monitor['state'];
|
||||
|
||||
$eventLog->logEvent(
|
||||
$source,
|
||||
(string)$monitor['instance'],
|
||||
$current === 'up' ? 'recovered' : ($current === 'warning' ? 'warning_raised' : 'hard_error'),
|
||||
$previous,
|
||||
$current,
|
||||
$current === 'up' ? 'info' : ($current === 'warning' ? 'warning' : 'alarm'),
|
||||
'Zustandswechsel durch Heartbeat.'
|
||||
);
|
||||
}
|
||||
|
||||
Http::ok([
|
||||
'message' => 'Heartbeat empfangen.',
|
||||
'monitor' => [
|
||||
'source' => $monitor['source'],
|
||||
'instance' => $monitor['instance'],
|
||||
'state' => $monitor['state'],
|
||||
'last_status' => $monitor['last_status'],
|
||||
'source' => $monitor['source'],
|
||||
'instance' => $monitor['instance'],
|
||||
'state' => $monitor['state'],
|
||||
'last_status' => $monitor['last_status'],
|
||||
'last_seen_utc' => $monitor['last_seen_utc'],
|
||||
]
|
||||
'state_changed' => (bool)($monitor['_state_changed'] ?? false),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
// Log Event
|
||||
if (str_ends_with($uri, '/event') && $method === 'POST') {
|
||||
$source = trim($inputData['source'] ?? '');
|
||||
$instance = trim($inputData['instance'] ?? 'default');
|
||||
$kind = trim($inputData['kind'] ?? 'started');
|
||||
$severity = trim($inputData['severity'] ?? 'info');
|
||||
$message = $inputData['message'] ?? null;
|
||||
$meta = $inputData['meta'] ?? null;
|
||||
case 'event':
|
||||
requirePost();
|
||||
|
||||
if (empty($source)) sendResponse(['error' => 'Bad Request', 'message' => 'Field "source" is required.'], 400);
|
||||
$source = Http::str('source');
|
||||
if ($source === null) {
|
||||
Http::fail(400, 'missing_source', 'Das Feld "source" wird benoetigt.');
|
||||
}
|
||||
|
||||
$verifyToken($source);
|
||||
$eventId = $eventLog->logEvent($source, $instance, $kind, null, null, $severity, $message, $meta);
|
||||
authorizeSource($db, $source);
|
||||
|
||||
sendResponse(['status' => 'success', 'event_id' => $eventId]);
|
||||
}
|
||||
$meta = Http::input('meta');
|
||||
$eventId = $eventLog->logEvent(
|
||||
$source,
|
||||
Http::str('instance') ?? 'default',
|
||||
Http::str('kind') ?? 'started',
|
||||
Http::str('from_state'),
|
||||
Http::str('to_state'),
|
||||
Http::str('severity') ?? 'info',
|
||||
Http::str('message'),
|
||||
is_array($meta) ? $meta : null
|
||||
);
|
||||
|
||||
// Status / Monitore auflisten
|
||||
if (str_ends_with($uri, '/status') && $method === 'GET') {
|
||||
Http::ok(['event_id' => $eventId], 201);
|
||||
|
||||
case 'status':
|
||||
ApiAuth::requireScope($db, 'watchdog:read');
|
||||
$monitors = $monitorRepo->getAllMonitors();
|
||||
sendResponse(['count' => count($monitors), 'monitors' => $monitors]);
|
||||
}
|
||||
Http::ok(['count' => count($monitors), 'monitors' => $monitors]);
|
||||
|
||||
// Events auflisten
|
||||
if (str_ends_with($uri, '/events') && $method === 'GET') {
|
||||
$limit = (int)($_GET['limit'] ?? 50);
|
||||
$events = $eventLog->getRecentEvents($limit);
|
||||
sendResponse(['count' => count($events), 'events' => $events]);
|
||||
}
|
||||
case 'events':
|
||||
ApiAuth::requireScope($db, 'watchdog:read');
|
||||
$events = $eventLog->getRecentEvents(
|
||||
Http::int('limit', 50),
|
||||
Http::str('source'),
|
||||
Http::str('instance'),
|
||||
Http::str('severity')
|
||||
);
|
||||
Http::ok(['count' => count($events), 'events' => $events]);
|
||||
|
||||
sendResponse(['error' => 'Not Found', 'message' => 'Endpoint not found'], 404);
|
||||
case 'evaluate':
|
||||
// Bewusst nur fuer Shared Key oder eine angemeldete Sitzung -
|
||||
// ein Agenten-Token soll den Zustand aller Monitore nicht umschreiben.
|
||||
ApiAuth::requireScope($db, 'watchdog:evaluate');
|
||||
|
||||
} catch (Throwable $t) {
|
||||
sendResponse(['error' => 'Server Error', 'message' => $t->getMessage()], 500);
|
||||
$result = Evaluator::run($db);
|
||||
Http::ok($result + ['message' => sprintf(
|
||||
'%d Monitor(e) geprueft, %d Zustandswechsel.',
|
||||
$result['checked'],
|
||||
$result['changed']
|
||||
)]);
|
||||
|
||||
default:
|
||||
Http::fail(404, 'unknown_action', 'Endpunkt nicht gefunden.', null, [
|
||||
'available' => ['ping', 'event', 'status', 'events', 'evaluate'],
|
||||
]);
|
||||
}
|
||||
|
||||
// ======================================================================
|
||||
|
||||
function requirePost(): void
|
||||
{
|
||||
if (Http::method() !== 'POST') {
|
||||
Http::fail(405, 'method_not_allowed', 'Diese Aktion erwartet POST.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prueft die Berechtigung, fuer eine bestimmte Source zu melden.
|
||||
*
|
||||
* Akzeptiert zentrale Tokens (dc_tokens, Scope watchdog:ping) und die
|
||||
* aelteren, an eine Source gebundenen Agent-Tokens.
|
||||
*/
|
||||
function authorizeSource(PDO $db, string $source): void
|
||||
{
|
||||
// Zentrale Token-Hierarchie, Shared Key oder Session
|
||||
if (ApiAuth::resolve($db, 'watchdog:ping', null, true) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Alt-Tokens aus watchdog_agent_tokens
|
||||
$presented = Http::bearerToken();
|
||||
if ($presented !== null) {
|
||||
$legacy = new LegacyTokenManager($db);
|
||||
if ($legacy->validateToken($presented, $source)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Http::fail(
|
||||
401,
|
||||
'unauthorized',
|
||||
sprintf('Kein gueltiges Token fuer die Source "%s".', $source),
|
||||
null,
|
||||
['required_scope' => 'watchdog:ping']
|
||||
);
|
||||
}
|
||||
|
||||
function resolveWatchdogAction(): string
|
||||
{
|
||||
$explicit = Http::str('action');
|
||||
if ($explicit !== null) {
|
||||
return strtolower($explicit);
|
||||
}
|
||||
|
||||
$segments = array_values(array_filter(
|
||||
explode('/', trim(Http::path(), '/')),
|
||||
static fn(string $s): bool => $s !== ''
|
||||
));
|
||||
|
||||
$last = strtolower((string)end($segments));
|
||||
|
||||
return match ($last) {
|
||||
'ping', 'heartbeat' => 'ping',
|
||||
'event' => 'event',
|
||||
'events' => 'events',
|
||||
'status' => 'status',
|
||||
'evaluate' => 'evaluate',
|
||||
default => 'status',
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user