Part-DB-server/tests/Services/System/UpdateExecutorTest.php

200 lines
6.7 KiB
PHP
Raw Normal View History

<?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\Services\System;
use App\Services\System\UpdateExecutor;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
2026-02-14 23:32:43 +01:00
final class UpdateExecutorTest extends KernelTestCase
{
private ?UpdateExecutor $updateExecutor = null;
protected function setUp(): void
{
self::bootKernel();
$this->updateExecutor = self::getContainer()->get(UpdateExecutor::class);
}
public function testIsLockedReturnsFalseWhenNoLockFile(): void
{
// Initially there should be no lock
// Note: This test assumes no concurrent update is running
$isLocked = $this->updateExecutor->isLocked();
$this->assertIsBool($isLocked);
}
public function testIsMaintenanceModeReturnsBool(): void
{
$isMaintenanceMode = $this->updateExecutor->isMaintenanceMode();
$this->assertIsBool($isMaintenanceMode);
}
public function testGetLockInfoReturnsNullOrArray(): void
{
$lockInfo = $this->updateExecutor->getLockInfo();
// Should be null when not locked, or array when locked
$this->assertTrue($lockInfo === null || is_array($lockInfo));
}
public function testGetMaintenanceInfoReturnsNullOrArray(): void
{
$maintenanceInfo = $this->updateExecutor->getMaintenanceInfo();
// Should be null when not in maintenance, or array when in maintenance
$this->assertTrue($maintenanceInfo === null || is_array($maintenanceInfo));
}
public function testGetUpdateLogsReturnsArray(): void
{
$logs = $this->updateExecutor->getUpdateLogs();
$this->assertIsArray($logs);
}
public function testValidateUpdatePreconditionsReturnsProperStructure(): void
{
$validation = $this->updateExecutor->validateUpdatePreconditions();
$this->assertIsArray($validation);
$this->assertArrayHasKey('valid', $validation);
$this->assertArrayHasKey('errors', $validation);
$this->assertIsBool($validation['valid']);
$this->assertIsArray($validation['errors']);
}
public function testGetProgressFilePath(): void
{
$progressPath = $this->updateExecutor->getProgressFilePath();
$this->assertIsString($progressPath);
$this->assertStringEndsWith('var/update_progress.json', $progressPath);
}
public function testGetProgressReturnsNullOrArray(): void
{
$progress = $this->updateExecutor->getProgress();
// Should be null when no progress file, or array when exists
$this->assertTrue($progress === null || is_array($progress));
}
public function testIsUpdateRunningReturnsBool(): void
{
$isRunning = $this->updateExecutor->isUpdateRunning();
$this->assertIsBool($isRunning);
}
public function testAcquireAndReleaseLock(): void
{
// First, ensure no lock exists
if ($this->updateExecutor->isLocked()) {
$this->updateExecutor->releaseLock();
}
// Acquire lock
$acquired = $this->updateExecutor->acquireLock();
$this->assertTrue($acquired);
// Should be locked now
$this->assertTrue($this->updateExecutor->isLocked());
// Lock info should exist
$lockInfo = $this->updateExecutor->getLockInfo();
$this->assertIsArray($lockInfo);
$this->assertArrayHasKey('started_at', $lockInfo);
// Trying to acquire again should fail
$acquiredAgain = $this->updateExecutor->acquireLock();
$this->assertFalse($acquiredAgain);
// Release lock
$this->updateExecutor->releaseLock();
// Should no longer be locked
$this->assertFalse($this->updateExecutor->isLocked());
}
Add manual backup creation and delete buttons to Update Manager (#1255) * Add manual backup creation and delete buttons to Update Manager - Add "Create Backup" button in the backups tab for on-demand backups - Add delete buttons (trash icons) for update logs and backups - New controller routes with CSRF protection and permission checks - Use data-turbo-confirm for CSP-safe confirmation dialogs - Add deleteLog() method to UpdateExecutor with filename validation * Add Docker backup support: download button, SQLite restore fix, decouple from auto-update - Decouple backup creation/restore UI from can_auto_update so Docker and other non-git installations can use backup features - Add backup download endpoint for saving backups externally - Fix SQLite restore to use configured DATABASE_URL path instead of hardcoded var/app.db (affects Docker and custom SQLite paths) - Show Docker-specific warning about var/backups/ not being persisted - Pass is_docker flag to template via InstallationTypeDetector * Add tests for backup/update manager improvements - Controller tests: auth, CSRF validation, 404 for missing backups, restore disabled check - UpdateExecutor: deleteLog validation, non-existent file, successful deletion - BackupManager: deleteBackup validation for missing/non-zip files * Fix test failures: add locale prefix to URLs, correct log directory path * Fix auth test: expect 401 instead of redirect for HTTP Basic auth * Improve test coverage for update manager controller Add happy-path tests for backup creation, deletion, download, and log deletion with valid CSRF tokens. Also test the locked state blocking backup creation. * Fix CSRF tests: initialize session before getting tokens * Fix CSRF tests: extract tokens from rendered page HTML * Harden backup security: password confirmation, CSRF, env toggle Address security review feedback from jbtronics: - Add IS_AUTHENTICATED_FULLY to all sensitive endpoints (create/delete backup, delete log, download backup, start update, restore) - Change backup download from GET to POST with CSRF token - Require password confirmation before downloading backups (backups contain sensitive data like password hashes and secrets) - Add DISABLE_BACKUP_DOWNLOAD env var (default: disabled) to control whether backup downloads are allowed - Add password confirmation modal with security warning in template - Add comprehensive tests: auth checks, env var blocking, POST-only enforcement, status/progress endpoint auth * Fix download modal: use per-backup modals for CSP/Turbo compatibility - Replace shared modal + inline JS with per-backup modals that have filename pre-set in hidden fields (no JavaScript needed) - Add data-turbo="false" to download forms for native browser handling - Add data-bs-dismiss="modal" to submit button to auto-close modal - Add hidden username field for Chrome accessibility best practice - Fix test: GET on POST-only route returns 404 not 405 * Fixed translation keys * Fixed text justification in download modal * Hardenened security of deleteLogEndpoint * Show whether backup, restores and updates are allowed or disabled by sysadmin on update manager * Added documentation for update manager related env variables --------- Co-authored-by: Jan Böhmer <mail@jan-boehmer.de>
2026-03-07 19:31:00 +01:00
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
if ($this->updateExecutor->isMaintenanceMode()) {
$this->updateExecutor->disableMaintenanceMode();
}
// Enable maintenance mode
$this->updateExecutor->enableMaintenanceMode('Test maintenance');
// Should be in maintenance mode now
$this->assertTrue($this->updateExecutor->isMaintenanceMode());
// Maintenance info should exist
$maintenanceInfo = $this->updateExecutor->getMaintenanceInfo();
$this->assertIsArray($maintenanceInfo);
$this->assertArrayHasKey('reason', $maintenanceInfo);
$this->assertEquals('Test maintenance', $maintenanceInfo['reason']);
// Disable maintenance mode
$this->updateExecutor->disableMaintenanceMode();
// Should no longer be in maintenance mode
$this->assertFalse($this->updateExecutor->isMaintenanceMode());
}
}