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

@@ -8,6 +8,7 @@ use App\Models\Permission;
use App\Models\Plugin;
use App\Models\Role;
use App\Models\User;
use App\Support\ExtensionStoragePath;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
@@ -130,7 +131,7 @@ class PluginSettingsControllerTest extends TestCase
*/
private function createTestSettingsFile(string $identifier, array $settings): void
{
$settingsDir = storage_path("app/plugins/{$identifier}/settings");
$settingsDir = ExtensionStoragePath::plugin($identifier, 'settings');
$settingsPath = $settingsDir.'/setting.json';
if (! File::isDirectory($settingsDir)) {
@@ -145,7 +146,7 @@ class PluginSettingsControllerTest extends TestCase
*/
private function cleanupTestSettings(string $identifier): void
{
$pluginDir = storage_path("app/plugins/{$identifier}");
$pluginDir = ExtensionStoragePath::plugin($identifier);
if (File::isDirectory($pluginDir)) {
File::deleteDirectory($pluginDir);
}
@@ -319,12 +320,14 @@ class PluginSettingsControllerTest extends TestCase
->assertJson(['success' => true]);
// 파일에서 값 확인
$settingsPath = storage_path('app/plugins/sirsoft-daum_postcode/settings/setting.json');
if (File::exists($settingsPath)) {
$savedContent = json_decode(File::get($settingsPath), true);
$this->assertSame('popup', $savedContent['display_mode'] ?? null);
$this->assertSame(640, $savedContent['popup_width'] ?? null);
}
$settingsPath = ExtensionStoragePath::plugin('sirsoft-daum_postcode', 'settings').'/setting.json';
// 저장이 200 으로 끝났으므로 파일은 반드시 있어야 한다 — `File::exists` 조건 안에
// 단언을 두면 경로가 어긋났을 때 검사가 조용히 공허해진다.
$this->assertFileExists($settingsPath);
$savedContent = json_decode(File::get($settingsPath), true);
$this->assertSame('popup', $savedContent['display_mode'] ?? null);
$this->assertSame(640, $savedContent['popup_width'] ?? null);
// 정리
$this->cleanupTestSettings('sirsoft-daum_postcode');
@@ -357,12 +360,15 @@ class PluginSettingsControllerTest extends TestCase
'another_unknown' => ['nested' => true],
]);
$settingsPath = storage_path('app/plugins/sirsoft-daum_postcode/settings/setting.json');
if (File::exists($settingsPath)) {
$savedContent = json_decode(File::get($settingsPath), true);
$this->assertArrayNotHasKey('injected_field', $savedContent);
$this->assertArrayNotHasKey('another_unknown', $savedContent);
}
$settingsPath = ExtensionStoragePath::plugin('sirsoft-daum_postcode', 'settings').'/setting.json';
// 스키마 밖 키만 담긴 요청은 저장 자체가 일어나지 않을 수 있다. 그 경우에도 단언은
// 수행한다 — 조건 안에 두면 파일이 없을 때 검사가 0건이 되어 공허하게 통과한다.
$savedContent = File::exists($settingsPath)
? (json_decode(File::get($settingsPath), true) ?? [])
: [];
$this->assertArrayNotHasKey('injected_field', $savedContent);
$this->assertArrayNotHasKey('another_unknown', $savedContent);
$this->cleanupTestSettings('sirsoft-daum_postcode');
}
@@ -81,6 +81,38 @@ class ExtensionTestIsolationTest extends TestCase
);
}
/**
* 테스트는 운영 라우트 캐시로 부팅하지 않는다.
*
* 라우트 캐시가 있으면 `RouteServiceProvider::boot()` 이 캐시 로드로 분기해 **라우트 파일이
* 실행되지 않는다.** 그러면 allowlist 가 라우트 축에서 통째로 무력화되어, core-only 테스트가
* 굽던 시점에 활성이던 모든 확장의 라우트를 가진 채 부팅한다.
*
* 위의 GDPR 라우트 단언만으로는 이 결함을 안정적으로 잡지 못한다 — GDPR 이 그 머신에
* 설치돼 있어야만 red 가 되기 때문이다. 여기서는 **메커니즘 자체**를 단언한다.
*
* @effects tests_do_not_boot_with_production_route_cache
*/
public function test_tests_do_not_boot_with_the_production_route_cache(): void
{
$cachedRoutesPath = $this->app->getCachedRoutesPath();
// 경로 구분자를 슬래시로 통일해 판정한다 — Windows 는 역슬래시를 섞어 돌려준다.
$normalized = strtr($cachedRoutesPath, '\\', '/');
$this->assertStringNotContainsString(
'bootstrap/cache',
$normalized,
'테스트가 운영 라우트 캐시 경로를 본다 — tests/bootstrap.php 의 APP_ROUTES_CACHE '
.'리다이렉트가 사라졌다. 라우트 파일이 실행되지 않아 확장 격리가 무력화된다.'
);
$this->assertFalse(
$this->app->routesAreCached(),
'테스트가 캐시된 라우트로 부팅했다 — 라우트 파일이 실행되지 않아 allowlist 가 적용되지 않는다.'
);
}
/**
* @effects allowlist_inactive_when_never_configured
*/
@@ -99,7 +131,7 @@ class ExtensionTestIsolationTest extends TestCase
/**
* @effects selfExtension_returns_null_for_core_tests
*/
public function test_selfExtension_returns_null_for_core_tests(): void
public function test_self_extension_returns_null_for_core_tests(): void
{
// 본 테스트 클래스는 tests/Feature/ 하위 (코어 테스트) →
// selfExtension() 의 modules/plugins 경로 패턴에 매칭되지 않아 null 반환
@@ -6,6 +6,7 @@ use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Contracts\Repositories\TemplateRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Extension\Helpers\FilePermissionHelper;
use App\Models\Module;
use App\Models\Plugin;
use App\Models\Template;
@@ -1204,16 +1205,31 @@ class ExtensionStaticCacheServiceTest extends TestCase
);
// ① 디렉토리 생성은 umask 를 무력화하는 명시 chmod 를 거친다.
//
// 정합화 구현은 코어 공통 프리미티브(`FilePermissionHelper::hardenDirectory`)로 옮겼다.
// 검사도 그 위임을 따라가야 한다 — 옮겨간 뒤에도 이 클래스의 소스 리터럴만 보면 실제로
// 도는 코드가 아닌 **죽은 자리**를 지키게 되어 가드가 공허해진다.
$makeDirectory = $this->methodBody($source, 'makeDirectory');
$this->assertNotSame('', $makeDirectory, 'makeDirectory 를 소스에서 찾지 못했다 — 검사가 공허하다');
$this->assertStringContainsString(
'@chmod($dir, self::PUBLISH_DIR_MODE)',
'FilePermissionHelper::hardenDirectory($dir, self::PUBLISH_DIR_MODE)',
$makeDirectory,
'게시 디렉토리 정합화가 공통 프리미티브를 거치지 않는다 — umask/소유권 규율이 이 클래스에서 갈라진다'
);
$helperSource = (string) file_get_contents(
(new \ReflectionClass(FilePermissionHelper::class))->getFileName()
);
$harden = $this->methodBody($helperSource, 'hardenDirectory');
$this->assertNotSame('', $harden, 'hardenDirectory 를 소스에서 찾지 못했다 — 검사가 공허하다');
$this->assertStringContainsString(
'@chmod($path, $mode)',
$harden,
'ensureDirectoryExists 의 mode 는 umask 로 깎인다 — 명시 chmod 가 없으면 0755 로 굳는다'
);
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($dir)',
$makeDirectory
'static::inheritOwnershipFromParent($path)',
$harden
);
// ② 정합화는 root 갈래와 항상-실행 갈래를 모두 갖는다.
@@ -0,0 +1,177 @@
<?php
namespace Tests\Unit\Extension;
use Composer\Autoload\ClassLoader;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 확장 vendor(제3자 composer 패키지)가 PHPUnit 프로세스에서도 오토로드되는지에 대한 회귀 테스트.
*
* `autoload-extensions.php` 의 `vendor_autoloads` 를 소비하는 진입점은 `public/index.php` 와
* `artisan` 뿐이었다. 그래서 테스트 프로세스에서는 확장 전용 패키지가 오토로드되지 않았고,
* 그 패키지를 쓰는 코드 경로가 통째로 테스트 불가였다 — 아무도 그 경로를 테스트하지 않는 동안
* 이 결손은 드러나지 않는다 (공개 #125 에서 처음 드러났다).
*
* `tests/bootstrap.php` 가 그 등록을 하되, 확장 vendor 의 `autoload.php` 를 그대로 require
* 하지 않고 제3자 항목만 골라 `vendorDir` 없는 로더로 등록한다. 그렇게 하지 않으면 두 가지가
* 조용히 깨지며, 그 둘이 이 테스트의 나머지 두 축이다.
*/
class ExtensionVendorAutoloadInTestsTest extends TestCase
{
/**
* 확장 vendor 의 제3자 클래스가 테스트 프로세스에서 오토로드된다.
*
* 모집단 주의: 확장 활성 디렉토리와 그 `vendor/` 는 gitignore 대상이라, 확장 composer
* 설치를 하지 않은 체크아웃에서는 모집단이 0 이 되어 이 단언이 공허하게 통과한다.
* 그 상태에서도 아래 두 축(자기 네임스페이스 비하이재킹 / base path 무결성)은 유효하다.
*/
#[Test]
public function extension_third_party_packages_are_autoloadable(): void
{
$unloadable = [];
$sampled = [];
foreach ($this->discoverExtensionVendorClassmaps() as $classmapFile) {
foreach (require $classmapFile as $fqcn => $path) {
// 확장 자기 심볼은 애초에 등록 대상이 아니고, Composer 자신의 클래스는 루트 오토로더가
// 이미 들고 있어 우리 등록이 없어도 통과한다 — 표본으로 쓰면 공허한 단언이 된다.
if ($this->isExtensionOwnSymbol($fqcn) || str_starts_with($fqcn, 'Composer\\')) {
continue;
}
$sampled[] = $fqcn;
if (! class_exists($fqcn) && ! interface_exists($fqcn) && ! trait_exists($fqcn)) {
$unloadable[] = $fqcn;
}
// 확장마다 대표 1건만 본다 — 맵 전체를 로드하면 스위트가 느려지고,
// 오토로더가 걸렸는지 여부는 대표 1건으로 판정된다.
break;
}
}
$this->assertSame(
[],
$unloadable,
'확장 vendor 의 제3자 클래스가 테스트 프로세스에서 오토로드되지 않았습니다 — '
.'tests/bootstrap.php 의 확장 vendor 등록을 확인하세요. 표본: '
.implode(', ', $sampled)
);
}
/**
* 확장 자기 네임스페이스가 vendor 오토로더에 하이재킹되지 않는다.
*
* 확장 vendor 의 Composer 오토로더는 확장 자신의 PSR-4 를 **활성** 디렉토리로 매핑하고
* 자신을 prepend 로 등록한다. 그것을 그대로 쓰면 `tests/bootstrap.php` 가 앞서 prepend 한
* `_bundled` 등록을 이겨서, 테스트가 `_bundled` 가 아니라 활성 디렉토리 사본을 검증하게
* 된다 — `_bundled` 에서만 작업한다는 규율이 오류 없이 깨지는 형태다.
*/
#[Test]
public function bundled_extension_classes_are_not_hijacked_to_the_active_directory(): void
{
$hijacked = [];
foreach (glob(base_path('modules/_bundled/*/module.php')) ?: [] as $manifest) {
$identifier = basename(dirname($manifest));
$class = $this->extensionEntryClass('Modules', $identifier);
if ($class === null || ! class_exists($class)) {
continue;
}
$file = (new \ReflectionClass($class))->getFileName();
if ($file !== false && ! str_contains(str_replace('\\', '/', $file), '/modules/_bundled/')) {
$hijacked[$identifier] = $file;
}
}
$this->assertSame(
[],
$hijacked,
'_bundled 확장의 클래스가 활성 디렉토리에서 로드되었습니다 — 확장 vendor 오토로더가 '
.'자기 PSR-4 를 등록하고 있습니다.'
);
}
/**
* 등록된 Composer 로더 목록의 첫 항목이 루트 vendor 로 남는다.
*
* Composer 로더는 `vendorDir` 를 가지면 `ClassLoader::getRegisteredLoaders()` 맨 앞에
* 자신을 넣는데, `Illuminate\Foundation\Testing\TestCase::createApplication()` 이
* `Application::inferBasePath()` 로 그 첫 항목에서 base path 를 유추한다. 확장 vendor 의
* 로더가 그 자리를 차지하면 이후 테스트의 앱 부팅이 `modules/{id}/bootstrap/app.php` 를
* 찾다 실패한다. (운영 진입점은 basePath 를 명시 전달하므로 영향이 없다.)
*/
#[Test]
public function registered_loader_list_still_points_at_the_project_root(): void
{
$registered = array_keys(ClassLoader::getRegisteredLoaders());
$this->assertNotEmpty($registered, '등록된 Composer 로더가 없습니다.');
$this->assertSame(
realpath(base_path('vendor')),
realpath($registered[0]),
'Composer 로더 목록의 첫 항목이 루트 vendor 가 아닙니다 — 확장 vendor 로더가 '
.'vendorDir 를 갖고 등록되어 Application::inferBasePath() 를 오염시킵니다.'
);
}
/**
* 확장(모듈/플러그인)의 vendor classmap 파일 경로를 모읍니다.
*
* @return array<int, string> classmap 파일 절대 경로 목록
*/
private function discoverExtensionVendorClassmaps(): array
{
$found = [];
foreach (['modules', 'plugins'] as $type) {
foreach ([$type, $type.'/_bundled'] as $dir) {
foreach (glob(base_path($dir.'/*/vendor/composer/autoload_classmap.php')) ?: [] as $file) {
$found[] = $file;
}
}
}
return $found;
}
/**
* 확장 자신의 네임스페이스에 속하는 심볼인지 판정합니다.
*
* @param string $symbol FQCN 또는 PSR-4 접두사
* @return bool 확장 자기 심볼이면 true
*/
private function isExtensionOwnSymbol(string $symbol): bool
{
return str_starts_with($symbol, 'Modules\\') || str_starts_with($symbol, 'Plugins\\');
}
/**
* 확장 식별자로부터 진입 클래스 FQCN 을 조립합니다.
*
* @param string $root 네임스페이스 루트 (Modules|Plugins)
* @param string $identifier 확장 식별자 (vendor-name)
* @return string|null FQCN. 식별자 형식이 아니면 null
*/
private function extensionEntryClass(string $root, string $identifier): ?string
{
$parts = explode('-', $identifier);
if (count($parts) < 2) {
return null;
}
$vendor = ucfirst($parts[0]);
$name = str_replace('_', '', ucwords($parts[1], '_'));
$entry = $root === 'Modules' ? 'Module' : 'Plugin';
return $root.'\\'.$vendor.'\\'.$name.'\\'.$entry;
}
}
@@ -3,6 +3,7 @@
namespace Tests\Unit\Extension;
use App\Extension\PluginManager;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Mockery;
@@ -26,7 +27,7 @@ class PluginManagerSettingsTest extends TestCase
{
parent::setUp();
$this->testSettingsDir = storage_path('app/plugins/test-init-plugin/settings');
$this->testSettingsDir = ExtensionStoragePath::plugin('test-init-plugin', 'settings');
$this->testDefaultsDir = sys_get_temp_dir().'/g7_test_defaults_'.uniqid();
// 테스트용 디렉토리 정리
@@ -3,6 +3,7 @@
namespace Tests\Unit\Extension;
use App\Extension\Helpers\SettingsMigrator;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
@@ -18,8 +19,8 @@ class SettingsMigratorTest extends TestCase
{
parent::setUp();
$this->moduleSettingsDir = storage_path('app/modules/test-migrator-mod/settings');
$this->pluginSettingsDir = storage_path('app/plugins/test-migrator-plug/settings');
$this->moduleSettingsDir = ExtensionStoragePath::module('test-migrator-mod', 'settings');
$this->pluginSettingsDir = ExtensionStoragePath::plugin('test-migrator-plug', 'settings');
$this->moduleDir = base_path('modules/test-migrator-mod');
// 모듈 설정 디렉토리 및 파일 생성
@@ -59,12 +60,12 @@ class SettingsMigratorTest extends TestCase
protected function tearDown(): void
{
if (File::isDirectory(storage_path('app/modules/test-migrator-mod'))) {
File::deleteDirectory(storage_path('app/modules/test-migrator-mod'));
if (File::isDirectory(ExtensionStoragePath::module('test-migrator-mod'))) {
File::deleteDirectory(ExtensionStoragePath::module('test-migrator-mod'));
}
if (File::isDirectory(storage_path('app/plugins/test-migrator-plug'))) {
File::deleteDirectory(storage_path('app/plugins/test-migrator-plug'));
if (File::isDirectory(ExtensionStoragePath::plugin('test-migrator-plug'))) {
File::deleteDirectory(ExtensionStoragePath::plugin('test-migrator-plug'));
}
if (File::isDirectory($this->moduleDir)) {
@@ -0,0 +1,186 @@
<?php
namespace Tests\Unit\Helpers;
use App\Extension\Helpers\FilePermissionHelper;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* `FilePermissionHelper::ensureWritableDirectory()` 단위 테스트.
*
* 이 프리미티브의 존재 이유는 "확보 실패가 다시 500 을 내지 않는 것" 이다. 제3자 라이브러리에
* 쓰기 경로를 지정하는 목적 자체가 vendor 쓰기 실패로 인한 500 을 막는 것인데, 확보 지점이
* PHP 경고를 내면 Laravel `HandleExceptions` 가 이를 `ErrorException` 으로 승격시켜 같은 500 이
* 다른 줄에서 그대로 난다 (공개 #125 의 2차 결함).
*
* 그래서 실패 케이스는 반환값만 보지 않고 **경고가 나지 않았다는 것까지** 단언한다 — 경고를
* 예외로 바꾸는 핸들러를 씌운 채로 호출해, 승격이 일어나면 테스트가 실패하도록 만든다.
*/
class FilePermissionHelperWritableDirectoryTest extends TestCase
{
/** 테스트가 만든 경로 (tearDown 정리 대상) */
private string $root;
protected function setUp(): void
{
parent::setUp();
$this->root = storage_path('framework/testing/writable-dir-'.getmypid());
File::deleteDirectory($this->root);
File::ensureDirectoryExists($this->root);
}
protected function tearDown(): void
{
File::deleteDirectory($this->root);
parent::tearDown();
}
/**
* PHP 경고를 `ErrorException` 으로 승격시키는 핸들러 아래에서 콜백을 실행합니다.
*
* `Illuminate\Foundation\Bootstrap\HandleExceptions::handleError()` 와 **동형**이어야 한다 —
* 그 핸들러는 `error_reporting() & $level` 을 확인하므로 `@` 로 억제된 진단은 승격시키지
* 않는다. 이 검사를 빠뜨리면 억제를 존중하는 올바른 코드까지 실패로 보고해, 실제 운영에서는
* 나지 않는 500 을 있다고 말하게 된다.
*
* 따라서 이 헬퍼가 잡아내는 것은 정확히 하나다 — **억제되지 않은 경고가 새어 나가는가.**
* `File::makeDirectory(..., force: true)` 를 `ensureDirectoryExists()` 로 되돌리면 여기서 걸린다.
*
* @param \Closure $callback 실행할 콜백
* @return mixed 콜백 반환값
*/
private function withWarningsAsExceptions(\Closure $callback): mixed
{
set_error_handler(static function (int $level, string $message, string $file = '', int $line = 0): bool {
if (error_reporting() & $level) {
throw new \ErrorException($message, 0, $level, $file, $line);
}
return true;
});
try {
return $callback();
} finally {
restore_error_handler();
}
}
/**
* 없는 디렉토리를 만들고 쓰기 가능으로 판정합니다.
*/
public function test_creates_missing_directory_and_reports_writable(): void
{
$target = $this->root.'/created/deeply/nested';
$this->assertFalse(is_dir($target));
$result = FilePermissionHelper::ensureWritableDirectory($target, 0775, $failure);
$this->assertTrue($result);
$this->assertNull($failure);
$this->assertDirectoryExists($target);
$this->assertTrue(is_writable($target));
}
/**
* 이미 있는 쓰기 가능 디렉토리는 그대로 통과합니다 (재생성하지 않음).
*/
public function test_returns_true_for_existing_writable_directory(): void
{
$target = $this->root.'/existing';
File::ensureDirectoryExists($target);
File::put($target.'/keep.txt', 'keep');
$this->assertTrue(FilePermissionHelper::ensureWritableDirectory($target, 0775, $failure));
$this->assertNull($failure);
// 내용이 보존됐다 = 지우고 다시 만들지 않았다.
$this->assertFileExists($target.'/keep.txt');
}
/**
* 같은 이름의 파일이 자리를 차지하면 경고 없이 실패 사유를 돌려줍니다.
*/
public function test_reports_occupied_by_file_without_raising_warning(): void
{
$target = $this->root.'/occupied';
File::put($target, 'not a directory');
$failure = null;
$result = $this->withWarningsAsExceptions(
function () use ($target, &$failure) {
return FilePermissionHelper::ensureWritableDirectory($target, 0775, $failure);
}
);
$this->assertFalse($result);
$this->assertSame('occupied_by_file', $failure['reason']);
$this->assertSame($target, $failure['path']);
}
/**
* 경로 중간이 파일이라 생성이 불가능해도 경고 없이 실패 사유를 돌려줍니다.
*
* 상위(`$this->root`)는 쓰기 가능하므로 `ancestor_not_writable` 로 걸러지지 않고 실제
* `mkdir` 까지 가서 실패하는 경로다 — 억제되지 않은 `mkdir` 이었다면 여기서 경고가 난다.
*/
public function test_reports_create_failed_when_a_path_segment_is_a_file(): void
{
$blocker = $this->root.'/blocker';
File::put($blocker, 'file in the middle of the path');
$target = $blocker.'/sub/cache';
$failure = null;
$result = $this->withWarningsAsExceptions(
function () use ($target, &$failure) {
return FilePermissionHelper::ensureWritableDirectory($target, 0775, $failure);
}
);
$this->assertFalse($result);
$this->assertSame('create_failed', $failure['reason']);
$this->assertSame($target, $failure['path']);
$this->assertDirectoryDoesNotExist($target);
}
/**
* 실재하는 최근접 상위를 찾아 올라갑니다.
*/
public function test_nearest_existing_ancestor_walks_up_to_first_existing_directory(): void
{
$this->assertSame(
rtrim($this->root, '/\\'),
rtrim((string) FilePermissionHelper::nearestExistingAncestor($this->root.'/a/b/c'), '/\\')
);
$existing = $this->root.'/present';
File::ensureDirectoryExists($existing);
$this->assertSame(
rtrim($existing, '/\\'),
rtrim((string) FilePermissionHelper::nearestExistingAncestor($existing.'/child'), '/\\')
);
}
/**
* 정합화는 대상이 없어도 예외·경고를 내지 않습니다.
*
* `hardenDirectory()` 는 `@` 억제 chmod 와 소유권 상속만 수행하므로, 경합으로 대상이
* 사라진 상황에서도 호출자에게 실패를 던지지 않아야 한다.
*/
public function test_harden_directory_is_silent_when_target_is_absent(): void
{
$missing = $this->root.'/vanished';
$this->withWarningsAsExceptions(function () use ($missing): void {
FilePermissionHelper::hardenDirectory($missing, 0775);
});
$this->assertDirectoryDoesNotExist($missing);
}
}
@@ -2,11 +2,11 @@
namespace Tests\Unit\Services;
use App\Contracts\Extension\ModuleInterface;
use App\Extension\ModuleManager;
use App\Extension\TemplateManager;
use App\Services\LayoutService;
use App\Services\ModuleSettingsService;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;
use Mockery;
@@ -48,7 +48,7 @@ class ModuleSettingsServiceTest extends TestCase
);
// 테스트용 설정 디렉토리 경로
$this->testSettingsDir = storage_path('app/modules');
$this->testSettingsDir = dirname(ExtensionStoragePath::module('placeholder'));
}
// ========================================================================
@@ -6,6 +6,7 @@ use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Services\LayoutService;
use App\Services\PluginSettingsService;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Facades\Crypt;
use Mockery;
use Tests\Helpers\MocksExtensions;
@@ -46,7 +47,7 @@ class PluginSettingsServiceTest extends TestCase
);
// 테스트용 설정 디렉토리 경로
$this->testSettingsDir = storage_path('app/plugins');
$this->testSettingsDir = dirname(ExtensionStoragePath::plugin('placeholder'));
}
// ========================================================================
+125
View File
@@ -1,5 +1,7 @@
<?php
use Composer\Autoload\ClassLoader;
/**
* PHPUnit 테스트용 부트스트랩 파일
*
@@ -143,6 +145,35 @@ if (file_exists($configCacheFile)) {
unlink($configCacheFile);
}
/*
|--------------------------------------------------------------------------
| 라우트 캐시 격리 (테스트 환경 보장)
|--------------------------------------------------------------------------
|
| 라우트 캐시가 있으면 `RouteServiceProvider::boot()` 이 캐시 로드로 분기해 **라우트 파일이
| 아예 실행되지 않는다.** 그러면 테스트가 선언한 확장 allowlist(`requiredExtensions`)가
| 라우트 축에서 통째로 무력화된다 — core-only 테스트인데도 굽던 시점에 활성이던 모든 확장의
| 라우트가 등록된 채로 부팅한다. 실패는 그 사실을 단언하는 테스트에서만 드러나고, 나머지
| 테스트는 격리가 깨진 줄 모르는 채 통과한다.
|
| 라우트 캐시는 확장 설치·활성화·업데이트마다 `RouteCacheHelper::rebuild()` 가 다시 굽기
| 때문에, 개발 머신에서는 사실상 항상 존재한다.
|
| 삭제하지 않고 **경로를 돌린다.** 삭제하면 테스트를 한 번 돌릴 때마다 운영 중 사이트의
| 라우트 캐시가 사라지고(재생성은 다음 확장 작업까지 일어나지 않는다), 그 사이 모든 요청이
| 라우트 파일 스캔 경로로 떨어진다. 돌려놓은 경로의 파일은 만들지 않으므로
| `routesAreCached()` 가 false 가 되어 라우트 파일이 정상 실행되고, 테스트 안에서
| `route:cache` 를 굽더라도 그 산출물이 운영 캐시를 덮지 않는다.
|
| config 캐시(위)와 달리 삭제가 아니라 리다이렉트인 이유가 이것이다 — config 캐시는
| `config:cache` 로 즉시 복구되지만 라우트 캐시는 복구 시점이 확장 작업에 묶여 있다.
|
*/
$testingRoutesCache = 'storage/framework/testing/routes-v7.php';
putenv('APP_ROUTES_CACHE='.$testingRoutesCache);
$_ENV['APP_ROUTES_CACHE'] = $testingRoutesCache;
$_SERVER['APP_ROUTES_CACHE'] = $testingRoutesCache;
// Composer 오토로더 로드
$loader = require __DIR__.'/../vendor/autoload.php';
@@ -338,6 +369,100 @@ if (file_exists($extensionAutoloadFile)) {
}
}
/*
|--------------------------------------------------------------------------
| 확장 vendor(제3자 composer 패키지) 오토로드 등록
|--------------------------------------------------------------------------
|
| `autoload-extensions.php` 의 `vendor_autoloads` 를 소비하는 진입점은 `public/index.php`
| 와 `artisan` 뿐이라, PHPUnit 프로세스에서는 확장 전용 composer 패키지(`\HTMLPurifier` 등)가
| 오토로드되지 않았다. 그 패키지를 쓰는 코드 경로가 통째로 테스트 불가였고, 그 결손은 아무도
| 그 경로를 테스트하지 않는 동안 드러나지 않는다 (공개 #125).
|
| 확장 vendor 의 `autoload.php` 를 그대로 require 하지 않고 생성된 맵만 읽어 자체 로더를 만든다.
| 그 오토로더를 그대로 쓰면 두 가지가 깨진다.
|
| 1. 확장 자신의 PSR-4 와 files 를 **활성 디렉토리**로 매핑하고 자신을 prepend 로 걸어, 위에서
| _bundled 를 prepend 한 등록을 이긴다 — 테스트가 `_bundled` 가 아니라 활성 디렉토리 사본을
| 검증하게 되어 "_bundled 에서만 작업한다" 는 규율이 조용히 깨진다.
| 2. Composer 로더는 `vendorDir` 를 갖고 자신을 `ClassLoader::getRegisteredLoaders()` 맨 앞에
| 넣는데, `Illuminate\Foundation\Testing\TestCase::createApplication()` 이
| `Application::inferBasePath()` 로 그 첫 항목에서 base path 를 유추한다. 이후 테스트의 앱
| 부팅이 `modules/{id}/bootstrap/app.php` 를 찾다 실패한다. (운영 진입점은 basePath 를 명시
| 전달하므로 영향이 없다.)
|
| 그래서 `Modules\` / `Plugins\` 로 시작하는 항목은 전부 제외하고 — 확장 자기 코드는 위에서
| 이미 등록했다 — `vendorDir` 없는 단일 로더로 제3자 패키지만 등록한다. 루트 오토로더가 먼저
| 등록되어 있으므로 append 로 걸어 루트 vendor 가 우선하게 둔다(같은 패키지 중복 선언 방지).
|
*/
$extensionVendorLoader = new ClassLoader;
$extensionVendorClassMap = [];
$extensionVendorFiles = [];
$isExtensionOwnSymbol = static fn (string $symbol): bool => str_starts_with($symbol, 'Modules\\')
|| str_starts_with($symbol, 'Plugins\\');
foreach (['modules', 'plugins'] as $extensionType) {
foreach ([__DIR__.'/../'.$extensionType, __DIR__.'/../'.$extensionType.'/_bundled'] as $searchDir) {
if (! is_dir($searchDir)) {
continue;
}
foreach (scandir($searchDir) ?: [] as $entry) {
if ($entry === '.' || $entry === '..' || $entry === '_bundled' || $entry === '_pending') {
continue;
}
$vendorDir = $searchDir.'/'.$entry.'/vendor';
$classmapFile = $vendorDir.'/composer/autoload_classmap.php';
if (! is_dir($vendorDir) || ! file_exists($classmapFile)) {
continue;
}
// 먼저 발견한 것(활성 디렉토리)이 이긴다 — 같은 클래스를 뒤에서 덮어쓰지 않는다.
foreach (require $classmapFile as $fqcn => $path) {
if (! $isExtensionOwnSymbol($fqcn) && ! isset($extensionVendorClassMap[$fqcn])) {
$extensionVendorClassMap[$fqcn] = $path;
}
}
$psr4File = $vendorDir.'/composer/autoload_psr4.php';
if (file_exists($psr4File)) {
foreach (require $psr4File as $prefix => $paths) {
if (! $isExtensionOwnSymbol($prefix)) {
$extensionVendorLoader->addPsr4($prefix, $paths);
}
}
}
// 패키지가 요구하는 부트스트랩 파일(HTMLPurifier 의 HTMLPURIFIER_PREFIX 정의 등).
// vendor 디렉토리 바깥의 항목(확장 자신의 helpers)은 제외한다.
$filesFile = $vendorDir.'/composer/autoload_files.php';
if (file_exists($filesFile)) {
$vendorReal = realpath($vendorDir) ?: $vendorDir;
foreach (require $filesFile as $file) {
if (str_starts_with(realpath($file) ?: $file, $vendorReal)) {
$extensionVendorFiles[] = $file;
}
}
}
}
}
}
if ($extensionVendorClassMap !== []) {
$extensionVendorLoader->addClassMap($extensionVendorClassMap);
}
// vendorDir 를 주지 않았으므로 register() 가 registeredLoaders 를 건드리지 않는다.
$extensionVendorLoader->register();
foreach ($extensionVendorFiles as $extensionVendorFile) {
require_once $extensionVendorFile;
}
// 모듈/플러그인 테스트 네임스페이스 등록 (tests/ 디렉토리)
$modulesDir = __DIR__.'/../modules';
if (is_dir($modulesDir)) {
@@ -67,6 +67,7 @@ effects:
- allowlisted_plugin_middleware_is_registered_in_web_group
- selfExtension_returns_null_for_core_tests
- production_env_keeps_full_extension_loading
- tests_do_not_boot_with_production_route_cache
test_files:
- tests/Unit/Extension/ExtensionTestAllowlistTest.php