fix(core-update): --prune 시 public/storage symlink 삭제로 업로드 파일 404 되는 문제
--prune 은 릴리즈 소스에 없는 public/storage 런타임 symlink 를 orphan 으로 삭제해 업로드 파일이 404 되었다. 심층 방어 2층으로 차단한다. - 층1(예방): FilePermissionHelper 에 preserveLinkPaths 화이트리스트 추가. applyUpdate 가 public 타깃에 ['storage'] 전달 → 매칭 orphan 링크/junction 만 삭제 제외 (정밀 보호) - 층2(복구): StorageLinkHelper::ensurePublicStorageLink 신규 정적 헬퍼. CoreUpdateCommand 종료 시점(정상+핸드오프) 호출로 부재/손상 링크 멱등 재생성 (Windows junction 폴백). beta.5 migration 05 는 이 헬퍼로 위임(상위호환)
This commit is contained in:
1 parent
9251af5c6a
commit
0a6ff23132
11 files changed
+700
-66
No files matched your search
@@ -8,6 +8,7 @@ use App\Exceptions\UpgradeHandoffException;
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use App\Extension\Helpers\CoreBackupHelper;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Helpers\StorageLinkHelper;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
@@ -517,6 +518,12 @@ class CoreUpdateCommand extends Command
|
||||
$this->surfacePermissionWarnings($service, $log);
|
||||
$log('업데이트 경로 소유권 복원 완료');
|
||||
|
||||
// 소유권 복원 완료 후 · 유지보수 해제 전에 `public/storage` symlink 를 방어 복구한다.
|
||||
// `--prune` 이 릴리즈 소스에 없는 symlink 를 orphan 으로 삭제했거나(#43) 손상된
|
||||
// 경우에도, 첫 요청부터 `/storage/...` 가 200 을 반환하도록 링크를 재생성한다.
|
||||
StorageLinkHelper::ensurePublicStorageLink();
|
||||
$log('public/storage symlink 확인/복구 완료');
|
||||
|
||||
$service->cleanupPending($pendingPath);
|
||||
|
||||
if ($backupPath) {
|
||||
@@ -623,6 +630,11 @@ class CoreUpdateCommand extends Command
|
||||
$this->surfacePermissionWarnings($service, $log);
|
||||
$log('핸드오프 cleanup 완료 (버전 toVersion 고정 + 캐시 clear + 소유권 복원)');
|
||||
|
||||
// 핸드오프 시에도 파일은 이미 toVersion 으로 반영돼 `public/storage` symlink 가
|
||||
// 삭제/손상됐을 수 있으므로 유지보수 해제 전에 동일하게 방어 복구한다(#43).
|
||||
StorageLinkHelper::ensurePublicStorageLink();
|
||||
$log('public/storage symlink 확인/복구 완료 (핸드오프)');
|
||||
|
||||
if (! empty($pendingPath)) {
|
||||
$service->cleanupPending($pendingPath);
|
||||
}
|
||||
|
||||
@@ -33,12 +33,17 @@ class FilePermissionHelper
|
||||
* @param bool $removeOrphans 소스에 없는 대상 파일/디렉토리 삭제 여부
|
||||
* @param bool $preserveTopLevelOrphans 최상위 한 레벨의 orphan 보존 여부
|
||||
* @param array<string, bool>|null $applyList 적용 대상 파일 상대경로 화이트리스트
|
||||
* (이 디렉토리 루트 기준, `'sub/file.txt' => true` 형태의 lookup 맵). null 이면
|
||||
* 전체 파일 복사(기존 동작). 지정 시 이 맵에 없는 파일은 복사를 스킵한다 — 코어
|
||||
* 업데이트 증분 모드에서 "코어가 변경하지 않은 파일"을 건드리지 않기 위함. symlink
|
||||
* 는 이 필터의 영향을 받지 않고 항상 재생성된다(링크는 목록 산출 대상이 아님).
|
||||
* (이 디렉토리 루트 기준, `'sub/file.txt' => true` 형태의 lookup 맵). null 이면
|
||||
* 전체 파일 복사(기존 동작). 지정 시 이 맵에 없는 파일은 복사를 스킵한다 — 코어
|
||||
* 업데이트 증분 모드에서 "코어가 변경하지 않은 파일"을 건드리지 않기 위함. symlink
|
||||
* 는 이 필터의 영향을 받지 않고 항상 재생성된다(링크는 목록 산출 대상이 아님).
|
||||
* @param array<int, string> $preserveLinkPaths orphan 정리 시 삭제하지 않고 보존할
|
||||
* symlink/junction 의 상대경로 화이트리스트(이 디렉토리 루트 기준, 예 `['storage']`).
|
||||
* `removeOrphans=true` 라도 이 목록에 매칭되는 orphan 링크는 삭제하지 않는다 — 코어
|
||||
* 업데이트 prune 모드에서 `public/storage` symlink 가 orphan 으로 판정되어 삭제되던
|
||||
* 결함(#43) 차단. 화이트리스트 밖 orphan 링크는 기존대로 삭제된다.
|
||||
*/
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false, bool $preserveTopLevelOrphans = false, ?array $applyList = null): void
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false, bool $preserveTopLevelOrphans = false, ?array $applyList = null, array $preserveLinkPaths = []): void
|
||||
{
|
||||
if (! File::isDirectory($destination)) {
|
||||
// 신규 디렉토리: 부모 디렉토리의 퍼미션/소유권 상속
|
||||
@@ -81,7 +86,10 @@ class FilePermissionHelper
|
||||
|
||||
if ($item->isDir()) {
|
||||
// preserveTopLevelOrphans 는 최상위 한 레벨 한정 — 자식 재귀에는 항상 false 전달.
|
||||
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans, preserveTopLevelOrphans: false, applyList: $applyList);
|
||||
// preserveLinkPaths 는 이 디렉토리 루트 기준 상대경로(예 `public/storage` → `storage`)라
|
||||
// 재귀에 그대로 하향 전달 — removeOrphanItems 가 각 레벨에서 itemRelativePath 전체로
|
||||
// 매칭하므로 중첩 보호 경로도 정확히 판정된다.
|
||||
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans, preserveTopLevelOrphans: false, applyList: $applyList, preserveLinkPaths: $preserveLinkPaths);
|
||||
} else {
|
||||
// 증분 모드(applyList 지정): 화이트리스트에 없는 파일은 스킵 —
|
||||
// 코어가 변경하지 않은 파일의 현재 디스크 상태(사용자 수정 포함)를 보존.
|
||||
@@ -94,7 +102,7 @@ class FilePermissionHelper
|
||||
|
||||
// 소스에 없는 대상 파일/디렉토리 삭제
|
||||
if ($removeOrphans && File::isDirectory($destination)) {
|
||||
static::removeOrphanItems($source, $destination, $excludes, $relativePath, $preserveTopLevelOrphans);
|
||||
static::removeOrphanItems($source, $destination, $excludes, $relativePath, $preserveTopLevelOrphans, $preserveLinkPaths);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,8 +210,11 @@ class FilePermissionHelper
|
||||
* @param array $excludes 제외할 이름 또는 경로 목록
|
||||
* @param string $relativePath 현재 상대 경로
|
||||
* @param bool $preserveTopLevelOrphans 최상위 한 레벨의 orphan 보존 여부
|
||||
* @param array<int, string> $preserveLinkPaths 삭제하지 않고 보존할 symlink/junction
|
||||
* 상대경로 화이트리스트(루트 기준). orphan 이 링크이면서 이 목록에 매칭되면 삭제하지
|
||||
* 않고 보존한다 — `public/storage` symlink 보호(#43). 화이트리스트 밖 orphan 링크는 삭제.
|
||||
*/
|
||||
protected static function removeOrphanItems(string $source, string $destination, array $excludes, string $relativePath, bool $preserveTopLevelOrphans = false): void
|
||||
protected static function removeOrphanItems(string $source, string $destination, array $excludes, string $relativePath, bool $preserveTopLevelOrphans = false, array $preserveLinkPaths = []): void
|
||||
{
|
||||
// 최상위 한 레벨에서 소스에 없는 항목(사용자 추가) 보존 — `_bundled/my-project` 등.
|
||||
// 호출자(copyDirectory)는 최상위 진입 시에만 relativePath='' + 플래그 true 로 들어오며,
|
||||
@@ -227,6 +238,21 @@ class FilePermissionHelper
|
||||
|
||||
// 소스에 존재하지 않는 항목만 삭제
|
||||
if (! File::exists($srcPath) && ! File::isDirectory($srcPath)) {
|
||||
// 보호 화이트리스트 매칭 링크/junction 은 orphan 이어도 보존 — 코어 업데이트
|
||||
// prune 모드에서 `public/storage` symlink 가 릴리즈 소스에 없다는 이유로 삭제되어
|
||||
// 업로드 파일이 404 되던 결함(#43) 차단. 화이트리스트 밖 orphan 링크는 아래에서 삭제.
|
||||
if (
|
||||
in_array($itemRelativePath, $preserveLinkPaths, true)
|
||||
&& (is_link($destItem->getPathname()) || static::isReparsePoint($destItem->getPathname()))
|
||||
) {
|
||||
Log::info('removeOrphanItems: 보호 대상 orphan 링크 보존', [
|
||||
'path' => $destItem->getPathname(),
|
||||
'relative' => $itemRelativePath,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// symlink / Windows junction 은 링크 자체만 제거 — File::deleteDirectory 는 is_dir()
|
||||
// 추적 검사 후 재귀 삭제하므로 link-to-dir 인 경우 target 의 모든 파일을 삭제하는
|
||||
// 사고 발생 가능. 링크 검사가 isDir() 보다 먼저 평가되어야 한다.
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* `public/storage` symlink 멱등 복구 헬퍼.
|
||||
*
|
||||
* 코어 업데이트(특히 `--prune`) 이후 `public/storage` symlink 가 부재/손상 상태로 남는
|
||||
* 결함(#43)을 종료 시점에 방어 복구한다. `is_link` 이면 no-op, 부재/일반 디렉토리이면
|
||||
* `storage/app/public` 을 가리키는 symlink 를 (필요 시 백업 후) 재생성한다.
|
||||
*
|
||||
* V-1 안전: 이 헬퍼는 beta.5 DataMigration `RecoverPublicStorageSymlink` 가 in-process
|
||||
* fallback 으로 호출할 수 있으므로, `Illuminate\Support\Facades\*` 파사드 + 네이티브
|
||||
* 함수 + 로컬 로직만 사용한다 (신규 Service/Manager/Repository 메서드 의존 금지).
|
||||
*
|
||||
* 로거 주입: 두 호출자의 로깅 채널이 다르다 — migration 은 `$context->logger`(채널
|
||||
* `upgrade`), 코어 업데이트 커맨드는 `Log::channel('upgrade')`. 파사드를 직접 쓰면
|
||||
* migration 의 채널 격리가 깨지므로 로거를 주입받고, `null` 이면 `upgrade` 채널로 폴백한다.
|
||||
*/
|
||||
class StorageLinkHelper
|
||||
{
|
||||
/**
|
||||
* `public/storage` 가 정상 symlink 인지 확인하고, 아니면 멱등 재생성합니다.
|
||||
*
|
||||
* 멱등 판정 순서:
|
||||
* 1. `is_link(public/storage)` → 이미 정상 symlink, no-op.
|
||||
* 2. `storage/app/public` 부재 → Laravel storage:link 컨벤션 미사용 환경, skip
|
||||
* (false positive 차단 — 운영자 의도적 구성 존중).
|
||||
* 3. `public/storage` 부재 → `symlink()` 로 신규 생성 (prune 삭제 갭 복구 핵심).
|
||||
* 4. `public/storage` 가 일반 디렉토리 → `.broken.{YmdHis}` rename 백업 후 재생성
|
||||
* (dereferenced 콘텐츠 데이터 손실 없이 보존).
|
||||
*
|
||||
* Windows `SeCreateSymbolicLink` 권한 부족으로 `symlink()` 가 실패하면 target 이
|
||||
* 디렉토리일 때 `mklink /J`(junction) 로 폴백한다. 그래도 실패하면 rename 백업을
|
||||
* 원위치로 복원하고 warning 로그만 남긴다 (graceful degrade — 데이터 손실 없음).
|
||||
*
|
||||
* @param LoggerInterface|null $logger 로그 채널 격리용 주입 로거.
|
||||
* `null` 이면 `Log::channel('upgrade')` 로 폴백.
|
||||
*/
|
||||
public static function ensurePublicStorageLink(?LoggerInterface $logger = null): void
|
||||
{
|
||||
$logger ??= Log::channel('upgrade');
|
||||
|
||||
$publicStorage = public_path('storage');
|
||||
$storageSource = storage_path('app/public');
|
||||
|
||||
// 1) 이미 정상 symlink → no-op (멱등)
|
||||
if (is_link($publicStorage)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 2) Laravel storage:link source 부재 → 표준 미사용 환경, skip (false positive 차단)
|
||||
if (! is_dir($storageSource)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) public/storage 부재 → 신규 생성 (prune 이 삭제한 케이스 — 기존 스텝 미커버)
|
||||
if (! file_exists($publicStorage)) {
|
||||
if (static::createLink($storageSource, $publicStorage)) {
|
||||
$logger->info('[storage-link] public/storage symlink 신규 생성', [
|
||||
'target' => $storageSource,
|
||||
]);
|
||||
} else {
|
||||
$logger->warning('[storage-link] public/storage symlink 생성 실패 — 수동 `php artisan storage:link` 필요', [
|
||||
'target' => $storageSource,
|
||||
]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Windows junction(`mklink /J`)은 `is_link()` 가 false 지만 이미 정상 링크다
|
||||
// (reparse point). rename 백업 대상에서 제외 — no-op 로 존중한다.
|
||||
if (static::isReparsePoint($publicStorage)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 4) public/storage 가 일반 디렉토리(손상) → rename 백업 후 재생성
|
||||
$backup = $publicStorage.'.broken.'.date('YmdHis');
|
||||
if (! @rename($publicStorage, $backup)) {
|
||||
$logger->warning('[storage-link] public/storage rename 실패 — 복구 skip', [
|
||||
'path' => $publicStorage,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (static::createLink($storageSource, $publicStorage)) {
|
||||
$logger->info('[storage-link] public/storage symlink 재생성 완료 — 백업 디렉토리 검증 후 수동 삭제 권장', [
|
||||
'backup' => $backup,
|
||||
'target' => $storageSource,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 재생성 실패 → rename 원복 (데이터 손실 없음)
|
||||
@rename($backup, $publicStorage);
|
||||
$logger->warning('[storage-link] public/storage symlink 재생성 실패 — rename 원복, 수동 `php artisan storage:link` 필요', [
|
||||
'target' => $storageSource,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* `symlink()` 로 링크를 생성하고, 실패 시 Windows junction 폴백을 시도합니다.
|
||||
*
|
||||
* Windows 에서 PHP `symlink()` 는 `SeCreateSymbolicLink` 권한이 필요하지만 junction
|
||||
* (`mklink /J`)은 권한 없이 생성 가능하므로, target 이 디렉토리이면 junction 으로 폴백한다.
|
||||
*
|
||||
* @param string $target 링크가 가리킬 대상 (`storage/app/public`)
|
||||
* @param string $link 생성할 링크 경로 (`public/storage`)
|
||||
* @return bool 링크 생성 성공 여부
|
||||
*/
|
||||
protected static function createLink(string $target, string $link): bool
|
||||
{
|
||||
if (@symlink($target, $link)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// symlink 실패 + target 이 디렉토리 → Windows junction 폴백.
|
||||
if (PHP_OS_FAMILY === 'Windows' && is_dir($target)) {
|
||||
exec(
|
||||
'cmd /c mklink /J '.escapeshellarg($link).' '.escapeshellarg($target).' 2>&1',
|
||||
$out,
|
||||
$code
|
||||
);
|
||||
if ($code === 0 && is_dir($link)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 경로가 Windows JUNCTION 인지 판정합니다 (`is_link()` 미인식 reparse point).
|
||||
*
|
||||
* Windows 에서 junction 과 일반 디렉토리는 둘 다 `is_dir()` 이 true 라 구분되지 않고,
|
||||
* `readlink()` 는 일반 디렉토리에는 **자기 경로**를, junction 에는 **target 경로**를
|
||||
* 반환한다. 따라서 "readlink 가 자기 경로와 다른 target 을 반환" 하는 경우만 junction 으로
|
||||
* 판정한다. 일반 symlink 는 호출부(case 1)가 먼저 처리하므로 여기서 false. 비-Windows 는
|
||||
* 항상 false. 이 판정으로 정상 junction 은 case 4(rename 재생성) 대상에서 제외된다.
|
||||
*
|
||||
* @param string $path 검사할 경로
|
||||
* @return bool junction 여부
|
||||
*/
|
||||
protected static function isReparsePoint(string $path): bool
|
||||
{
|
||||
if (PHP_OS_FAMILY !== 'Windows') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 일반 symlink / 파일 은 junction 아님.
|
||||
if (is_link($path) || is_file($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$target = @readlink($path);
|
||||
if ($target === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// readlink 가 자기 경로와 다른 target 을 반환하면 junction. (일반 디렉토리는 자기 경로
|
||||
// 반환 → 같으므로 false.) 경로 구분자/대소문자 차이를 흡수하기 위해 정규화 후 비교.
|
||||
$normalize = static fn (string $p): string => strtolower(str_replace('/', '\\', rtrim($p, '/\\')));
|
||||
|
||||
return $normalize($target) !== $normalize($path);
|
||||
}
|
||||
}
|
||||
@@ -904,7 +904,7 @@ class CoreUpdateService
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param bool $prune true 면 전체 덮어쓰기 + orphan 삭제(기존 동작), false 면 증분 적용
|
||||
* @param array<int, string>|null $applyList 적용 대상 상대경로 목록(target 접두사 포함).
|
||||
* `CoreBackupHelper::computeApplyList()` 산출물. null 이면 증분 불가로 판단해 전체 덮어쓰기.
|
||||
* `CoreBackupHelper::computeApplyList()` 산출물. null 이면 증분 불가로 판단해 전체 덮어쓰기.
|
||||
*/
|
||||
public function applyUpdate(string $sourcePath, ?\Closure $onProgress = null, bool $prune = false, ?array $applyList = null): void
|
||||
{
|
||||
@@ -953,6 +953,12 @@ class CoreUpdateService
|
||||
// 소스(번들 확장만 포함)에 없다는 이유로 삭제되던 결함 차단.
|
||||
// 번들 확장 디렉토리 *내부* stale 정리는 prune 모드에서만 수행된다.
|
||||
$preserveTopLevelOrphans = str_ends_with($normalizedTarget, '_bundled');
|
||||
|
||||
// `public` 타깃 prune 시 `public/storage` symlink 를 orphan 삭제에서 보호한다 —
|
||||
// 릴리즈 소스에는 런타임 symlink 가 없으므로 orphan 으로 판정되어 삭제되면
|
||||
// 업로드 파일이 404 되는 결함(#43). 다른 타깃은 빈 배열이라 영향 없음.
|
||||
$preserveLinkPaths = $normalizedTarget === 'public' ? ['storage'] : [];
|
||||
|
||||
FilePermissionHelper::copyDirectory(
|
||||
$src,
|
||||
$dest,
|
||||
@@ -961,6 +967,7 @@ class CoreUpdateService
|
||||
removeOrphans: $prune,
|
||||
preserveTopLevelOrphans: $preserveTopLevelOrphans,
|
||||
applyList: $targetApplyList,
|
||||
preserveLinkPaths: $preserveLinkPaths,
|
||||
);
|
||||
} else {
|
||||
// 단일 파일 target — 증분 모드에서는 적용 목록에 있을 때만 복사.
|
||||
|
||||
Reference in new issue
Block a user