A free open source IT asset/license management system
Fixed #19670 - better handle S3 files consistently
snipeb2d8707e5116
diff --git a/app/Helpers/StorageHelper.php b/app/Helpers/StorageHelper.phpindex d9305c2af9..a116791e4b 100644--- a/app/Helpers/StorageHelper.php+++ b/app/Helpers/StorageHelper.php@@ -43,14 +43,14 @@ class StorageHelperreturn response()->download(Storage::disk($disk)->path($filename), null, $safeHeaders);case 's3':- Storage::disk($disk)->temporaryUrl(+ return redirect()->to(Storage::disk($disk)->temporaryUrl($filename,now()->addMinutes(5),['ResponseContentType' => 'application/octet-stream',- 'ResponseContentDisposition' => 'attachment; filename=download-file',+ 'ResponseContentDisposition' => 'attachment; filename="'.basename($filename).'"',]- );+ ));default:return Storage::disk($disk)->download($filename, null, $safeHeaders);@@ -209,7 +209,7 @@ class StorageHelper*/public static function readablePath(string $filename, string $disk = 'public'): ?string{- if (!Storage::disk($disk)->exists($filename)) {+ if (! Storage::disk($disk)->exists($filename)) {return null;}@@ -229,8 +229,8 @@ class StorageHelperreturn null;}if ($extension !== '') {- $tmpWithExt = $tmp . '.' . $extension;- if (!@rename($tmp, $tmpWithExt)) {+ $tmpWithExt = $tmp.'.'.$extension;+ if (! @rename($tmp, $tmpWithExt)) {@unlink($tmp);return null;@@ -258,7 +258,7 @@ class StorageHelper// Auto-clean at request end so the caller doesn't own the// lifecycle. Register once per file so many calls in the same// request each get their own cleanup.- register_shutdown_function(fn() => @unlink($tmp));+ register_shutdown_function(fn () => @unlink($tmp));return $tmp;}diff --git a/app/Http/Controllers/Api/ImportController.php b/app/Http/Controllers/Api/ImportController.phpindex 06d447fbb9..2417e36f2e 100644--- a/app/Http/Controllers/Api/ImportController.php+++ b/app/Http/Controllers/Api/ImportController.php@@ -19,7 +19,6 @@ use Illuminate\Support\Facades\Storage;use Illuminate\Support\Str;use League\Csv\Reader;use Onnov\DetectEncoding\EncodingDetector;-use Symfony\Component\HttpFoundation\File\Exception\FileException;class ImportController extends Controller{@@ -52,7 +51,9 @@ class ImportController extends Controller$this->authorize('import');if (! config('app.lock_passwords')) {$files = Request::file('files');- $path = config('app.private_uploads').'/imports';+ // Path inside the private disk. Under PRIVATE_FILESYSTEM_DISK=local this resolves to+ // storage/private_uploads/imports, and under s3_private it lands at <bucket>/private_uploads/imports+ $diskPath = 'private_uploads/imports';$results = [];$import = new Import;$detector = new EncodingDetector;@@ -232,26 +233,17 @@ class ImportController extends Controller$date = date('Y-m-d-his');$fixed_filename = Str::of($file->getClientOriginalName())->basename('.csv').'.csv';+ $file_name = $date . '-' . $fixed_filename;- try {- $file->move($path, $date.'-'.$fixed_filename);- } catch (FileException $exception) {+ // Storage::putFileAs routes through the Filesystem abstraction so it works+ // uniformly against local and s3_private drivers.+ if (!Storage::putFileAs($diskPath, $file, $file_name)) {$results['error'] = trans('admin/hardware/message.upload.error');- if (config('app.debug')) {- $results['error'] .= ' '.$exception->getMessage();- }return response()->json(Helper::formatStandardApiResponse('error', null, $results['error']), 500);}- $file_name = date('Y-m-d-his').'-'.$fixed_filename;$import->file_path = $file_name;- $import->filesize = null;-- if (! file_exists($path.'/'.$file_name)) {- return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.file_not_found')), 500);- }-- $import->filesize = filesize($path.'/'.$file_name);+ $import->filesize = $file->getSize();$import->created_by = auth()->id();$import->save();$results[] = $import;@@ -467,8 +459,12 @@ class ImportController extends Controller}try {- // Try to delete the file- Storage::delete('imports/'.$import->file_path);+ // Try to delete the file. Path shape matches the write+ // path in store(): 'private_uploads/imports/<name>' on+ // the default (private) disk. The pre-fix path 'imports/'+ // missed the 'private_uploads/' prefix and silently+ // no-op'd on both drivers.+ Storage::delete('private_uploads/imports/' . $import->file_path);$import->delete();return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.import.file_delete_success')));diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.phpindex 25ffe4258a..622186eb9a 100644--- a/app/Http/Controllers/SettingsController.php+++ b/app/Http/Controllers/SettingsController.php@@ -35,6 +35,7 @@ use Illuminate\Support\Str;use Illuminate\Validation\Rule;use League\Csv\EscapeFormula;use Symfony\Component\HttpFoundation\BinaryFileResponse;+use Symfony\Component\HttpFoundation\StreamedResponse;use ZipArchive;/**@@ -1569,33 +1570,28 @@ class SettingsController extends Controllerpublic function getBackups(): View{$settings = Setting::getSettings();- $path = 'app/backups';- $backup_files = Storage::files($path);+ $backupName = config('backup.backup.name', 'backups');+ $disk = Storage::disk('backup');$files_raw = [];- if (count($backup_files) > 0) {- for ($f = 0; $f < count($backup_files); $f++) {-- // Skip dotfiles like .gitignore and .DS_STORE- if ((substr(basename($backup_files[$f]), 0, 1) != '.')) {- // $lastmodified = Carbon::parse(Storage::lastModified($backup_files[$f]))->toDatetimeString();- $file_timestamp = Storage::lastModified($backup_files[$f]);-- $files_raw[] = [- 'filename' => basename($backup_files[$f]),- 'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])),- 'modified_value' => $file_timestamp,- 'modified_display' => date($settings->date_display_format.' '.$settings->time_display_format, $file_timestamp),-- ];- }+ foreach ($disk->files($backupName) as $file) {+ // Skip dotfiles like .gitignore and .DS_STORE+ if (substr(basename($file), 0, 1) === '.') {+ continue;}+ $file_timestamp = $disk->lastModified($file);+ $files_raw[] = [+ 'filename' => basename($file),+ 'filesize' => Setting::fileSizeConvert($disk->size($file)),+ 'modified_value' => $file_timestamp,+ 'modified_display' => date($settings->date_display_format . ' ' . $settings->time_display_format, $file_timestamp),+ ];}// Reverse the array so it lists oldest first$files = array_reverse($files_raw);- return view('settings/backups', compact('path', 'files'));+ return view('settings/backups', compact('files'));}/**@@ -1637,9 +1633,15 @@ class SettingsController extends Controller** @since [v1.8]*/- public function downloadFile($filename = null): RedirectResponse|BinaryFileResponse+ public function downloadFile($filename = null): RedirectResponse|BinaryFileResponse|StreamedResponse{- $path = 'app/backups';+ // Path inside the backup disk mirrors getBackups(): spatie writes+ // to <disk root>/<backup.backup.name>/*.zip, and BinFile.name+ // defaults to 'backups'. StorageHelper::downloader('backup')+ // dispatches to response()->download on the local driver and to+ // Storage::disk('backup')->download on the s3 driver, so this+ // works for both destinations without a driver switch here.+ $backupName = config('backup.backup.name', 'backups');$filename = basename((string) $filename);if ($this->hasInvalidBackupFilename($filename)) {@@ -1647,10 +1649,11 @@ class SettingsController extends Controller}if (! config('app.lock_passwords')) {- if (Storage::exists($path.'/'.$filename)) {+ $path = $backupName . '/' . $filename;+ if (Storage::disk('backup')->exists($path)) {Log::warning('User '.auth()->user()->username.' is attempting to download backup file: '.$filename);- return StorageHelper::downloader($path.'/'.$filename);+ return StorageHelper::downloader($path, 'backup');} else {// Redirect to the backup pagereturn redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));@@ -1679,13 +1682,15 @@ class SettingsController extends Controllerif (config('app.allow_backup_delete') == 'true') {if (! config('app.lock_passwords')) {- $path = 'app/backups';+ // Same disk + path so S3-destination backup is deletable from the UI.+ $disk = Storage::disk('backup');+ $path = config('backup.backup.name', 'backups') . '/' . $filename;- if (Storage::exists($path.'/'.$filename)) {+ if ($disk->exists($path)) {try {Log::warning('User '.auth()->user()->username.' is attempting to delete backup file: '.$filename);- Storage::delete($path.'/'.$filename);+ $disk->delete($path);return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted'));} catch (\Exception $e) {@@ -1760,135 +1765,189 @@ class SettingsController extends Controllerreturn redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));}- $path = 'app/backups';+ // Path inside the backup disk mirrors getBackups / downloadFile /+ // deleteFile. spatie writes to <disk root>/<backup.backup.name>/+ // and the name defaults to 'backups'.+ $backupDisk = Storage::disk('backup');+ $backupName = config('backup.backup.name', 'backups');+ $diskPath = $backupName . '/' . $filename;- if (! Storage::exists($path.'/'.$filename)) {+ if (!$backupDisk->exists($diskPath)) {return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));}- $absolutePath = storage_path($path).'/'.$filename;-- // Verify the archive is actually a zip and can be opened, BEFORE we- // do anything destructive. Prior behavior wiped the database first- // and only then tried to open the archive. An invalid or corrupted- // upload therefore destroyed the existing database and left the- // install with an empty migrated schema, while the flow still- // reported success because snipeit:restore returns exit 0 on- // internal errors (see RestoreFromBackup::handle).- //- // Refuse to proceed if the PHP zip extension is not loaded. The- // downstream snipeit:restore command needs ZipArchive too, so- // running it without ext-zip would fail after the wipe.- if (! class_exists(ZipArchive::class)) {- Log::error('Restore aborted: PHP zip extension is not loaded, cannot validate archive before wiping database.');-- return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.zip_extension_missing'));- }-- $zip = new ZipArchive;- $openResult = $zip->open($absolutePath);- if ($openResult !== true) {- Log::warning('Restore aborted: archive at '.$absolutePath.' failed zip open with code '.$openResult);+ // ZipArchive and snipeit:restore both need a local filesystem path.+ // On the local driver, resolve directly to the disk's on-disk path+ // and let the restore CLI read it in place. On any remote driver+ // (s3), stream the archive down to a temp file so downstream code+ // that expects a real path still works. The finally block below+ // unlinks the temp file on every exit path so a bail-out doesn't+ // leave hundreds of megabytes stranded in storage/app/restore-temp.+ $localTempPath = null;+ try {+ if (config('filesystems.disks.backup.driver') === 'local') {+ $absolutePath = $backupDisk->path($diskPath);+ } else {+ $tempDir = storage_path('app/restore-temp');+ if (!is_dir($tempDir) && !mkdir($tempDir, 0755, true) && !is_dir($tempDir)) {+ Log::error('Restore aborted: could not create temp directory ' . $tempDir);- return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));- }- $zip->close();+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));+ }+ $localTempPath = $tempDir . '/' . $filename;+ // readStream returns null on failure, fopen returns false.+ $srcStream = $backupDisk->readStream($diskPath);+ $dstStream = fopen($localTempPath, 'w');+ if ($srcStream === null || $dstStream === false) {+ if (is_resource($srcStream)) {+ fclose($srcStream);+ }+ if (is_resource($dstStream)) {+ fclose($dstStream);+ }+ Log::error('Restore aborted: failed to open streams for temp copy of ' . $diskPath);- // grab the user's info so we can make sure they exist in the system- $user = User::find(auth()->id());+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));+ }+ stream_copy_to_stream($srcStream, $dstStream);+ fclose($srcStream);+ fclose($dstStream);+ $absolutePath = $localTempPath;+ }- // Take a fresh pre-restore backup so we can point the operator at- // it if the restore fails after we wipe. This is the mitigation- // the pre-existing- $requestedBackupFilename = 'pre-restore-'.date('Y-m-d-H-i-s').'.zip';- // spatie prepends filename_prefix to the filename provided so this is the actual name on disk:- $preRestoreBackupFilename = config('backup.backup.destination.filename_prefix').$requestedBackupFilename;- $preBackupPath = storage_path($path).'/'.$preRestoreBackupFilename;+ // Verify the archive is actually a zip and can be opened, BEFORE we+ // do anything destructive. Prior behavior wiped the database first+ // and only then tried to open the archive. An invalid or corrupted+ // upload therefore destroyed the existing database and left the+ // install with an empty migrated schema, while the flow still+ // reported success because snipeit:restore returns exit 0 on+ // internal errors (see RestoreFromBackup::handle).+ //+ // Refuse to proceed if the PHP zip extension is not loaded. The+ // downstream snipeit:restore command needs ZipArchive too, so+ // running it without ext-zip would fail after the wipe.+ if (!class_exists(ZipArchive::class)) {+ Log::error('Restore aborted: PHP zip extension is not loaded, cannot validate archive before wiping database.');++ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.zip_extension_missing'));+ }- Log::debug('Running pre-restore backup: '.$preRestoreBackupFilename);- $preBackupExit = Artisan::call('snipeit:backup', [- '--filename' => $requestedBackupFilename,- '--force' => true,- ]);+ $zip = new ZipArchive;+ $openResult = $zip->open($absolutePath);+ if ($openResult !== true) {+ Log::warning('Restore aborted: archive at ' . $absolutePath . ' failed zip open with code ' . $openResult);- if ($preBackupExit !== 0 || ! (Storage::exists($path.'/'.$preRestoreBackupFilename))) {- Log::warning('Pre-restore backup failed (exit '.$preBackupExit.'); aborting restore to protect existing data.');+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));+ }+ $zip->close();++ // grab the user's info so we can make sure they exist in the system+ $user = User::find(auth()->id());++ // Take a fresh pre-restore backup so we can point the operator at+ // it if the restore fails after we wipe. This is the mitigation+ // the pre-existing+ $requestedBackupFilename = 'pre-restore-' . date('Y-m-d-H-i-s') . '.zip';+ // spatie prepends filename_prefix to the filename provided so this is the actual name on disk:+ $preRestoreBackupFilename = config('backup.backup.destination.filename_prefix') . $requestedBackupFilename;+ $preRestoreDiskPath = $backupName . '/' . $preRestoreBackupFilename;+ $preBackupHint = config('filesystems.disks.backup.driver') === 'local'+ ? $backupDisk->path($preRestoreDiskPath)+ : 'backup disk (' . $preRestoreDiskPath . ')';++ Log::debug('Running pre-restore backup: ' . $preRestoreBackupFilename);+ $preBackupExit = Artisan::call('snipeit:backup', [+ '--filename' => $requestedBackupFilename,+ '--force' => true,+ ]);- return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.pre_backup_failed'));- }+ if ($preBackupExit !== 0 || !$backupDisk->exists($preRestoreDiskPath)) {+ Log::warning('Pre-restore backup failed (exit ' . $preBackupExit . '); aborting restore to protect existing data.');- Log::warning('User '.auth()->user()->username.' is attempting to restore from: '.$absolutePath.' (pre-restore backup at '.$preBackupPath.')');+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.pre_backup_failed'));+ }- $restore_params = [- '--force' => true,- '--no-progress' => true,- 'filename' => $absolutePath,- ];+ Log::warning('User ' . auth()->user()->username . ' is attempting to restore from: ' . $absolutePath . ' (pre-restore backup at ' . $preBackupHint . ')');- if ($request->input('clean')) {- Log::debug("Attempting 'clean' - first, guessing prefix...");- Artisan::call('snipeit:restore', [- '--sanitize-guess-prefix' => true,+ $restore_params = [+ '--force' => true,+ '--no-progress' => true,'filename' => $absolutePath,- ]);- $guess_prefix_output = Artisan::output();- Log::debug("Sanitize output is: $guess_prefix_output");- [$prefix, $_output] = explode("\n", $guess_prefix_output);- Log::debug("prefix is: '$prefix'");- $restore_params['--sanitize-with-prefix'] = $prefix;- }+ ];- Artisan::call('db:wipe', ['--force' => true]);+ if ($request->input('clean')) {+ Log::debug("Attempting 'clean' - first, guessing prefix...");+ Artisan::call('snipeit:restore', [+ '--sanitize-guess-prefix' => true,+ 'filename' => $absolutePath,+ ]);+ $guess_prefix_output = Artisan::output();+ Log::debug("Sanitize output is: $guess_prefix_output");+ [$prefix, $_output] = explode("\n", $guess_prefix_output);+ Log::debug("prefix is: '$prefix'");+ $restore_params['--sanitize-with-prefix'] = $prefix;+ }- // run the restore command- $restoreExit = Artisan::call('snipeit:restore', $restore_params);- $restoreOutput = Artisan::output();- Log::debug('snipeit:restore output: '.$restoreOutput);+ Artisan::call('db:wipe', ['--force' => true]);- // snipeit:restore returns 0 even on some internal errors, so we also- // scan its output for its own "Could not access file" / "DB_CONNECTION- // must be MySQL" style error strings.- $restoreLooksFailed = $restoreExit !== 0 || str_contains(strtolower($restoreOutput), 'could not access file') || str_contains(strtolower($restoreOutput), 'db_connection must be mysql');+ // run the restore command+ $restoreExit = Artisan::call('snipeit:restore', $restore_params);+ $restoreOutput = Artisan::output();+ Log::debug('snipeit:restore output: ' . $restoreOutput);- if ($restoreLooksFailed) {- Log::error('Restore failed after db:wipe. Pre-restore backup available at '.$preBackupPath);+ // snipeit:restore returns 0 even on some internal errors, so we also+ // scan its output for its own "Could not access file" / "DB_CONNECTION+ // must be MySQL" style error strings.+ $restoreLooksFailed = $restoreExit !== 0 || str_contains(strtolower($restoreOutput), 'could not access file') || str_contains(strtolower($restoreOutput), 'db_connection must be mysql');- return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [- 'backup' => $preRestoreBackupFilename,- ]));- }+ if ($restoreLooksFailed) {+ Log::error('Restore failed after db:wipe. Pre-restore backup available at ' . $preBackupHint);- /* Run migrations */- Log::debug('Migrating database...');- $migrateExit = Artisan::call('migrate', ['--force' => true]);- $migrate_output = Artisan::output();- Log::debug($migrate_output);+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [+ 'backup' => $preRestoreBackupFilename,+ ]));+ }- if ($migrateExit !== 0) {- Log::error('Migrate failed after restore. Pre-restore backup available at '.$preBackupPath);+ /* Run migrations */+ Log::debug('Migrating database...');+ $migrateExit = Artisan::call('migrate', ['--force' => true]);+ $migrate_output = Artisan::output();+ Log::debug($migrate_output);- return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [- 'backup' => $preRestoreBackupFilename,- ]));- }+ if ($migrateExit !== 0) {+ Log::error('Migrate failed after restore. Pre-restore backup available at ' . $preBackupHint);- $find_user = DB::table('users')->where('username', $user->username)->exists();+ return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [+ 'backup' => $preRestoreBackupFilename,+ ]));+ }- if (! $find_user) {- Log::warning('Attempting to restore user: '.$user->username);- $new_user = $user->replicate();- $new_user->push();- } else {- Log::debug('User: '.$user->username.' already exists.');- }+ $find_user = DB::table('users')->where('username', $user->username)->exists();- Log::debug('Logging all users out..');- Artisan::call('snipeit:global-logout', ['--force' => true]);+ if (!$find_user) {+ Log::warning('Attempting to restore user: ' . $user->username);+ $new_user = $user->replicate();+ $new_user->push();+ } else {+ Log::debug('User: ' . $user->username . ' already exists.');+ }++ Log::debug('Logging all users out..');+ Artisan::call('snipeit:global-logout', ['--force' => true]);- DB::table('users')->update(['remember_token' => null]);- Auth::logout();+ DB::table('users')->update(['remember_token' => null]);+ Auth::logout();- return redirect()->route('login')->with('success', trans('admin/settings/message.restore.success'));+ return redirect()->route('login')->with('success', trans('admin/settings/message.restore.success'));+ } finally {+ // Temp copy only exists when we downloaded from a remote+ // driver. On the local driver $localTempPath stays null and+ // we skip the unlink entirely, so we don't accidentally+ // reach into the backup disk's own storage.+ if ($localTempPath !== null && file_exists($localTempPath)) {+ @unlink($localTempPath);+ }+ }}/**diff --git a/app/Http/Controllers/UploadedFilesController.php b/app/Http/Controllers/UploadedFilesController.phpindex 46a446fc47..dc549588b3 100644--- a/app/Http/Controllers/UploadedFilesController.php+++ b/app/Http/Controllers/UploadedFilesController.php@@ -188,14 +188,21 @@ class UploadedFilesController extends Controllerreturn redirect()->back()->with('error', trans('general.file_upload_status.file_not_found'));}- if (config('filesystems.default') == 's3_private') {- return redirect()->away(Storage::disk('s3_private')->temporaryUrl('private_uploads/imports/'.$import->file_path, now()->addMinutes(5)));+ $storedPath = 'private_uploads/imports/'.$import->file_path;+ if (! Storage::exists($storedPath)) {+ return redirect()->back()->with('error', trans('general.file_upload_status.file_not_found'));}- if (Storage::exists('private_uploads/imports/'.$import->file_path)) {- return response()->download(config('app.private_uploads').'/imports/'.$import->file_path);+ $defaultDisk = config('filesystems.default');+ if (config("filesystems.disks.$defaultDisk.driver") === 's3') {+ return redirect()->away(Storage::temporaryUrl($storedPath, now()->addMinutes(5), [+ 'ResponseContentType' => 'application/octet-stream',+ 'ResponseContentDisposition' => 'attachment; filename="'.basename($import->file_path).'"',+ ]));}+ return response()->download(Storage::path($storedPath));+}return redirect()->back()->with('error', trans('general.file_upload_status.file_not_found'));diff --git a/app/Http/Requests/ImageUploadRequest.php b/app/Http/Requests/ImageUploadRequest.phpindex 699f3f98cd..d4f9dc816e 100644--- a/app/Http/Requests/ImageUploadRequest.php+++ b/app/Http/Requests/ImageUploadRequest.php@@ -97,10 +97,10 @@ class ImageUploadRequest extends Request$path = trim((string) $path, '/');$prefix = $path === '' ? '' : $path.'/';- if ($path !== '' && ! Storage::disk('public')->exists($path)) {- Storage::disk('public')->makeDirectory($path);- }-+ // No pre-emptive makeDirectory. S3 has no directories to+ // create (flat namespace), and LocalFilesystemAdapter::write()+ // calls ensureDirectoryExists() before writing, so the parent+ // is auto-created on the local disk anyway.if ($this->offsetGet($form_fieldname) instanceof UploadedFile) {$image = $this->offsetGet($form_fieldname);} elseif ($this->hasFile($form_fieldname)) {diff --git a/config/filesystems.php b/config/filesystems.phpindex 52e45dc022..5c2fa3f1bb 100644--- a/config/filesystems.php+++ b/config/filesystems.php@@ -66,7 +66,8 @@ $config = ['endpoint' => env('PUBLIC_AWS_ENDPOINT'),'use_path_style_endpoint' => env('PUBLIC_AWS_PATH_STYLE'),'root' => env('PUBLIC_AWS_BUCKET_ROOT'),- 'visibility' => 'public',+ // No 'visibility' key: Admins who want public reads should grant them+ // via a bucket policy and set PUBLIC_AWS_URL to the public endpoint. See #19670.],'s3_private' => [@@ -83,7 +84,12 @@ $config = ['endpoint' => env('PRIVATE_AWS_ENDPOINT'),'use_path_style_endpoint' => env('PRIVATE_AWS_PATH_STYLE'),'root' => env('PRIVATE_AWS_BUCKET_ROOT'),- 'visibility' => 'private',+ // No 'visibility' key: sending an ACL header (even+ // ACL: private) is rejected on buckets with Object+ // Ownership = Bucket owner enforced, which has been the+ // default for buckets created since April 2023. Buckets+ // configured that way are already private by default via+ // the bucket policy, so this ACL was redundant. See #19670.],'rackspace' => [@@ -102,8 +108,24 @@ $config = ['secret' => env('PRIVATE_AWS_SECRET_ACCESS_KEY'),'region' => env('PRIVATE_AWS_DEFAULT_REGION'),'bucket' => env('PRIVATE_AWS_BUCKET'),- 'root' => env('BACKUP_FILESYSTEM_ROOT', storage_path('app')),- 'visibility' => 'private',+ // Root defaults differ by driver so the same disk config+ // does the right thing on both. On local, backups live+ // under storage_path("app")/backups (matches the pre-S3+ // shape and the spatie backup name). On s3, the root+ // becomes an S3 key prefix, and defaulting it to a local+ // filesystem path (storage_path("app") = "/Users/..." or+ // "/var/www/...") puts every backup behind a leading-slash+ // prefix that Flysystem's S3 adapter can't list back+ // (upload preserves the leading /, listContents strips+ // it, so the write/read round-trip breaks). Empty string+ // = bucket root, which is what admins actually want.+ // Override in either direction via BACKUP_FILESYSTEM_ROOT.+ 'root' => env('BACKUP_FILESYSTEM_ROOT', env('BACKUP_FILESYSTEM_DRIVER', 'local') === 's3' ? '' : storage_path('app')),+ // No 'visibility' key: same reasoning as s3_private above.+ // On the default local driver this key does nothing anyway.+ // On the s3 driver it would send ACL: private, which buckets+ // with Object Ownership = Bucket owner enforced reject with+ // AccessControlListNotSupported. See #19670.],],@@ -163,7 +185,7 @@ $config['allowed_upload_mimetypes_array'] = ['application/json','application/msword','application/pdf',- // text/csv is the RFC 4180 mime; some browsers report CSVs as+ // text/csv is the RFC 4180 mime. Some browsers report CSVs as// application/csv or application/vnd.ms-excel instead depending on// OS registration. Accepting all three covers real-world uploads// without users hitting mysterious "wrong type" rejections.