A free open source IT asset/license management system
Added file purge to restore
snipe74d154850db1
diff --git a/app/Console/Commands/RestoreFromBackup.php b/app/Console/Commands/RestoreFromBackup.phpindex f449420cc5..c7a5fe3843 100644--- a/app/Console/Commands/RestoreFromBackup.php+++ b/app/Console/Commands/RestoreFromBackup.php@@ -2,6 +2,7 @@namespace App\Console\Commands;+use App\Enums\FileStorage;use enshrined\svgSanitize\Sanitizer;use Illuminate\Console\Command;use Illuminate\Support\Facades\Log;@@ -294,43 +295,14 @@ class RestoreFromBackup extends Commandreturn $this->error('Could not access file: '.$filename.' - '.$error_msg);}- $private_dirs = [- 'storage/private_uploads/accessories',- 'storage/private_uploads/assetmodels' => 'storage/private_uploads/models', // this was changed from assetmodels => models Aug 10 2025- 'storage/private_uploads/asset_maintenances' => 'storage/private_uploads/maintenances', // this was changed from asset_maintenances => maintenances Aug 10 2025- 'storage/private_uploads/maintenances', // but let 'maintenances' take precedence- 'storage/private_uploads/models', // and let 'models' take precedence- 'storage/private_uploads/assets', // these are asset _files_, not the pictures.- 'storage/private_uploads/audits',- 'storage/private_uploads/components',- 'storage/private_uploads/consumables',- 'storage/private_uploads/eula-pdfs',- 'storage/private_uploads/imports',- 'storage/private_uploads/locations',- 'storage/private_uploads/licenses',- 'storage/private_uploads/signatures',- 'storage/private_uploads/users',- ];+ // Upload directory enumeration lives in App\Enums\FileStorage+ // as the single source of truth.+ $private_dirs = FileStorage::privateDirs();$private_files = ['storage/oauth-private.key','storage/oauth-public.key',];- $public_dirs = [- 'public/uploads/accessories',- // 'public/uploads/assetmodels' => 'public/uploads/models', //according to git, this was _never_ a thing... (see below)- 'public/uploads/maintenances',- 'public/uploads/assets', // these are asset _pictures_, not asset files- 'public/uploads/avatars',- 'public/uploads/categories',- 'public/uploads/companies',- 'public/uploads/components',- 'public/uploads/consumables',- 'public/uploads/departments',- 'public/uploads/locations',- 'public/uploads/manufacturers',- 'public/uploads/models', // ...it's been this way for 9 years (as of late 2025)- 'public/uploads/suppliers',- ];+ $public_dirs = FileStorage::publicDirs();$public_files = self::PUBLIC_FILES;@@ -512,7 +484,7 @@ class RestoreFromBackup extends Command' -u '.escapeshellarg($connectionConfig['username']).' '.(empty($connectionConfig['unix_socket'])? ' -P '.escapeshellarg($connectionConfig['port'])- : ' -S '.escapeshellarg($connectionConfig['unix_socket'])). ' '.+ : ' -S ' . escapeshellarg($connectionConfig['unix_socket'])) . ' ' .escapeshellarg($connectionConfig['database']), // yanked -p since we pass via ENV[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],$pipes,@@ -584,8 +556,14 @@ class RestoreFromBackup extends Commandreturn $this->error('There may have been a problem with the database import: Error number '.$close_results);}+ // Prune the upload directories before extracting the backup's+ // files on top. A restore replaces the entire install (the DB+ // was wiped before this command ran), so any image or file that+ // the backup does not carry should not survive the restore.+ self::pruneUploadDirectories($public_dirs, $private_dirs);+ self::pruneUploadFiles(self::PUBLIC_FILES);+// and now copy the files over too (right?)- // FIXME - we don't prune the filesystem space yet!!!!if ($this->option('no-progress')) {$bar = null;} else {@@ -631,4 +609,64 @@ class RestoreFromBackup extends Command$this->warn($boring_file.' was skipped.');}}++ /**+ * Clear every file out of each upload directory the restore is+ * about to extract into. `.gitkeep` is preserved so the empty+ * directory still exists post-restore. Nested subdirectories are+ * left alone (Snipe-IT's upload dirs are flat per-resource today,+ * but defensive against future shapes).+ *+ * Accepts the directory lists as parameters rather than reading+ * them from UploadDirectories directly so a test can hand in a+ * fake sandbox dir instead of touching the real repo tree.+ *+ * @param array<int|string, string> $publicDirs+ * @param array<int|string, string> $privateDirs+ */+ protected static function pruneUploadDirectories(array $publicDirs, array $privateDirs): void+ {+ $all = [];+ foreach ([$publicDirs, $privateDirs] as $set) {+ foreach ($set as $src => $dst) {+ $all[] = is_int($src) ? $dst : $dst;+ }+ }++ foreach (array_unique($all) as $dir) {+ if (!is_dir($dir)) {+ continue;+ }+ foreach (scandir($dir) ?: [] as $entry) {+ if ($entry === '.' || $entry === '..' || $entry === '.gitkeep') {+ continue;+ }+ $path = $dir . '/' . $entry;+ if (is_file($path)) {+ @unlink($path);+ }+ }+ }+ }++ /**+ * Delete every file matching the given glob patterns before the+ * restore extracts its own copies on top. Covers the root-level+ * Settings branding files (Setting-*, logo.*, favicon.*, etc.)+ * that live outside the enumerated upload subdirectories, same+ * reasoning as pruneUploadDirectories but for the file-pattern+ * category. #19770.+ *+ * @param list<string> $patterns+ */+ protected static function pruneUploadFiles(array $patterns): void+ {+ foreach ($patterns as $pattern) {+ foreach (glob($pattern) ?: [] as $match) {+ if (is_file($match)) {+ @unlink($match);+ }+ }+ }+ }}diff --git a/tests/Feature/Console/RestoreFromBackupPruningTest.php b/tests/Feature/Console/RestoreFromBackupPruningTest.phpnew file mode 100644index 0000000000..ed05027e91--- /dev/null+++ b/tests/Feature/Console/RestoreFromBackupPruningTest.php@@ -0,0 +1,147 @@+<?php++namespace Tests\Feature\Console;++use App\Console\Commands\RestoreFromBackup;+use ReflectionMethod;+use Tests\TestCase;++/**+ * Covers the per-upload-directory pruning step in the restore flow.+ * Pre-fix, the restore extracted the backup's files on top of the+ * existing install without clearing them, so any image or file that+ * the backup did not carry survived the restore and compounded into+ * every subsequent backup. #19770.+ *+ * The pruning method is factored out of handle() so this test can+ * drive it directly against a sandbox directory tree rather than+ * invoking the full restore (which needs a real zip + a wiped DB).+ */+class RestoreFromBackupPruningTest extends TestCase+{+ private string $sandbox;++ protected function setUp(): void+ {+ parent::setUp();+ $this->sandbox = sys_get_temp_dir().'/snipeit-restore-prune-'.uniqid();+ mkdir($this->sandbox, 0755, true);+ }++ protected function tearDown(): void+ {+ $this->recursiveDelete($this->sandbox);+ parent::tearDown();+ }++ public function test_prunes_files_from_each_directory_except_gitkeep(): void+ {+ $publicDir = $this->sandbox.'/public/uploads/assets';+ $privateDir = $this->sandbox.'/storage/private_uploads/signatures';+ mkdir($publicDir, 0755, true);+ mkdir($privateDir, 0755, true);++ file_put_contents($publicDir.'/asset-1.png', 'bytes');+ file_put_contents($publicDir.'/asset-2.png', 'bytes');+ file_put_contents($publicDir.'/.gitkeep', '');+ file_put_contents($privateDir.'/siglog-abc.png', 'bytes');+ file_put_contents($privateDir.'/.gitkeep', '');++ $prune = new ReflectionMethod(RestoreFromBackup::class, 'pruneUploadDirectories');+ $prune->setAccessible(true);+ $prune->invoke(null, [$publicDir], [$privateDir]);++ $this->assertFileDoesNotExist($publicDir.'/asset-1.png');+ $this->assertFileDoesNotExist($publicDir.'/asset-2.png');+ $this->assertFileDoesNotExist($privateDir.'/siglog-abc.png');++ $this->assertFileExists($publicDir.'/.gitkeep', '.gitkeep must survive pruning so the empty directory stays checked in.');+ $this->assertFileExists($privateDir.'/.gitkeep');+ }++ public function test_handles_missing_directories_silently(): void+ {+ $missing = $this->sandbox.'/does/not/exist';++ $prune = new ReflectionMethod(RestoreFromBackup::class, 'pruneUploadDirectories');+ $prune->setAccessible(true);+ // Should not throw even when the enumerated directory does not exist.+ $prune->invoke(null, [$missing], []);++ $this->assertDirectoryDoesNotExist($missing);+ }++ public function test_prunes_glob_pattern_matches_at_the_uploads_root(): void+ {+ // Root-level Settings branding files (logo.*, favicon.*, Setting-*)+ // live outside the enumerated upload subdirectories. They need+ // their own pruning pass so stale branding does not survive+ // the restore. #19770.+ $uploadsRoot = $this->sandbox.'/public/uploads';+ mkdir($uploadsRoot, 0755, true);++ file_put_contents($uploadsRoot.'/logo.png', 'bytes');+ file_put_contents($uploadsRoot.'/logo.svg', 'bytes');+ file_put_contents($uploadsRoot.'/favicon.ico', 'bytes');+ file_put_contents($uploadsRoot.'/favicon-uploaded.png', 'bytes');+ file_put_contents($uploadsRoot.'/Setting-labels-1-abc.png', 'bytes');+ file_put_contents($uploadsRoot.'/setting-pdfs-1-xyz.png', 'bytes');+ file_put_contents($uploadsRoot.'/unrelated.txt', 'bytes');++ $prune = new ReflectionMethod(RestoreFromBackup::class, 'pruneUploadFiles');+ $prune->setAccessible(true);+ $prune->invoke(null, [+ $uploadsRoot.'/Setting-*',+ $uploadsRoot.'/setting-*',+ $uploadsRoot.'/logo.*',+ $uploadsRoot.'/favicon.*',+ $uploadsRoot.'/favicon-uploaded.*',+ ]);++ $this->assertFileDoesNotExist($uploadsRoot.'/logo.png');+ $this->assertFileDoesNotExist($uploadsRoot.'/logo.svg');+ $this->assertFileDoesNotExist($uploadsRoot.'/favicon.ico');+ $this->assertFileDoesNotExist($uploadsRoot.'/favicon-uploaded.png');+ $this->assertFileDoesNotExist($uploadsRoot.'/Setting-labels-1-abc.png');+ $this->assertFileDoesNotExist($uploadsRoot.'/setting-pdfs-1-xyz.png');++ $this->assertFileExists($uploadsRoot.'/unrelated.txt', 'Non-matching files must survive.');+ }++ public function test_leaves_nested_subdirectories_alone(): void+ {+ // Snipe-IT's upload dirs are flat today, but defensive against+ // future shapes: pruning deletes only direct files, not whole+ // subtrees.+ $dir = $this->sandbox.'/public/uploads/assets';+ $nested = $dir.'/subfolder';+ mkdir($nested, 0755, true);++ file_put_contents($dir.'/top-level.png', 'bytes');+ file_put_contents($nested.'/nested.png', 'bytes');++ $prune = new ReflectionMethod(RestoreFromBackup::class, 'pruneUploadDirectories');+ $prune->setAccessible(true);+ $prune->invoke(null, [$dir], []);++ $this->assertFileDoesNotExist($dir.'/top-level.png');+ $this->assertDirectoryExists($nested, 'Nested subdirectory should survive pruning.');+ $this->assertFileExists($nested.'/nested.png', 'Nested file should survive pruning.');+ }++ private function recursiveDelete(string $path): void+ {+ if (! is_dir($path)) {+ @unlink($path);++ return;+ }+ foreach (scandir($path) ?: [] as $entry) {+ if ($entry === '.' || $entry === '..') {+ continue;+ }+ $this->recursiveDelete($path.'/'.$entry);+ }+ @rmdir($path);+ }+}