fix(core,extensions): 확장 쓰기 경로 공통화 · HTMLPurifier 정의 캐시 storage 이전

https://github.com/gnuboard/g7/issues/125 — 상품 상세설명을 HTML 로 저장할 때
HTMLPurifier 가 모듈 vendor 폴더 안에 정의 캐시를 만들려다 실패해 저장이 매번 500 으로
끝나던 문제를 고친다. vendor 를 읽기 전용으로 두는 표준 배포에서 그 쓰기는 예외가 아니라
PHP 경고로 나오고 Laravel 이 이를 ErrorException 으로 승격시킨다. 캐시는 설정 해시당 1회만
기록되므로 캐시가 영영 생기지 않아 재시도해도 같은 결과였다.

캐시 경로를 storage 아래로 옮기고, 그 경로마저 확보하지 못하면 캐시만 끄고 정화는 그대로
수행한다 — 캐시는 성능 장치이고 정화는 보안 장치라, 전자의 실패가 후자를 건너뛰게 만들면
안 된다. 저장은 성공하므로 운영자에게 도달하는 흔적이 로그 하나뿐이라 error 수준으로 남긴다
(출하 기본 로그 수준이 error 라 warning 은 기본 설치 상태에서 파일에 남지 않는다).

그 과정에서 갈라져 있던 두 축을 코어 한 곳으로 모은다.

- 쓰기 디렉토리 확보: 억제 생성·chmod·setgid·소유권 상속·쓰기 판정 절차가 정적 게시와
 정의 캐시 두 곳에 서로 다른 하드닝으로 복제돼 있었다(억제 mkdir·setgid·clearstatcache 가
 사본마다 한쪽씩 빠져 있었다). FilePermissionHelper 의 ensureWritableDirectory 와
 hardenDirectory 로 통합하고, 실패 사유는 out 파라미터로 올려 정책(조용한 성능 저하 대
 시끄러운 실패)은 호출부가 정하게 둔다.

- 확장 저장 경로: storage_path('app/modules/…') 손조립이 30곳에 흩어져 있어 테스트 격리
 분기를 넣으려면 사본마다 복제해야 했고, 한 곳만 빠뜨려도 그 확장의 테스트가 운영 설정
 파일을 덮어쓴다. 디스크 root 를 단일 출처로 읽는 ExtensionStoragePath 로 전환하고 테스트
 분기는 config/filesystems.php 한 줄에서 끝낸다.

함께 고친 것

- 테스트가 운영 라우트 캐시로 부팅해 확장 allowlist 가 라우트 축에서 통째로 무력화되던
 문제. 삭제가 아니라 경로를 돌린다 — 라우트 캐시는 확장 작업 전까지 재생성되지 않아,
 삭제하면 운영 사이트가 그때까지 라우트 파일 스캔 경로로 떨어진다.
- PHPUnit 프로세스가 확장 vendor 의 제3자 composer 패키지를 오토로드하지 않아 그 패키지를
 쓰는 코드 경로가 통째로 테스트 불가였던 문제. 확장 자신의 오토로더를 그대로 쓰면 활성
 디렉토리가 _bundled 를 이기고 base path 유추까지 깨지므로, 생성된 맵에서 제3자 항목만
 골라 별도 로더로 등록한다.
- 게시 폴더가 setgid 를 갖지 않아, 명령줄과 웹이 번갈아 만든 하위 폴더를 다른 쪽이 쓰지
 못하던 문제.
- 관리자 템플릿이 HTML 정화 라이브러리를 직접 지정하지 않아 전이 의존으로 딸려온 구버전이
 쓰이던 문제.

동반 산출물

- 규정 표(·AGENTS.md) 6행 + storage-driver/service-repository/testing-guide 문서
- audit 룰 2종 + coverage 6항목. 저장소가 이미 전량 전환돼 전수 실행이 공허 통과하므로
 판정식은 픽스처 36건이 잠근다
- INSTALL.md 에 설치 후 파일 권한 절 추가 (vendor 쓰기 권한 불요를 명시)
This commit is contained in:
HeuJung committed 2026-08-28 15:22:22 +09:00
1 parent fc27a6edf6
commit 85e266d361
88 files changed
+1913 -332

No files matched your search

