This commit is contained in:
Sebastian Almberg 2026-02-25 19:36:54 +01:00 committed by GitHub
commit a7ee70da01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 466 additions and 29 deletions

View file

@ -24,14 +24,17 @@ declare(strict_types=1);
namespace App\Controller;
use App\Services\System\BackupManager;
use App\Services\System\InstallationTypeDetector;
use App\Services\System\UpdateChecker;
use App\Services\System\UpdateExecutor;
use Shivas\VersioningBundle\Service\VersionManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Attribute\Route;
@ -49,6 +52,7 @@ class UpdateManagerController extends AbstractController
private readonly UpdateExecutor $updateExecutor,
private readonly VersionManagerInterface $versionManager,
private readonly BackupManager $backupManager,
private readonly InstallationTypeDetector $installationTypeDetector,
#[Autowire(env: 'bool:DISABLE_WEB_UPDATES')]
private readonly bool $webUpdatesDisabled = false,
#[Autowire(env: 'bool:DISABLE_BACKUP_RESTORE')]
@ -101,6 +105,7 @@ class UpdateManagerController extends AbstractController
'backups' => $this->backupManager->getBackups(),
'web_updates_disabled' => $this->webUpdatesDisabled,
'backup_restore_disabled' => $this->backupRestoreDisabled,
'is_docker' => $this->installationTypeDetector->isDocker(),
]);
}
@ -314,6 +319,99 @@ class UpdateManagerController extends AbstractController
return $this->json($details);
}
/**
* Create a manual backup.
*/
#[Route('/backup', name: 'admin_update_manager_backup', methods: ['POST'])]
public function createBackup(Request $request): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
if (!$this->isCsrfTokenValid('update_manager_backup', $request->request->get('_token'))) {
$this->addFlash('error', 'Invalid CSRF token.');
return $this->redirectToRoute('admin_update_manager');
}
if ($this->updateExecutor->isLocked()) {
$this->addFlash('error', 'Cannot create backup while an update is in progress.');
return $this->redirectToRoute('admin_update_manager');
}
try {
$backupPath = $this->backupManager->createBackup(null, 'manual');
$this->addFlash('success', 'update_manager.backup.created');
} catch (\Exception $e) {
$this->addFlash('error', 'Backup failed: ' . $e->getMessage());
}
return $this->redirectToRoute('admin_update_manager');
}
/**
* Delete a backup file.
*/
#[Route('/backup/delete', name: 'admin_update_manager_backup_delete', methods: ['POST'])]
public function deleteBackup(Request $request): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
if (!$this->isCsrfTokenValid('update_manager_delete', $request->request->get('_token'))) {
$this->addFlash('error', 'Invalid CSRF token.');
return $this->redirectToRoute('admin_update_manager');
}
$filename = $request->request->get('filename');
if ($filename && $this->backupManager->deleteBackup($filename)) {
$this->addFlash('success', 'update_manager.backup.deleted');
} else {
$this->addFlash('error', 'update_manager.backup.delete_error');
}
return $this->redirectToRoute('admin_update_manager');
}
/**
* Delete an update log file.
*/
#[Route('/log/delete', name: 'admin_update_manager_log_delete', methods: ['POST'])]
public function deleteLog(Request $request): Response
{
$this->denyAccessUnlessGranted('@system.manage_updates');
if (!$this->isCsrfTokenValid('update_manager_delete', $request->request->get('_token'))) {
$this->addFlash('error', 'Invalid CSRF token.');
return $this->redirectToRoute('admin_update_manager');
}
$filename = $request->request->get('filename');
if ($filename && $this->updateExecutor->deleteLog($filename)) {
$this->addFlash('success', 'update_manager.log.deleted');
} else {
$this->addFlash('error', 'update_manager.log.delete_error');
}
return $this->redirectToRoute('admin_update_manager');
}
/**
* Download a backup file.
*/
#[Route('/backup/download/{filename}', name: 'admin_update_manager_backup_download', methods: ['GET'])]
public function downloadBackup(string $filename): BinaryFileResponse
{
$this->denyAccessUnlessGranted('@system.manage_updates');
$details = $this->backupManager->getBackupDetails($filename);
if (!$details) {
throw $this->createNotFoundException('Backup not found');
}
$response = new BinaryFileResponse($details['path']);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $details['file']);
return $response;
}
/**
* Restore from a backup.
*/

