{
"tool_response": {
"filePath": "\/var\/www\/dev.campus.systemische-tools.de\/src\/Infrastructure\/Persistence\/FileBackupRepository.php",
"oldString": " \/**\n * Restore a file from backup.\n *\n * @throws \\RuntimeException If restore fails\n *\/\n public function restore(int $id): bool\n {\n $backup = $this->findById($id);\n\n if ($backup === null) {\n throw new \\RuntimeException('Backup not found');\n }\n\n $filePath = $backup['file_path'];\n $content = $backup['file_content'];\n\n \/\/ Check if directory exists\n $dir = dirname($filePath);\n if (!is_dir($dir)) {\n throw new \\RuntimeException(\"Directory does not exist: {$dir}\");\n }\n\n \/\/ Write content back to file\n $result = file_put_contents($filePath, $content);\n\n if ($result === false) {\n throw new \\RuntimeException(\"Failed to write to file: {$filePath}\");\n }\n\n \/\/ Log the restore action\n $this->logRestore($id, $filePath);\n\n return true;\n }",
"newString": " \/**\n * Restore a file from backup.\n *\n * @throws \\RuntimeException If restore fails\n * @throws \\SecurityException If path validation fails\n *\/\n public function restore(int $id): bool\n {\n $backup = $this->findById($id);\n\n if ($backup === null) {\n throw new \\RuntimeException('Backup not found');\n }\n\n $filePath = $backup['file_path'];\n $content = $backup['file_content'];\n\n \/\/ SECURITY: Validate the restore path before writing\n $this->validateRestorePath($filePath);\n\n \/\/ Check if directory exists\n $dir = dirname($filePath);\n if (!is_dir($dir)) {\n throw new \\RuntimeException(\"Directory does not exist: {$dir}\");\n }\n\n \/\/ Write content back to file\n $result = file_put_contents($filePath, $content);\n\n if ($result === false) {\n throw new \\RuntimeException(\"Failed to write to file: {$filePath}\");\n }\n\n \/\/ Log the restore action\n $this->logRestore($id, $filePath);\n\n return true;\n }\n\n \/**\n * Validate that a file path is safe for restoration.\n *\n * @throws \\RuntimeException If path is not allowed\n *\/\n private function validateRestorePath(string $filePath): void\n {\n \/\/ Check for path traversal attempts\n if (str_contains($filePath, '..')) {\n $this->logSecurityViolation('path_traversal', $filePath);\n throw new \\RuntimeException('Invalid path: path traversal detected');\n }\n\n \/\/ Normalize the path\n $dir = dirname($filePath);\n $realDir = realpath($dir);\n\n if ($realDir === false) {\n throw new \\RuntimeException('Invalid path: directory does not exist');\n }\n\n \/\/ Reconstruct full path with real directory\n $normalizedPath = $realDir . '\/' . basename($filePath);\n\n \/\/ Check against allowlist\n $isAllowed = false;\n foreach (self::ALLOWED_RESTORE_PATHS as $allowedPath) {\n if (str_starts_with($normalizedPath, $allowedPath)) {\n $isAllowed = true;\n break;\n }\n }\n\n if (!$isAllowed) {\n $this->logSecurityViolation('path_not_allowed', $filePath);\n throw new \\RuntimeException('Invalid path: restore location not permitted');\n }\n }\n\n \/**\n * Log security violation attempts.\n *\/\n private function logSecurityViolation(string $type, string $filePath): void\n {\n $stmt = $this->db->prepare(\n \"INSERT INTO mcp_log (tool, operation, parameters, result, logged_at)\n VALUES ('backup_restore', 'security_violation', :params, 'blocked', NOW())\"\n );\n $stmt->execute([\n 'params' => json_encode([\n 'violation_type' => $type,\n 'attempted_path' => $filePath,\n 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',\n ]),\n ]);\n }",
"originalFile": "<?php\n\ndeclare(strict_types=1);\n\nnamespace Infrastructure\\Persistence;\n\nuse Infrastructure\\Config\\DatabaseFactory;\nuse PDO;\n\n\/**\n * Repository for file_backup_history table.\n *\/\nclass FileBackupRepository\n{\n private PDO $db;\n\n \/**\n * Allowlist of base paths where file restoration is permitted.\n * Only files within these directories can be restored.\n *\/\n private const ALLOWED_RESTORE_PATHS = [\n '\/var\/www\/dev.campus.systemische-tools.de\/',\n '\/var\/www\/prod.campus.systemische-tools.de\/',\n ];\n\n public function __construct()\n {\n $this->db = DatabaseFactory::dev();\n }\n\n \/**\n * Find all backups with optional filters.\n *\n * @param array<string, mixed> $filters\n *\/\n public function findAll(array $filters = [], int $limit = 50, int $offset = 0): array\n {\n $sql = 'SELECT id, file_path, content_hash, file_size, version, change_type,\n changed_at, changed_by, reason\n FROM file_backup_history WHERE 1=1';\n $params = [];\n\n if (!empty($filters['search'])) {\n $sql .= ' AND file_path LIKE :search';\n $params['search'] = '%' . $filters['search'] . '%';\n }\n\n if (!empty($filters['change_type'])) {\n $sql .= ' AND change_type = :change_type';\n $params['change_type'] = $filters['change_type'];\n }\n\n $sql .= ' ORDER BY changed_at DESC LIMIT :limit OFFSET :offset';\n\n $stmt = $this->db->prepare($sql);\n foreach ($params as $key => $value) {\n $stmt->bindValue($key, $value);\n }\n $stmt->bindValue('limit', $limit, PDO::PARAM_INT);\n $stmt->bindValue('offset', $offset, PDO::PARAM_INT);\n $stmt->execute();\n\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n \/**\n * Count total backups with filters.\n *\n * @param array<string, mixed> $filters\n *\/\n public function count(array $filters = []): int\n {\n $sql = 'SELECT COUNT(*) FROM file_backup_history WHERE 1=1';\n $params = [];\n\n if (!empty($filters['search'])) {\n $sql .= ' AND file_path LIKE :search';\n $params['search'] = '%' . $filters['search'] . '%';\n }\n\n if (!empty($filters['change_type'])) {\n $sql .= ' AND change_type = :change_type';\n $params['change_type'] = $filters['change_type'];\n }\n\n $stmt = $this->db->prepare($sql);\n $stmt->execute($params);\n\n return (int) $stmt->fetchColumn();\n }\n\n \/**\n * Find backup by ID.\n *\/\n public function findById(int $id): ?array\n {\n $stmt = $this->db->prepare(\n 'SELECT * FROM file_backup_history WHERE id = :id'\n );\n $stmt->execute(['id' => $id]);\n $result = $stmt->fetch(PDO::FETCH_ASSOC);\n\n return $result !== false ? $result : null;\n }\n\n \/**\n * Find all backups for a specific file path.\n *\/\n public function findByFilePath(string $path): array\n {\n $stmt = $this->db->prepare(\n 'SELECT id, file_path, content_hash, file_size, version, change_type,\n changed_at, changed_by, reason\n FROM file_backup_history\n WHERE file_path = :path\n ORDER BY version DESC'\n );\n $stmt->execute(['path' => $path]);\n\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n \/**\n * Get statistics about backups.\n *\n * @return array<string, int>\n *\/\n public function getStatistics(): array\n {\n $stats = [];\n\n \/\/ Total backups\n $stats['total'] = (int) $this->db->query(\n 'SELECT COUNT(*) FROM file_backup_history'\n )->fetchColumn();\n\n \/\/ Unique files\n $stats['files'] = (int) $this->db->query(\n 'SELECT COUNT(DISTINCT file_path) FROM file_backup_history'\n )->fetchColumn();\n\n \/\/ Total versions (max version per file summed)\n $stats['versions'] = (int) $this->db->query(\n 'SELECT COALESCE(SUM(max_version), 0) FROM (\n SELECT MAX(version) as max_version FROM file_backup_history GROUP BY file_path\n ) as v'\n )->fetchColumn();\n\n \/\/ Last 24 hours\n $stats['recent'] = (int) $this->db->query(\n 'SELECT COUNT(*) FROM file_backup_history WHERE changed_at >= NOW() - INTERVAL 24 HOUR'\n )->fetchColumn();\n\n \/\/ By change type\n $stats['created'] = (int) $this->db->query(\n \"SELECT COUNT(*) FROM file_backup_history WHERE change_type = 'created'\"\n )->fetchColumn();\n\n $stats['modified'] = (int) $this->db->query(\n \"SELECT COUNT(*) FROM file_backup_history WHERE change_type = 'modified'\"\n )->fetchColumn();\n\n return $stats;\n }\n\n \/**\n * Restore a file from backup.\n *\n * @throws \\RuntimeException If restore fails\n *\/\n public function restore(int $id): bool\n {\n $backup = $this->findById($id);\n\n if ($backup === null) {\n throw new \\RuntimeException('Backup not found');\n }\n\n $filePath = $backup['file_path'];\n $content = $backup['file_content'];\n\n \/\/ Check if directory exists\n $dir = dirname($filePath);\n if (!is_dir($dir)) {\n throw new \\RuntimeException(\"Directory does not exist: {$dir}\");\n }\n\n \/\/ Write content back to file\n $result = file_put_contents($filePath, $content);\n\n if ($result === false) {\n throw new \\RuntimeException(\"Failed to write to file: {$filePath}\");\n }\n\n \/\/ Log the restore action\n $this->logRestore($id, $filePath);\n\n return true;\n }\n\n \/**\n * Log restore action to mcp_log.\n *\/\n private function logRestore(int $backupId, string $filePath): void\n {\n $stmt = $this->db->prepare(\n \"INSERT INTO mcp_log (tool, operation, parameters, result, logged_at)\n VALUES ('backup_restore', 'restore', :params, 'success', NOW())\"\n );\n $stmt->execute([\n 'params' => json_encode(['backup_id' => $backupId, 'file_path' => $filePath]),\n ]);\n }\n\n \/**\n * Get content preview (first N lines).\n *\/\n public function getContentPreview(int $id, int $maxLines = 500): ?string\n {\n $backup = $this->findById($id);\n\n if ($backup === null || empty($backup['file_content'])) {\n return null;\n }\n\n $lines = explode(\"\\n\", $backup['file_content']);\n\n if (count($lines) <= $maxLines) {\n return $backup['file_content'];\n }\n\n return implode(\"\\n\", array_slice($lines, 0, $maxLines)) . \"\\n\\n... (\" . (count($lines) - $maxLines) . ' weitere Zeilen)';\n }\n}\n",
"structuredPatch": [
{
"oldStart": 167,
"oldLines": 6,
"newStart": 167,
"newLines": 7,
"lines": [
" * Restore a file from backup.",
" *",
" * @throws \\RuntimeException If restore fails",
"+ * @throws \\SecurityException If path validation fails",
" *\/",
" public function restore(int $id): bool",
" {"
]
},
{
"oldStart": 179,
"oldLines": 6,
"newStart": 180,
"newLines": 9,
"lines": [
" $filePath = $backup['file_path'];",
" $content = $backup['file_content'];",
" ",
"+ \/\/ SECURITY: Validate the restore path before writing",
"+ $this->validateRestorePath($filePath);",
"+",
" \/\/ Check if directory exists",
" $dir = dirname($filePath);",
" if (!is_dir($dir)) {"
]
},
{
"oldStart": 199,
"oldLines": 6,
"newStart": 203,
"newLines": 63,
"lines": [
" }",
" ",
" \/**",
"+ * Validate that a file path is safe for restoration.",
"+ *",
"+ * @throws \\RuntimeException If path is not allowed",
"+ *\/",
"+ private function validateRestorePath(string $filePath): void",
"+ {",
"+ \/\/ Check for path traversal attempts",
"+ if (str_contains($filePath, '..')) {",
"+ $this->logSecurityViolation('path_traversal', $filePath);",
"+ throw new \\RuntimeException('Invalid path: path traversal detected');",
"+ }",
"+",
"+ \/\/ Normalize the path",
"+ $dir = dirname($filePath);",
"+ $realDir = realpath($dir);",
"+",
"+ if ($realDir === false) {",
"+ throw new \\RuntimeException('Invalid path: directory does not exist');",
"+ }",
"+",
"+ \/\/ Reconstruct full path with real directory",
"+ $normalizedPath = $realDir . '\/' . basename($filePath);",
"+",
"+ \/\/ Check against allowlist",
"+ $isAllowed = false;",
"+ foreach (self::ALLOWED_RESTORE_PATHS as $allowedPath) {",
"+ if (str_starts_with($normalizedPath, $allowedPath)) {",
"+ $isAllowed = true;",
"+ break;",
"+ }",
"+ }",
"+",
"+ if (!$isAllowed) {",
"+ $this->logSecurityViolation('path_not_allowed', $filePath);",
"+ throw new \\RuntimeException('Invalid path: restore location not permitted');",
"+ }",
"+ }",
"+",
"+ \/**",
"+ * Log security violation attempts.",
"+ *\/",
"+ private function logSecurityViolation(string $type, string $filePath): void",
"+ {",
"+ $stmt = $this->db->prepare(",
"+ \"INSERT INTO mcp_log (tool, operation, parameters, result, logged_at)",
"+ VALUES ('backup_restore', 'security_violation', :params, 'blocked', NOW())\"",
"+ );",
"+ $stmt->execute([",
"+ 'params' => json_encode([",
"+ 'violation_type' => $type,",
"+ 'attempted_path' => $filePath,",
"+ 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',",
"+ ]),",
"+ ]);",
"+ }",
"+",
"+ \/**",
" * Log restore action to mcp_log.",
" *\/",
" private function logRestore(int $backupId, string $filePath): void"
]
}
],
"userModified": false,
"replaceAll": false
}
}