@@ -387,6 +387,122 @@ class FilePermissionHelper
static::applyOwnership($path, fileowner($parentDir), filegroup($parentDir));
}
/**
* 이미 존재하는 디렉토리의 퍼미션·소유권을 umask 와 무관하게 정합화합니다.
*
* `File::ensureDirectoryExists($dir, 0775)` 등 생성 API 의 mode 인자는 **umask 로 깎인다** —
* umask 022 환경에서는 0775 요청이 0755 로 만들어져 그룹 공유(웹 계정)가 쓸 수 없다.
* 명시 `chmod` 로 umask 를 무력화하고, POSIX 에서는 setgid 를 세워 그 아래에 만들어지는
* 하위 디렉토리가 그룹을 상속하게 한다. setgid 가 없으면 CLI(스케줄러/큐)가 먼저 만든
* 하위 디렉토리를 웹 프로세스가 쓰지 못한다. Windows 에는 setgid 개념이 없어 제외한다.
*
* 마지막으로 부모 소유권을 상속시켜 sudo/CLI 계정 고정을 막는다.
*
* @param string $path 대상 디렉토리 절대 경로
* @param int $mode 적용할 퍼미션 (예: 0775)
*/
public static function hardenDirectory(string $path, int $mode = 0775): void
{
@chmod($path, $mode);
if (PHP_OS_FAMILY !== 'Windows') {
@chmod($path, $mode | 02000);
}
static::inheritOwnershipFromParent($path);
}
/**
* 쓰기 가능한 디렉토리를 확보합니다 — 없으면 만들고, 권한을 정합화한 뒤 실제 쓰기 가능 여부를 판정합니다.
*
* 제3자 라이브러리에 넘길 캐시·임시 디렉토리처럼 "확보하지 못하면 그 기능만 끄면 되는"
* 자리를 위한 프리미티브다. **예외도 PHP 경고도 내지 않는다** — `File::ensureDirectoryExists()`
* 는 `mkdir()` 을 억제 없이 호출하므로 생성 실패가 `E_WARNING` 으로 나오고 Laravel
* `HandleExceptions` 가 이를 `ErrorException` 으로 승격시켜 요청이 500 이 된다. 쓰기 경로를
* 지정하는 목적 자체가 그 500 을 막는 것이므로, 확보 실패가 다시 500 을 내면 무의미하다.
*
* 실패 정책은 호출부가 정한다 — 조용히 성능 저하로 이어갈지(정의 캐시), 시끄럽게 실패로
* 처리할지(정적 게시)가 자리마다 다르기 때문이다. 사유는 `$failure` out 파라미터로 올린다.
*
* @param string $path 확보할 디렉토리 절대 경로
* @param int $mode 생성 시 적용할 퍼미션
* @param array{reason: string, path: string}|null $failure out — 실패 사유와 그 대상 경로.
* reason 은 `occupied_by_file`(경로가 파일로 점유) /
* `ancestor_not_writable`(실재하는 최근접 상위가 쓰기 불가) /
* `create_failed`(생성 실패) / `not_writable`(존재하나 쓰기 불가)
* @return bool 확보 성공 여부
*/
public static function ensureWritableDirectory(string $path, int $mode = 0775, ?array &$failure = null): bool
{
$failure = null;
if (! is_dir($path)) {
// 같은 이름의 파일이 자리를 차지하면 mkdir 이 경고를 낸다 — 먼저 걸러낸다.
if (file_exists($path)) {
$failure = ['reason' => 'occupied_by_file', 'path' => $path];
return false;
}
// 상위가 쓰기 불가라면 생성 자체가 불가능하다. 여기서 끊어야 호출부가 "무엇을
// 고쳐야 하는지"(대상 디렉토리가 아니라 그 상위)를 운영자에게 지목할 수 있다.
$ancestor = static::nearestExistingAncestor($path);
if ($ancestor === null || ! is_writable($ancestor)) {
$failure = ['reason' => 'ancestor_not_writable', 'path' => $ancestor ?? dirname($path)];
return false;
}
// force 인자로 경고를 억제한다. 실패는 아래 판정이 흡수한다.
File::makeDirectory($path, $mode, true, true);
if (is_dir($path)) {
static::hardenDirectory($path, $mode);
}
}
// 방금 만든 경로의 stat 은 캐시돼 있을 수 있다 — 판정 전에 비운다.
clearstatcache(true, $path);
if (! is_dir($path)) {
$failure = ['reason' => 'create_failed', 'path' => $path];
return false;
}
if (! is_writable($path)) {
$failure = ['reason' => 'not_writable', 'path' => $path];
return false;
}
return true;
}
/**
* 경로에서 위로 올라가며 실재하는 첫 디렉토리를 찾습니다.
*
* @param string $path 기준 경로
* @return string|null 실재하는 최근접 상위 (루트까지 없으면 null)
*/
public static function nearestExistingAncestor(string $path): ?string
{
$current = dirname($path);
while (! File::isDirectory($current)) {
$parent = dirname($current);
if ($parent === $current) {
return null;
}
$current = $parent;
}
return $current;
}
/**
* 소유자·그룹을 적용합니다. sudo 없이 실행 시 silent fail 로 현행 동작 유지.
*
+3 -2
View File
@@ -2,6 +2,7 @@
namespace App\Extension\Helpers;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
@@ -406,10 +407,10 @@ class SettingsMigrator
private function getSettingsDir(): string
{
if ($this->type === 'module') {
return storage_path('app/modules/'.$this->identifier.'/settings');
return ExtensionStoragePath::module($this->identifier, 'settings');
}
return storage_path('app/plugins/'.$this->identifier.'/settings');
return ExtensionStoragePath::plugin($this->identifier, 'settings');
}
/**
+4 -3
View File
@@ -44,6 +44,7 @@ use App\Models\Template;
use App\Providers\CoreServiceProvider;
use App\Services\LayoutExtensionService;
use App\Support\AssetUrl;
use App\Support\ExtensionStoragePath;
use App\Support\RouteCacheHelper;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
@@ -1791,7 +1792,7 @@ class ModuleManager implements ModuleManagerInterface
}
$identifier = $module->getIdentifier();
$settingsDir = storage_path('app/modules/'.$identifier.'/settings');
$settingsDir = ExtensionStoragePath::module($identifier, 'settings');
// 이미 환경설정 디렉토리가 있고 파일이 있으면 스킵 (재설치 시 덮어쓰기 방지)
if (File::isDirectory($settingsDir) && count(File::files($settingsDir)) > 0) {
@@ -1915,7 +1916,7 @@ class ModuleManager implements ModuleManagerInterface
*/
protected function deleteModuleStorage(ModuleInterface $module): void
{
$moduleStoragePath = storage_path('app/modules/'.$module->getIdentifier());
$moduleStoragePath = ExtensionStoragePath::module($module->getIdentifier());
if (! File::isDirectory($moduleStoragePath)) {
Log::info('삭제할 모듈 스토리지 디렉토리가 없습니다.', [
@@ -2000,7 +2001,7 @@ class ModuleManager implements ModuleManagerInterface
// 5. 스토리지 디렉토리 1-depth 용량 조회
$storageInfo = $this->getStorageDirectoriesInfo(
storage_path('app/modules/'.$identifier)
ExtensionStoragePath::module($identifier)
);
// 6. Composer vendor 디렉토리 정보 조회
+4 -3
View File
@@ -45,6 +45,7 @@ use App\Providers\CoreServiceProvider;
use App\Services\DriverRegistryService;
use App\Services\LayoutExtensionService;
use App\Support\AssetUrl;
use App\Support\ExtensionStoragePath;
use App\Support\RouteCacheHelper;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
@@ -2610,7 +2611,7 @@ class PluginManager implements PluginManagerInterface
protected function initializePluginSettings(PluginInterface $plugin): void
{
$identifier = $plugin->getIdentifier();
$settingsDir = storage_path("app/plugins/{$identifier}/settings");
$settingsDir = ExtensionStoragePath::plugin($identifier, 'settings');
$settingsPath = $settingsDir.'/setting.json';
// 이미 설정 파일이 존재하면 스킵 (재설치 시 기존 설정 유지)
@@ -2691,7 +2692,7 @@ class PluginManager implements PluginManagerInterface
protected function deletePluginSettingsDirectory(PluginInterface $plugin): void
{
$identifier = $plugin->getIdentifier();
$pluginStorageDir = storage_path("app/plugins/{$identifier}");
$pluginStorageDir = ExtensionStoragePath::plugin($identifier);
if (File::isDirectory($pluginStorageDir)) {
File::deleteDirectory($pluginStorageDir);
@@ -2761,7 +2762,7 @@ class PluginManager implements PluginManagerInterface
// 5. 스토리지 디렉토리 1-depth 용량 조회
$storageInfo = $this->getStorageDirectoriesInfo(
storage_path('app/plugins/'.$identifier)
ExtensionStoragePath::plugin($identifier)
);
// 6. Composer vendor 디렉토리 정보 조회