View file

@ -327,14 +327,14 @@ readonly class BackupManager
*/
private function restoreDatabaseFromBackup(string $tempDir): void
{
// Get database connection params from Doctrine
$connection = $this->entityManager->getConnection();
$params = $connection->getParams();
$platform = $connection->getDatabasePlatform();
// Check for SQL dump (MySQL/PostgreSQL)
$sqlFile = $tempDir . '/database.sql';
if (file_exists($sqlFile)) {
// Import SQL using mysql/psql command directly
// First, get database connection params from Doctrine
$connection = $this->entityManager->getConnection();
$params = $connection->getParams();
$platform = $connection->getDatabasePlatform();
if ($platform instanceof AbstractMySQLPlatform) {
// Use mysql command to import - need to use shell to handle input redirection
@ -403,7 +403,8 @@ readonly class BackupManager
// Check for SQLite database file
$sqliteFile = $tempDir . '/var/app.db';
if (file_exists($sqliteFile)) {
$targetDb = $this->projectDir . '/var/app.db';
// Use the actual configured SQLite path from Doctrine, not a hardcoded path
$targetDb = $params['path'] ?? $this->projectDir . '/var/app.db';
$this->filesystem->copy($sqliteFile, $targetDb, true);
return;
}

View file

@ -602,6 +602,33 @@ class UpdateExecutor
}
/**
* Delete a specific update log file.
*/
public function deleteLog(string $filename): bool
{
// Validate filename pattern for security
if (!preg_match('/^update-[\w.\-]+\.log$/', $filename)) {
$this->logger->warning('Attempted to delete invalid log filename: ' . $filename);
return false;
}
$logPath = $this->project_dir . '/' . self::UPDATE_LOG_DIR . '/' . $filename;
if (!file_exists($logPath)) {
return false;
}
try {
$this->filesystem->remove($logPath);
$this->logger->info('Deleted update log: ' . $filename);
return true;
} catch (\Exception $e) {
$this->logger->error('Failed to delete update log: ' . $e->getMessage());
return false;
}
}
/**
* Restore from a backup file with maintenance mode and cache clearing.
*

View file

@ -343,11 +343,26 @@
{{ log.date|date('Y-m-d H:i') }}
</td>
<td><code class="small">{{ log.file }}</code></td>
<td>
<a href="{{ path('admin_update_manager_log', {filename: log.file}) }}"
class="btn btn-sm btn-outline-secondary">
<i class="fas fa-eye"></i>
</a>
<td class="text-end">
<div class="btn-group btn-group-sm">
<a href="{{ path('admin_update_manager_log', {filename: log.file}) }}"
class="btn btn-outline-secondary"
title="{% trans %}update_manager.view_log{% endtrans %}">
<i class="fas fa-eye"></i>
</a>
{% if is_granted('@system.manage_updates') %}
<form action="{{ path('admin_update_manager_log_delete') }}" method="post" class="d-inline"
data-turbo-confirm="{% trans %}update_manager.log.delete.confirm{% endtrans %}">
<input type="hidden" name="_token" value="{{ csrf_token('update_manager_delete') }}">
<input type="hidden" name="filename" value="{{ log.file }}">
<button type="submit"
class="btn btn-outline-danger"
title="{% trans %}update_manager.delete{% endtrans %}">
<i class="fas fa-trash-alt"></i>
</button>
</form>
{% endif %}
</div>
</td>
</tr>
{% else %}
@ -362,6 +377,23 @@
</div>
</div>
<div class="tab-pane fade" id="backups-tab">
{% if is_granted('@system.manage_updates') and not is_locked %}
<div class="p-2 border-bottom">
<form action="{{ path('admin_update_manager_backup') }}" method="post" class="d-inline"
data-turbo-confirm="{% trans %}update_manager.backup.create.confirm{% endtrans %}">
<input type="hidden" name="_token" value="{{ csrf_token('update_manager_backup') }}">
<button type="submit" class="btn btn-sm btn-success">
<i class="fas fa-plus me-1"></i>{% trans %}update_manager.backup.create{% endtrans %}
</button>
</form>
</div>
{% endif %}
{% if is_docker %}
<div class="alert alert-info alert-sm m-2 mb-0 py-2 small">
<i class="fas fa-info-circle me-1"></i>
{% trans %}update_manager.backup.docker_warning{% endtrans %}
</div>
{% endif %}
<div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
<table class="table table-hover table-sm mb-0">
<thead class="sticky-top" style="background-color: #f8f9fa;">
@ -383,24 +415,45 @@
{{ (backup.size / 1024 / 1024)|number_format(1) }} MB
</td>
<td class="text-end">
{% if status.can_auto_update and validation.valid and not backup_restore_disabled %}
<form action="{{ path('admin_update_manager_restore') }}" method="post" class="d-inline"
data-controller="backup-restore"
data-backup-restore-filename-value="{{ backup.file }}"
data-backup-restore-date-value="{{ backup.date|date('Y-m-d H:i') }}"
data-backup-restore-confirm-title-value="{{ 'update_manager.restore_confirm_title'|trans }}"
data-backup-restore-confirm-message-value="{{ 'update_manager.restore_confirm_message'|trans }}"
data-backup-restore-confirm-warning-value="{{ 'update_manager.restore_confirm_warning'|trans }}">
<input type="hidden" name="_token" value="{{ csrf_token('update_manager_restore') }}">
<input type="hidden" name="filename" value="{{ backup.file }}">
<input type="hidden" name="restore_database" value="1">
<button type="submit"
class="btn btn-sm btn-outline-warning"
title="{% trans %}update_manager.restore_backup{% endtrans %}">
<i class="fas fa-undo"></i>
</button>
</form>
{% endif %}
<div class="btn-group btn-group-sm">
{% if is_granted('@system.manage_updates') %}
<a href="{{ path('admin_update_manager_backup_download', {filename: backup.file}) }}"
class="btn btn-outline-secondary"
title="{% trans %}update_manager.backup.download{% endtrans %}">
<i class="fas fa-download"></i>
</a>
{% endif %}
{% if not backup_restore_disabled and is_granted('@system.manage_updates') %}
<form action="{{ path('admin_update_manager_restore') }}" method="post" class="d-inline"
data-controller="backup-restore"
data-backup-restore-filename-value="{{ backup.file }}"
data-backup-restore-date-value="{{ backup.date|date('Y-m-d H:i') }}"
data-backup-restore-confirm-title-value="{{ 'update_manager.restore_confirm_title'|trans }}"
data-backup-restore-confirm-message-value="{{ 'update_manager.restore_confirm_message'|trans }}"
data-backup-restore-confirm-warning-value="{{ 'update_manager.restore_confirm_warning'|trans }}">
<input type="hidden" name="_token" value="{{ csrf_token('update_manager_restore') }}">
<input type="hidden" name="filename" value="{{ backup.file }}">
<input type="hidden" name="restore_database" value="1">
<button type="submit"
class="btn btn-outline-warning"
title="{% trans %}update_manager.restore_backup{% endtrans %}">
<i class="fas fa-undo"></i>
</button>
</form>
{% endif %}
{% if is_granted('@system.manage_updates') %}
<form action="{{ path('admin_update_manager_backup_delete') }}" method="post" class="d-inline"
data-turbo-confirm="{% trans %}update_manager.backup.delete.confirm{% endtrans %}">
<input type="hidden" name="_token" value="{{ csrf_token('update_manager_delete') }}">
<input type="hidden" name="filename" value="{{ backup.file }}">
<button type="submit"
class="btn btn-outline-danger"
title="{% trans %}update_manager.delete{% endtrans %}">
<i class="fas fa-trash-alt"></i>
</button>
</form>
{% endif %}
</div>
</td>
</tr>
{% else %}

View file

@ -0,0 +1,138 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace App\Tests\Controller;
use App\Entity\UserSystem\User;
use PHPUnit\Framework\Attributes\Group;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
#[Group("slow")]
#[Group("DB")]
final class UpdateManagerControllerTest extends WebTestCase
{
private function loginAsAdmin($client): void
{
$entityManager = $client->getContainer()->get('doctrine')->getManager();
$userRepository = $entityManager->getRepository(User::class);
$user = $userRepository->findOneBy(['name' => 'admin']);
if (!$user) {
$this->markTestSkipped('Admin user not found');
}
$client->loginUser($user);
}
public function testIndexPageRequiresAuth(): void
{
$client = static::createClient();
$client->request('GET', '/en/system/update-manager');
// Should deny access (401 with HTTP Basic auth in test env)
$this->assertResponseStatusCodeSame(401);
}
public function testIndexPageAccessibleByAdmin(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('GET', '/en/system/update-manager');
$this->assertResponseIsSuccessful();
}
public function testCreateBackupRequiresCsrf(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('POST', '/en/system/update-manager/backup', [
'_token' => 'invalid',
]);
// Should redirect with error flash
$this->assertResponseRedirects();
}
public function testDeleteBackupRequiresCsrf(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('POST', '/en/system/update-manager/backup/delete', [
'_token' => 'invalid',
'filename' => 'test.zip',
]);
$this->assertResponseRedirects();
}
public function testDeleteLogRequiresCsrf(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('POST', '/en/system/update-manager/log/delete', [
'_token' => 'invalid',
'filename' => 'test.log',
]);
$this->assertResponseRedirects();
}
public function testDownloadBackupReturns404ForNonExistent(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('GET', '/en/system/update-manager/backup/download/nonexistent.zip');
$this->assertResponseStatusCodeSame(404);
}
public function testBackupDetailsReturns404ForNonExistent(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
$client->request('GET', '/en/system/update-manager/backup/nonexistent.zip');
$this->assertResponseStatusCodeSame(404);
}
public function testRestoreBlockedWhenDisabled(): void
{
$client = static::createClient();
$this->loginAsAdmin($client);
// DISABLE_BACKUP_RESTORE=1 is the default in .env, so this should return 403
$client->request('POST', '/en/system/update-manager/restore', [
'_token' => 'invalid',
'filename' => 'test.zip',
]);
$this->assertResponseStatusCodeSame(403);
}
}

View file

@ -82,6 +82,16 @@ final class BackupManagerTest extends KernelTestCase
$this->assertSame('2.6.0', $matches[2]);
}
public function testDeleteBackupReturnsFalseForNonExistentFile(): void
{
$this->assertFalse($this->backupManager->deleteBackup('non-existent.zip'));
}
public function testDeleteBackupReturnsFalseForNonZipFile(): void
{
$this->assertFalse($this->backupManager->deleteBackup('not-a-zip.txt'));
}
/**
* Test version parsing with different filename formats.
*/

View file

@ -139,6 +139,38 @@ final class UpdateExecutorTest extends KernelTestCase
$this->assertFalse($this->updateExecutor->isLocked());
}
public function testDeleteLogRejectsInvalidFilename(): void
{
// Path traversal attempts should be rejected
$this->assertFalse($this->updateExecutor->deleteLog('../../../etc/passwd'));
$this->assertFalse($this->updateExecutor->deleteLog('malicious.txt'));
$this->assertFalse($this->updateExecutor->deleteLog(''));
// Must start with "update-"
$this->assertFalse($this->updateExecutor->deleteLog('backup-v1.0.0.log'));
}
public function testDeleteLogReturnsFalseForNonExistentFile(): void
{
$this->assertFalse($this->updateExecutor->deleteLog('update-nonexistent-file.log'));
}
public function testDeleteLogDeletesExistingFile(): void
{
// Create a temporary log file in the update logs directory
$projectDir = self::getContainer()->getParameter('kernel.project_dir');
$logDir = $projectDir . '/var/log/updates';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$testFile = 'update-test-delete-' . uniqid() . '.log';
file_put_contents($logDir . '/' . $testFile, 'test log content');
$this->assertTrue($this->updateExecutor->deleteLog($testFile));
$this->assertFileDoesNotExist($logDir . '/' . $testFile);
}
public function testEnableAndDisableMaintenanceMode(): void
{
// First, ensure maintenance mode is off

View file

@ -12335,6 +12335,84 @@ Buerklin-API Authentication server:
<target>Backup restore is disabled by server configuration.</target>
</segment>
</unit>
<unit id="um_bk_create" name="update_manager.backup.create">
<segment state="translated">
<source>update_manager.backup.create</source>
<target>Create Backup</target>
</segment>
</unit>
<unit id="um_bk_create_confirm" name="update_manager.backup.create.confirm">
<segment state="translated">
<source>update_manager.backup.create.confirm</source>
<target>Create a full backup now? This may take a moment.</target>
</segment>
</unit>
<unit id="um_bk_created" name="update_manager.backup.created">
<segment state="translated">
<source>update_manager.backup.created</source>
<target>Backup created successfully.</target>
</segment>
</unit>
<unit id="um_bk_del_confirm" name="update_manager.backup.delete.confirm">
<segment state="translated">
<source>update_manager.backup.delete.confirm</source>
<target>Are you sure you want to delete this backup?</target>
</segment>
</unit>
<unit id="um_bk_deleted" name="update_manager.backup.deleted">
<segment state="translated">
<source>update_manager.backup.deleted</source>
<target>Backup deleted successfully.</target>
</segment>
</unit>
<unit id="um_bk_del_err" name="update_manager.backup.delete_error">
<segment state="translated">
<source>update_manager.backup.delete_error</source>
<target>Failed to delete backup.</target>
</segment>
</unit>
<unit id="um_log_del_confirm" name="update_manager.log.delete.confirm">
<segment state="translated">
<source>update_manager.log.delete.confirm</source>
<target>Are you sure you want to delete this log?</target>
</segment>
</unit>
<unit id="um_log_deleted" name="update_manager.log.deleted">
<segment state="translated">
<source>update_manager.log.deleted</source>
<target>Log deleted successfully.</target>
</segment>
</unit>
<unit id="um_log_del_err" name="update_manager.log.delete_error">
<segment state="translated">
<source>update_manager.log.delete_error</source>
<target>Failed to delete log.</target>
</segment>
</unit>
<unit id="um_view_log" name="update_manager.view_log">
<segment state="translated">
<source>update_manager.view_log</source>
<target>View log</target>
</segment>
</unit>
<unit id="um_delete" name="update_manager.delete">
<segment state="translated">
<source>update_manager.delete</source>
<target>Delete</target>
</segment>
</unit>
<unit id="um_bk_download" name="update_manager.backup.download">
<segment state="translated">
<source>update_manager.backup.download</source>
<target>Download backup</target>
</segment>
</unit>
<unit id="um_bk_docker_warning" name="update_manager.backup.docker_warning">
<segment state="translated">
<source>update_manager.backup.docker_warning</source>
<target>Docker installation detected. Backups are stored in var/backups/ which is not a persistent volume. Use the download button to save backups externally, or mount var/backups/ as a volume in your docker-compose.yml.</target>
</segment>
</unit>
<unit id="kHKChQB" name="settings.ips.conrad">
<segment state="translated">
<source>settings.ips.conrad</source>