v7.0.0-beta.6 release
This commit is contained in:
1 parent
cc45c0b84c
commit
61f5874fd2
51 files changed
+4151
-106
No files matched your search
@@ -0,0 +1,391 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Extension\Helpers\CoreBackupHelper;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* CoreBackupHelper 의 manifest 기반 prune 단위 테스트.
|
||||
*
|
||||
* 자동 롤백 시 신 버전 신규 파일이 활성 디렉토리에 잔존하는 결함을 차단하는
|
||||
* `writeNewFilesManifest()` / `pruneNewFiles()` 의 동작을 검증한다.
|
||||
*
|
||||
* 본 테스트는 BASE_PATH 를 건드리지 않는다 — 백업/_pending/활성 디렉토리 3개를
|
||||
* 모두 storage/app/test_core_prune/ 아래 임시 fixture 로 구성하고 helper 의
|
||||
* "활성" 인자에 임시 경로를 명시 전달하는 방식으로 격리한다.
|
||||
*/
|
||||
class CoreBackupHelperPruneTest extends TestCase
|
||||
{
|
||||
private string $testRoot;
|
||||
|
||||
private string $backupPath;
|
||||
|
||||
private string $sourcePath;
|
||||
|
||||
private string $activePath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->testRoot = storage_path('app/test_core_prune_'.uniqid());
|
||||
$this->backupPath = $this->testRoot.'/backup';
|
||||
$this->sourcePath = $this->testRoot.'/_pending';
|
||||
$this->activePath = $this->testRoot.'/active';
|
||||
|
||||
File::ensureDirectoryExists($this->backupPath);
|
||||
File::ensureDirectoryExists($this->sourcePath);
|
||||
File::ensureDirectoryExists($this->activePath);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::isDirectory($this->testRoot)) {
|
||||
File::deleteDirectory($this->testRoot);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// writeNewFilesManifest() — manifest 생성
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* _pending 에만 있고 backup 에는 없는 파일이 new_files 로 식별되는지 검증.
|
||||
*/
|
||||
public function test_write_manifest_identifies_new_files_in_pending_only(): void
|
||||
{
|
||||
// backup (= 활성 디렉토리의 사전 스냅샷) 에 있는 기존 파일
|
||||
File::ensureDirectoryExists($this->backupPath.'/app/Services');
|
||||
File::put($this->backupPath.'/app/Services/ExistingService.php', '<?php');
|
||||
|
||||
// _pending 에는 기존 + 신규
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app/Services');
|
||||
File::put($this->sourcePath.'/app/Services/ExistingService.php', '<?php // updated');
|
||||
File::put($this->sourcePath.'/app/Services/NewServiceProviderClass.php', '<?php // new');
|
||||
|
||||
$result = CoreBackupHelper::writeNewFilesManifest(
|
||||
$this->backupPath,
|
||||
$this->sourcePath,
|
||||
['app'],
|
||||
[],
|
||||
[],
|
||||
'7.0.0-beta.5',
|
||||
'7.0.0-beta.6',
|
||||
);
|
||||
|
||||
$manifestPath = $this->backupPath.'/_new_files_manifest.json';
|
||||
$this->assertFileExists($manifestPath);
|
||||
|
||||
$manifest = json_decode(File::get($manifestPath), true);
|
||||
$this->assertIsArray($manifest);
|
||||
$this->assertSame(1, $manifest['version']);
|
||||
$this->assertSame('7.0.0-beta.5', $manifest['from_version']);
|
||||
$this->assertSame('7.0.0-beta.6', $manifest['to_version']);
|
||||
$this->assertContains('app/Services/NewServiceProviderClass.php', $manifest['new_files']);
|
||||
$this->assertNotContains('app/Services/ExistingService.php', $manifest['new_files']);
|
||||
$this->assertGreaterThanOrEqual(1, $result['new_files_count']);
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 에만 있는 신규 디렉토리가 new_dirs 로 식별되는지 검증.
|
||||
*/
|
||||
public function test_write_manifest_identifies_new_dirs(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->backupPath.'/app');
|
||||
File::put($this->backupPath.'/app/keep.php', '<?php');
|
||||
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app');
|
||||
File::put($this->sourcePath.'/app/keep.php', '<?php');
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app/Services/LanguagePack');
|
||||
File::put($this->sourcePath.'/app/Services/LanguagePack/Module.php', '<?php');
|
||||
|
||||
CoreBackupHelper::writeNewFilesManifest(
|
||||
$this->backupPath,
|
||||
$this->sourcePath,
|
||||
['app'],
|
||||
[],
|
||||
[],
|
||||
'7.0.0-beta.5',
|
||||
'7.0.0-beta.6',
|
||||
);
|
||||
|
||||
$manifest = json_decode(File::get($this->backupPath.'/_new_files_manifest.json'), true);
|
||||
$this->assertContains('app/Services/LanguagePack', $manifest['new_dirs']);
|
||||
$this->assertContains('app/Services/LanguagePack/Module.php', $manifest['new_files']);
|
||||
}
|
||||
|
||||
/**
|
||||
* protectedPaths 하위는 manifest 에서 제외되는지 검증 (방어 깊이).
|
||||
*/
|
||||
public function test_write_manifest_excludes_protected_paths(): void
|
||||
{
|
||||
// _pending 에 storage/.env 가상 신규 파일 — 보호 경로
|
||||
File::ensureDirectoryExists($this->sourcePath.'/storage');
|
||||
File::put($this->sourcePath.'/storage/secret.txt', 'should not be tracked');
|
||||
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app');
|
||||
File::put($this->sourcePath.'/app/Real.php', '<?php');
|
||||
|
||||
CoreBackupHelper::writeNewFilesManifest(
|
||||
$this->backupPath,
|
||||
$this->sourcePath,
|
||||
['app', 'storage'],
|
||||
['storage'],
|
||||
[],
|
||||
'7.0.0-beta.5',
|
||||
'7.0.0-beta.6',
|
||||
);
|
||||
|
||||
$manifest = json_decode(File::get($this->backupPath.'/_new_files_manifest.json'), true);
|
||||
$this->assertNotContains('storage/secret.txt', $manifest['new_files']);
|
||||
$this->assertContains('app/Real.php', $manifest['new_files']);
|
||||
}
|
||||
|
||||
/**
|
||||
* excludes 패턴 (node_modules, .git 등) 은 manifest 에서 제외.
|
||||
*/
|
||||
public function test_write_manifest_excludes_pattern_matches(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app/node_modules');
|
||||
File::put($this->sourcePath.'/app/node_modules/lib.js', '');
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app');
|
||||
File::put($this->sourcePath.'/app/Real.php', '<?php');
|
||||
|
||||
CoreBackupHelper::writeNewFilesManifest(
|
||||
$this->backupPath,
|
||||
$this->sourcePath,
|
||||
['app'],
|
||||
[],
|
||||
['node_modules'],
|
||||
'7.0.0-beta.5',
|
||||
'7.0.0-beta.6',
|
||||
);
|
||||
|
||||
$manifest = json_decode(File::get($this->backupPath.'/_new_files_manifest.json'), true);
|
||||
$this->assertNotContains('app/node_modules/lib.js', $manifest['new_files']);
|
||||
$this->assertContains('app/Real.php', $manifest['new_files']);
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest JSON 의 키 순서 / 정렬 규칙 invariant — beta.6 Upgrade DataMigration 01
|
||||
* 의 사후 작성본과 바이트 단위 호환을 보장하기 위해 키 순서/정렬을 고정한다.
|
||||
*/
|
||||
public function test_manifest_schema_invariant(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->sourcePath.'/app');
|
||||
File::put($this->sourcePath.'/app/Beta.php', '<?php');
|
||||
File::put($this->sourcePath.'/app/Alpha.php', '<?php');
|
||||
|
||||
CoreBackupHelper::writeNewFilesManifest(
|
||||
$this->backupPath,
|
||||
$this->sourcePath,
|
||||
['app'],
|
||||
[],
|
||||
[],
|
||||
'7.0.0-beta.5',
|
||||
'7.0.0-beta.6',
|
||||
);
|
||||
|
||||
$manifest = json_decode(File::get($this->backupPath.'/_new_files_manifest.json'), true);
|
||||
|
||||
// 정렬 규칙: new_files / new_dirs 는 lexicographic ascending
|
||||
$sorted = $manifest['new_files'];
|
||||
$copy = $sorted;
|
||||
sort($copy, SORT_STRING);
|
||||
$this->assertSame($copy, $sorted, 'new_files 는 알파벳 오름차순 정렬되어야 함');
|
||||
|
||||
// 최상위 키 6종 명시 (DataMigration 01 의 invariant)
|
||||
$this->assertSame(
|
||||
['version', 'created_at', 'from_version', 'to_version', 'new_files', 'new_dirs'],
|
||||
array_keys($manifest),
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// pruneNewFiles() — manifest 기반 신규 파일 정리
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* manifest 에 등록된 신규 파일이 활성 디렉토리에서 삭제되는지 검증.
|
||||
*/
|
||||
public function test_prune_removes_new_files_listed_in_manifest(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->activePath.'/app/Services/LanguagePack');
|
||||
File::put($this->activePath.'/app/Services/LanguagePack/Module.php', '<?php');
|
||||
File::put($this->activePath.'/app/Services/UserKeep.php', '<?php // user');
|
||||
|
||||
$this->writeManifest([
|
||||
'new_files' => ['app/Services/LanguagePack/Module.php'],
|
||||
'new_dirs' => ['app/Services/LanguagePack'],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertFileDoesNotExist($this->activePath.'/app/Services/LanguagePack/Module.php');
|
||||
$this->assertDirectoryDoesNotExist($this->activePath.'/app/Services/LanguagePack');
|
||||
// 사용자 파일은 보존
|
||||
$this->assertFileExists($this->activePath.'/app/Services/UserKeep.php');
|
||||
|
||||
$this->assertSame(1, $result['removed_files']);
|
||||
$this->assertSame(1, $result['removed_dirs']);
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 의 new_dirs 중 사용자 파일이 남아있는 디렉토리는 rmdir 안 함.
|
||||
*/
|
||||
public function test_prune_keeps_dirs_with_user_files(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->activePath.'/app/Services/LanguagePack');
|
||||
File::put($this->activePath.'/app/Services/LanguagePack/Module.php', '<?php');
|
||||
File::put($this->activePath.'/app/Services/LanguagePack/UserAdded.php', '<?php // user');
|
||||
|
||||
$this->writeManifest([
|
||||
'new_files' => ['app/Services/LanguagePack/Module.php'],
|
||||
'new_dirs' => ['app/Services/LanguagePack'],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertFileDoesNotExist($this->activePath.'/app/Services/LanguagePack/Module.php');
|
||||
$this->assertDirectoryExists($this->activePath.'/app/Services/LanguagePack');
|
||||
$this->assertFileExists($this->activePath.'/app/Services/LanguagePack/UserAdded.php');
|
||||
|
||||
$this->assertSame(1, $result['removed_files']);
|
||||
$this->assertSame(0, $result['removed_dirs']);
|
||||
}
|
||||
|
||||
/**
|
||||
* protected_paths 하위 manifest 항목은 prune 시점에 재검증되어 삭제되지 않음.
|
||||
*/
|
||||
public function test_prune_respects_protected_paths_double_guard(): void
|
||||
{
|
||||
// manifest 에 가상으로 보호 경로 항목을 주입 — 운영 결함 또는 악의적 매니페스트 시뮬레이션
|
||||
File::ensureDirectoryExists($this->activePath.'/storage');
|
||||
File::put($this->activePath.'/storage/secret.txt', 'must keep');
|
||||
|
||||
$this->writeManifest([
|
||||
'new_files' => ['storage/secret.txt'],
|
||||
'new_dirs' => [],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles(
|
||||
$this->backupPath,
|
||||
$this->activePath,
|
||||
['storage'],
|
||||
);
|
||||
|
||||
$this->assertFileExists($this->activePath.'/storage/secret.txt');
|
||||
$this->assertSame(0, $result['removed_files']);
|
||||
$this->assertGreaterThanOrEqual(1, $result['protected_count']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리에 symlink 가 있고 manifest 에 등재되어 있어도 절대 삭제하지 않음.
|
||||
* Windows 에서는 markTestSkipped (symlink() 권한 제약).
|
||||
*/
|
||||
public function test_prune_skips_symlinks_unconditionally(): void
|
||||
{
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$this->markTestSkipped('Windows 에서는 PHP symlink() 권한이 필요하여 건너뜀');
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists($this->activePath.'/public');
|
||||
File::ensureDirectoryExists($this->activePath.'/storage/app/public');
|
||||
symlink($this->activePath.'/storage/app/public', $this->activePath.'/public/storage');
|
||||
|
||||
$this->writeManifest([
|
||||
'new_files' => ['public/storage'],
|
||||
'new_dirs' => [],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertTrue(is_link($this->activePath.'/public/storage'));
|
||||
$this->assertGreaterThanOrEqual(1, $result['symlink_skipped']);
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 부재 시 prune 은 noop + warning 없이 빈 결과 반환.
|
||||
*/
|
||||
public function test_prune_returns_zero_when_manifest_absent(): void
|
||||
{
|
||||
File::put($this->activePath.'/keep.php', '<?php');
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertFileExists($this->activePath.'/keep.php');
|
||||
$this->assertSame(0, $result['removed_files']);
|
||||
$this->assertSame(0, $result['removed_dirs']);
|
||||
$this->assertFalse($result['manifest_loaded']);
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest JSON 파싱 실패 시 prune 은 noop + manifest_loaded:false.
|
||||
*/
|
||||
public function test_prune_handles_corrupted_manifest_gracefully(): void
|
||||
{
|
||||
File::put($this->backupPath.'/_new_files_manifest.json', '{this is not valid json');
|
||||
File::put($this->activePath.'/keep.php', '<?php');
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertFileExists($this->activePath.'/keep.php');
|
||||
$this->assertFalse($result['manifest_loaded']);
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 의 new_files 가 실제 디스크에 없으면 (이미 삭제됨) skip.
|
||||
*/
|
||||
public function test_prune_skips_missing_files_gracefully(): void
|
||||
{
|
||||
$this->writeManifest([
|
||||
'new_files' => ['app/Nonexistent.php'],
|
||||
'new_dirs' => ['app/Ghost'],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertSame(0, $result['removed_files']);
|
||||
$this->assertSame(0, $result['removed_dirs']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 디렉토리 정리 — new_dirs 가 깊이 역순으로 처리되어 중첩 디렉토리도 제거.
|
||||
*/
|
||||
public function test_prune_empty_dirs_in_depth_reverse_order(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->activePath.'/a/b/c');
|
||||
File::put($this->activePath.'/a/b/c/file.php', '<?php');
|
||||
|
||||
$this->writeManifest([
|
||||
'new_files' => ['a/b/c/file.php'],
|
||||
'new_dirs' => ['a', 'a/b', 'a/b/c'],
|
||||
]);
|
||||
|
||||
$result = CoreBackupHelper::pruneNewFiles($this->backupPath, $this->activePath, []);
|
||||
|
||||
$this->assertDirectoryDoesNotExist($this->activePath.'/a');
|
||||
$this->assertSame(3, $result['removed_dirs']);
|
||||
}
|
||||
|
||||
private function writeManifest(array $data): void
|
||||
{
|
||||
$manifest = [
|
||||
'version' => 1,
|
||||
'created_at' => date('c'),
|
||||
'from_version' => '7.0.0-beta.5',
|
||||
'to_version' => '7.0.0-beta.6',
|
||||
'new_files' => $data['new_files'] ?? [],
|
||||
'new_dirs' => $data['new_dirs'] ?? [],
|
||||
];
|
||||
|
||||
File::put($this->backupPath.'/_new_files_manifest.json', json_encode(
|
||||
$manifest,
|
||||
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,52 @@ class EnvironmentDetectorTest extends TestCase
|
||||
$this->assertSame($hint, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* stat 가드 완화 회귀 — 시놀로지 DSM 등 open_basedir 환경에서 정상 절대경로
|
||||
* 가 false negative 로 거부되지 않고 hint/config 후보로 채택되어야 함.
|
||||
* 실제 실행 가능 여부는 canExecuteComposer 의 proc_open 결과로 최종 판정.
|
||||
*/
|
||||
public function test_find_composer_binary_accepts_safe_absolute_path_hint_without_stat(): void
|
||||
{
|
||||
$detector = new EnvironmentDetector;
|
||||
$detector->resetCache();
|
||||
|
||||
// 실제로 존재하지 않는 경로지만 메타문자 없음 — stat 가드 제거로 채택됨
|
||||
$hint = '/usr/local/bin/composer';
|
||||
$result = $detector->findComposerBinary($hint);
|
||||
|
||||
$this->assertSame($hint, $result);
|
||||
}
|
||||
|
||||
public function test_find_composer_binary_rejects_single_token_hint_with_shell_metachars(): void
|
||||
{
|
||||
$detector = new EnvironmentDetector;
|
||||
$detector->resetCache();
|
||||
|
||||
$original = config('process.composer_binary');
|
||||
config(['process.composer_binary' => null]);
|
||||
|
||||
try {
|
||||
// 단일 토큰(공백 없음) 셸 메타문자 hint 는 isExecutableCandidate 가 거부.
|
||||
// 공백 포함 hint 는 .env 값을 신뢰하는 운영자 자기 책임 영역이라 별도 분기.
|
||||
foreach ([
|
||||
'/bin/composer;id',
|
||||
'/bin/composer$(id)',
|
||||
'`/bin/composer`',
|
||||
'/bin/composer|nc',
|
||||
'/bin/composer&id',
|
||||
] as $payload) {
|
||||
$detector->resetCache();
|
||||
$result = $detector->findComposerBinary($payload);
|
||||
|
||||
// 메타문자 hint 는 절대 채택되지 않음 — 결과는 PATH 검색 결과 또는 null
|
||||
$this->assertNotSame($payload, $result, "메타문자 hint 거부: {$payload}");
|
||||
}
|
||||
} finally {
|
||||
config(['process.composer_binary' => $original]);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_summarize_returns_complete_report(): void
|
||||
{
|
||||
$report = $this->detector->summarize();
|
||||
|
||||
@@ -40,7 +40,22 @@ class ComposerPathValidationTest extends TestCase
|
||||
define('CHECK_CONFIGURATION_LIBRARY', true);
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/api/check-configuration.php';
|
||||
// BASE_PATH 가 다른 테스트 인프라에 의해 정의되지 않은 경우, 프로젝트 루트로
|
||||
// 정의해 인접 테스트(DeleteDirectoryTest/InstallerWindowsCommandsTest)의
|
||||
// `require_once BASE_PATH . '/public/install/...'` 패턴이 깨지지 않도록 함.
|
||||
$projectRoot = dirname(__DIR__, 3);
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
|
||||
}
|
||||
|
||||
require_once $projectRoot . '/public/install/api/check-configuration.php';
|
||||
// applyInstallerComposerEnvVars() 는 functions.php 에 정의. stat 가드 완화 회복
|
||||
// 이후 시스템 기본 'composer' 또는 정상 절대경로 입력이 exec 단계까지 도달하면서
|
||||
// 이 함수를 호출하므로 사전 로드 필요.
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,24 +36,25 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
define('CHECK_CONFIGURATION_LIBRARY', true);
|
||||
}
|
||||
|
||||
// BASE_PATH 미정의 시 프로젝트 루트로 정의 — 같은 PHPUnit 프로세스에서 뒤에
|
||||
// 실행되는 인접 테스트(DeleteDirectoryTest, InstallerWindowsCommandsTest 등)가
|
||||
// `require_once BASE_PATH . '/public/install/...'` 로 로드하는 패턴이 깨지지 않도록.
|
||||
$projectRoot = dirname(__DIR__, 3);
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
// STATE_PATH 는 테스트 격리용 임시 경로로 분리 — 운영 storage/installer-state.json 미오염.
|
||||
self::$tempBase = sys_get_temp_dir() . '/g7-installer-hardening-' . bin2hex(random_bytes(4));
|
||||
@mkdir(self::$tempBase . '/storage/app', 0755, true);
|
||||
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', self::$tempBase);
|
||||
} else {
|
||||
self::$tempBase = BASE_PATH;
|
||||
@mkdir(BASE_PATH . '/storage/app', 0755, true);
|
||||
}
|
||||
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
|
||||
define('STATE_PATH', self::$tempBase . '/storage/installer-state.json');
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/api/check-configuration.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-state.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/functions.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/task-runner.php';
|
||||
require_once $projectRoot . '/public/install/api/check-configuration.php';
|
||||
require_once $projectRoot . '/public/install/includes/installer-state.php';
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
require_once $projectRoot . '/public/install/includes/task-runner.php';
|
||||
|
||||
self::$loaded = true;
|
||||
}
|
||||
@@ -122,13 +123,16 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_nonexistent_path(): void
|
||||
public function test_getComposerCommand_passes_through_safe_absolute_path(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/nonexistent/path/to/composer']);
|
||||
// open_basedir 같은 PHP 런타임 제약 환경의 false negative 를 피하기 위해
|
||||
// stat 의존 가드가 제거됨. 메타문자 없는 단일 절대경로는 escape 후 그대로 사용.
|
||||
// 실제 실행 가능 여부는 exec 결과로 최종 판정 (silent fallback 안 함).
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/composer']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd);
|
||||
$this->assertSame(escapeshellarg('/usr/local/bin/composer'), $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
@@ -153,11 +157,252 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_metachars(): void
|
||||
{
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", 'a\\b'] as $bad) {
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), "메타문자 거부: {$bad}");
|
||||
// 백슬래시는 Windows 경로 구분자이므로 차단 대상 아님 (escapeshellarg 가 셸 인젝션 차단)
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", "a\0b", "a\x01b", "a\rb"] as $bad) {
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), "메타문자 거부: " . bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_accepts_windows_paths(): void
|
||||
{
|
||||
// Windows 절대경로는 백슬래시 포함이지만 공백·메타문자 없으면 통과.
|
||||
// 공백 포함 디렉토리(예: 'C:\\Program Files\\...') 는 공백 분리 입력 형식의 토큰
|
||||
// 분리 휴리스틱과 충돌하므로 본 회복 범위 외 — 알려진 한계.
|
||||
foreach ([
|
||||
'C:\\laragon\\bin\\php\\php-8.3.26-Win32-vs16-x64\\php.exe',
|
||||
'C:\\php\\php.exe',
|
||||
'D:\\xampp\\php\\php.exe',
|
||||
'C:\\php\\composer.phar',
|
||||
] as $path) {
|
||||
$this->assertTrue(isInstallerExecutablePath($path), "Windows 경로 허용: {$path}");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_windows_path_with_space_known_limitation(): void
|
||||
{
|
||||
// 'C:\\Program Files\\...' 같은 공백 포함 Windows 경로는 본 회복 범위 외.
|
||||
// 공백 분리 입력(PHP + Composer 합성) 형식 휴리스틱과 충돌 — escapeshellarg 단일 토큰
|
||||
// wrap 만으로는 공백 의도(토큰 구분 vs 디렉토리명) 를 자동 구분할 수 없음.
|
||||
// 회피: 8.3 short path 형식(C:\\PROGRA~1\\...) 사용 또는 공백 없는 경로 사용.
|
||||
$this->assertFalse(isInstallerExecutablePath('C:\\Program Files\\PHP\\php.exe'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// open_basedir 회귀 회복 — stat 의존 가드 완화
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* stat 가드가 제거되어 시놀로지 DSM 등 open_basedir 환경에서도
|
||||
* 정상 절대경로 입력이 통과해야 함. 실제 실행 가능 여부는 exec 결과로 판정.
|
||||
*/
|
||||
public function test_isInstallerExecutablePath_accepts_safe_absolute_path_without_stat(): void
|
||||
{
|
||||
// 실제로 존재하지 않는 경로지만 메타문자 없음 — stat 가드 제거로 true
|
||||
$this->assertTrue(isInstallerExecutablePath('/usr/local/bin/php83'));
|
||||
$this->assertTrue(isInstallerExecutablePath('/opt/plesk/php/8.3/bin/php'));
|
||||
$this->assertTrue(isInstallerExecutablePath('/nonexistent/path/to/binary'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Composer 공백 분리 입력 안전 복원 — 멀티 PHP 환경 호환성
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_accepts_php_composer_space_separated_input(): void
|
||||
{
|
||||
// 시놀로지/cPanel/Plesk 멀티 PHP 환경의 운영 패턴
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
// 두 토큰 각각 escapeshellarg 적용 후 공백으로 합성
|
||||
$expected = escapeshellarg('/usr/local/bin/php83') . ' ' . escapeshellarg('/usr/local/bin/composer');
|
||||
$this->assertSame($expected, $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_space_separated_with_metachar_in_first_token(): void
|
||||
{
|
||||
// 첫 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php$(id) /usr/local/bin/composer']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_space_separated_with_metachar_in_second_token(): void
|
||||
{
|
||||
// 두 번째 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer;id']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_three_or_more_tokens(): void
|
||||
{
|
||||
// 3 토큰 이상은 두 번째 토큰에 공백이 남음 → 두 번째 토큰의 메타문자(공백) 로 거부
|
||||
$this->writeState(['composer_binary' => '/bin/php /bin/composer extra_arg']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_shows_human_friendly_space_separated_form(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
|
||||
$display = getComposerCommandForDisplay();
|
||||
|
||||
// 사람에게 보이는 표기는 escape 없는 원본 형식 유지
|
||||
$this->assertSame('/usr/local/bin/php83 /usr/local/bin/composer', $display);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload_in_space_separated(): void
|
||||
{
|
||||
// 두 토큰 중 하나라도 메타문자 포함이면 display 도 composer 폴백
|
||||
$this->writeState(['composer_binary' => '/bin/php `id`']);
|
||||
|
||||
$display = getComposerCommandForDisplay();
|
||||
|
||||
$this->assertSame('composer', $display);
|
||||
$this->assertStringNotContainsString('`', $display);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// validatePhpPath / validateComposerPath stat 가드 완화 (인스톨러 검증 API)
|
||||
// ========================================================================
|
||||
|
||||
public function test_validatePhpPath_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
foreach ([
|
||||
'/usr/local/bin/php; id',
|
||||
'/usr/local/bin/php$(id)',
|
||||
'`/usr/local/bin/php`',
|
||||
'/usr/local/bin/php|nc evil',
|
||||
"/usr/local/bin/php\nrm -rf /",
|
||||
] as $payload) {
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', [$payload]);
|
||||
$this->assertFalse($result['valid'], "메타문자 거부: {$payload}");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_rejects_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', ['']);
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_safe_path_reaches_exec_phase(): void
|
||||
{
|
||||
// 메타문자 없는 절대경로는 stat 가드 없이 exec 단계까지 도달.
|
||||
// 존재하지 않으면 exec 실패 (return code != 0) 로 거부 — 단, 거부 메시지는
|
||||
// 'error_php_exec_failed' 로 stat 거부와 동일. 핵심: stat 가드가 사라졌다는 점.
|
||||
$api = new ValidationApi();
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', ['/nonexistent/path/to/php']);
|
||||
|
||||
// 실제 실행 실패로 invalid 이지만, 그 판정이 exec 결과에 기반함을 의미적으로 검증.
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_validateComposerPath_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
foreach ([
|
||||
'/usr/local/bin/composer; id',
|
||||
'/usr/local/bin/composer$(id)',
|
||||
'`/usr/local/bin/composer`',
|
||||
"/usr/local/bin/composer\nrm",
|
||||
] as $payload) {
|
||||
$result = $this->invokePrivate($api, 'validateComposerPath', [$payload]);
|
||||
$this->assertFalse($result['valid'], "메타문자 거부: {$payload}");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validateComposerPath_rejects_space_separated_with_metachar(): void
|
||||
{
|
||||
// 공백 분리 입력의 토큰별 메타문자 검증
|
||||
$api = new ValidationApi();
|
||||
foreach ([
|
||||
'/bin/php$(id) /bin/composer',
|
||||
'/bin/php /bin/composer;id',
|
||||
'/bin/php `id`',
|
||||
'/bin/php /bin/composer extra_token',
|
||||
] as $payload) {
|
||||
$result = $this->invokePrivate($api, 'validateComposerPath', [$payload]);
|
||||
$this->assertFalse($result['valid'], "공백 분리 + 메타문자 거부: {$payload}");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_splitPhpComposerTokens_helper_splits_into_two_tokens(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$result = $this->invokePrivate($api, 'splitPhpComposerTokens', ['/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
$this->assertSame(['php' => '/usr/local/bin/php83', 'composer' => '/usr/local/bin/composer'], $result);
|
||||
}
|
||||
|
||||
public function test_splitPhpComposerTokens_helper_returns_null_for_single_token(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$result = $this->invokePrivate($api, 'splitPhpComposerTokens', ['/usr/local/bin/composer']);
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_accepts_safe_paths(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
|
||||
foreach ([
|
||||
'/usr/local/bin/php83',
|
||||
'/opt/php/bin/php',
|
||||
'C:/php/php.exe',
|
||||
'/nonexistent/path',
|
||||
// Windows 절대경로 (백슬래시 포함) — 회귀 가드: PO 환경 (Windows 빌트인 서버)
|
||||
'C:\\laragon\\bin\\php\\php-8.3.26-Win32-vs16-x64\\php.exe',
|
||||
'C:\\php\\php.exe',
|
||||
'D:\\xampp\\php\\php.exe',
|
||||
] as $safe) {
|
||||
$this->assertTrue($this->invokePrivate($api, 'isInstallerSafePathArg', [$safe]), "허용: {$safe}");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_rejects_metachars_and_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', ['']));
|
||||
// 백슬래시는 Windows 경로 구분자이므로 차단 대상이 아님 — 셸 인젝션 차단은 escapeshellarg 가 담당
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", "a\0b", "a\x01b", "a\rb"] as $bad) {
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', [$bad]), "메타문자 거부: " . bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 워커 정합 — 검증 통과한 입력이 워커에서도 silent fallback 없이 전달
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_passes_through_single_absolute_path_without_silent_fallback(): void
|
||||
{
|
||||
// 검증 단계에서 통과한 단일 절대경로가 워커에서도 그대로 사용됨을 보장.
|
||||
// stat 가드 제거 후 회귀 — 정상 입력이 silent fallback 으로 사라지지 않음.
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/composer']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertNotSame('composer', $cmd, '검증 통과한 입력은 silent fallback 안 됨');
|
||||
$this->assertSame(escapeshellarg('/usr/local/bin/composer'), $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// High-2 — checkCorePendingPath traversal 차단
|
||||
// ========================================================================
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 세션 쿠키 round-trip 진단 endpoint 회귀 테스트
|
||||
*
|
||||
* 브라우저가 PHPSESSID 쿠키를 보내지 않아 인스톨러가 Step 0 무한 루프에 빠지는
|
||||
* 케이스를 사전 감지하기 위한 endpoint. set 으로 세션에 nonce 저장 후 verify 로
|
||||
* 같은 세션에서 nonce 가 복원되는지 확인.
|
||||
*/
|
||||
class SessionProbeTest extends TestCase
|
||||
{
|
||||
private static bool $loaded = false;
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
if (self::$loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
|
||||
$projectRoot = dirname(__DIR__, 3);
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', sys_get_temp_dir() . '/g7-session-probe-test-' . bin2hex(random_bytes(4)) . '.json');
|
||||
}
|
||||
if (! defined('SESSION_PROBE_LIBRARY')) {
|
||||
define('SESSION_PROBE_LIBRARY', true);
|
||||
}
|
||||
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
require_once $projectRoot . '/public/install/api/session-probe.php';
|
||||
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// 각 테스트 시작 시 세션 상태 초기화
|
||||
$_SESSION = [];
|
||||
}
|
||||
|
||||
public function test_set_action_generates_nonce_and_stores_in_session(): void
|
||||
{
|
||||
$result = sessionProbeSet();
|
||||
|
||||
$this->assertArrayHasKey('action', $result);
|
||||
$this->assertSame('set', $result['action']);
|
||||
$this->assertArrayHasKey('nonce', $result);
|
||||
$this->assertIsString($result['nonce']);
|
||||
// 32 hex chars (random_bytes(16))
|
||||
$this->assertSame(32, strlen($result['nonce']));
|
||||
$this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', $result['nonce']);
|
||||
|
||||
// 세션에 저장 확인
|
||||
$this->assertArrayHasKey('_installer_session_probe', $_SESSION);
|
||||
$this->assertSame($result['nonce'], $_SESSION['_installer_session_probe']);
|
||||
}
|
||||
|
||||
public function test_verify_action_matches_when_session_preserved(): void
|
||||
{
|
||||
$setResult = sessionProbeSet();
|
||||
$verifyResult = sessionProbeVerify();
|
||||
|
||||
$this->assertSame('verify', $verifyResult['action']);
|
||||
$this->assertTrue($verifyResult['matched']);
|
||||
$this->assertSame($setResult['nonce'], $verifyResult['nonce'] ?? null);
|
||||
}
|
||||
|
||||
public function test_verify_action_returns_unmatched_when_session_empty(): void
|
||||
{
|
||||
// set 호출 없이 verify — 세션 쿠키가 round-trip 되지 않은 시뮬레이션
|
||||
$verifyResult = sessionProbeVerify();
|
||||
|
||||
$this->assertSame('verify', $verifyResult['action']);
|
||||
$this->assertFalse($verifyResult['matched']);
|
||||
}
|
||||
|
||||
public function test_set_generates_distinct_nonces_on_repeated_calls(): void
|
||||
{
|
||||
$first = sessionProbeSet();
|
||||
$second = sessionProbeSet();
|
||||
|
||||
// 매 호출마다 새 nonce — 이전 호출의 nonce 가 캐시되지 않음
|
||||
$this->assertNotSame($first['nonce'], $second['nonce']);
|
||||
|
||||
// 세션에는 마지막 set 의 nonce 만 남음
|
||||
$this->assertSame($second['nonce'], $_SESSION['_installer_session_probe']);
|
||||
}
|
||||
|
||||
public function test_verify_action_consumes_nonce(): void
|
||||
{
|
||||
sessionProbeSet();
|
||||
sessionProbeVerify();
|
||||
|
||||
// 한 번 verify 한 nonce 는 재사용 방지를 위해 세션에서 제거되어야 함
|
||||
$this->assertArrayNotHasKey('_installer_session_probe', $_SESSION);
|
||||
|
||||
// 다음 verify 는 세션 빔 케이스와 동일하게 unmatched
|
||||
$secondVerify = sessionProbeVerify();
|
||||
$this->assertFalse($secondVerify['matched']);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user