fix(security): 예약 작업·언어팩·인스톨러의 차단목록을 허용목록으로 전환
KISA 신고포상제 접수 3건(KVE-2026-1677/1678/1679)의 공통 원인은 하나다 — "위험한 것을 골라 막았고, 목록 밖으로 우회됐다". 세 지점 모두 판정을 뒤집는다. 예약 작업 Artisan (KVE-2026-1679) 차단 9개 / 허용 229개였던 구조를 허용목록으로 바꾸고 명령마다 허용 옵션을 선언한다. 검증 과정에서 보고서보다 짧은 경로를 추가로 발견했다 — 검증기는 preg_split 의 첫 토큰을 명령명으로 봤지만 실행부는 문자열째 넘겼고, parameters 가 비면 Laravel 이 StringInput 으로 재파싱한다. 따옴표 한 쌍이면 차단목록의 tinker 가 그대로 실행됐다 (마커 파일로 확인). 파서를 엄격 형태 하나로 고정하고 실행은 (명령명, 인자배열)로 넘겨 재해석 지점 자체를 없앴다. 언어팩 (KVE-2026-1678) 위험 함수 11개를 정규식으로 나열하던 검사를 토큰 상태기계로 교체해 "번역 배열만" 통과시킨다. 목록에 없는 함수도, 함수 이름을 아예 쓰지 않는 형태도 원리적으로 막힌다. 파일 형식·PHP 위치·심볼릭 링크도 화이트리스트로 뒤집었다. 활성 승격이 require 배선의 필수 조건이므로 설치와 활성화의 권한 경계를 네 설치 경로 전부에 같은 강도로 건다 — 경로별 면제는 곧 우회로가 되기 때문이다. 화면은 운영자의 활성화 권한을 보고 auto_activate 를 실을지 결정하므로 재설치 흐름은 그대로 동작한다. 인스톨러 (KVE-2026-1677) 실행 바이너리 자리에 인자가 들어가는 것을 형태 규칙으로 차단한다. escapeshellarg 는 "하나의 인자" 임만 보장할 뿐 그 인자가 실행 파일인지 스크립트인지는 보장하지 않는다. 판정을 의존성 0 공용 정책으로 모아 진단 API·설치 워커·저장 시점이 같은 규칙을 쓴다. stat 은 호출하지 않는다 — 접근이 제한된 서버에서 정상 경로가 거부되던 회귀를 재발시키지 않기 위함이다. 검증: 백엔드 392건 + 프론트 7건 green(skip 1, symlink 미지원 환경). PoC 마커로 red 를 먼저 확보하고, 수정 후 stash 역회귀로 다시 red 가 되는 것까지 확인했다.
This commit is contained in:
1 parent
30867e0e0b
commit
4b6adf4788
45 files changed
+4382
-301
No files matched your search
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 실행 바이너리 경로 정책 테스트 (KVE-2026-1677).
|
||||
*
|
||||
* 정책 파일은 의존성이 없어야 한다 — 인스톨러 API(라이브러리 모드)와 설치 워커 양쪽에서
|
||||
* 단독으로 `require_once` 되므로, 이 테스트도 BASE_PATH·lang 스텁 없이 파일만 로드한다.
|
||||
* 로드에 다른 것이 필요해지면 이 테스트가 먼저 깨진다.
|
||||
*
|
||||
* 판정 축:
|
||||
* - 인자 자리 차단 (하이픈 선두 · 인터프리터+임의 스크립트)
|
||||
* - 자리별 비대칭 (PHP 자리는 이름 무제한 / Composer 자리는 이름 형태 제한)
|
||||
* - stat 미사용 (존재하지 않는 절대경로도 형태만 맞으면 통과 — open_basedir 회귀 가드)
|
||||
*/
|
||||
class BinaryPathPolicyTest extends TestCase
|
||||
{
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
require_once dirname(__DIR__, 3).'/public/install/includes/binary-path-policy.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙을 통과해야 하는 토큰.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param string $reason 통과 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('shapeAllowedProvider')]
|
||||
public function it_accepts_tokens_with_a_valid_shape(string $token, string $reason): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"통과해야 하는 경로가 거부됨 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙에 걸려야 하는 토큰.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param string $reason 거부 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects leading_hyphen_token_is_rejected
|
||||
* @effects php_slot_rejects_leading_hyphen
|
||||
* @effects relative_and_traversal_paths_are_rejected
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('shapeRejectedProvider')]
|
||||
public function it_rejects_tokens_with_an_invalid_shape(string $token, string $reason): void
|
||||
{
|
||||
$this->assertFalse(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"거부해야 하는 경로가 통과함 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리는 이름 형태까지 제한한다.
|
||||
*
|
||||
* @param string $token 경로 토큰
|
||||
* @param bool $expected 기대 판정
|
||||
* @param string $reason 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=interpreter_plus_script, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects getComposerCommand_rejects_interpreter_plus_arbitrary_script
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('composerSlotProvider')]
|
||||
public function it_restricts_the_composer_slot_by_name(string $token, bool $expected, string $reason): void
|
||||
{
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
installer_is_composer_binary_path($token),
|
||||
"Composer 자리 판정이 기대와 다름 ({$reason}): {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리는 이름을 제한하지 않는다.
|
||||
*
|
||||
* 래퍼 스크립트·버전이 붙은 이름·커스텀 이름을 모두 허용해야 한다. 이 자리는
|
||||
* 인자가 `--version` 으로 고정된 실행 파일 자리라 이름 제한이 이번 공격과 무관하고,
|
||||
* 제한하면 설치 환경 다양성을 해친다.
|
||||
*
|
||||
* @param string $token PHP 실행 경로
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=wrapper_script_name, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('phpSlotNameProvider')]
|
||||
public function it_does_not_restrict_the_php_slot_by_name(string $token): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
installer_binary_path_shape_ok($token),
|
||||
"PHP 자리 이름 제한이 생겨 정상 환경이 거부됨: {$token}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 2토큰 입력은 자리별 규칙을 모두 만족할 때만 해석된다.
|
||||
*
|
||||
* @param string $raw 원본 입력
|
||||
* @param array{php: string, composer: string}|null $expected 기대 해석 결과
|
||||
* @param string $reason 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects argument_injection_never_reaches_exec
|
||||
* @effects getComposerCommand_keeps_multi_php_pair_support
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('pairProvider')]
|
||||
public function it_resolves_only_well_formed_php_composer_pairs(string $raw, ?array $expected, string $reason): void
|
||||
{
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
installer_resolve_php_composer_pair($raw),
|
||||
"2토큰 해석이 기대와 다름 ({$reason}): {$raw}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 시스템 stat 에 의존하지 않는다 (open_basedir 회귀 가드).
|
||||
*
|
||||
* `#361` 은 `is_file()`/`is_executable()` 가드가 시놀로지 DSM 등에서 정상 절대경로를
|
||||
* false negative 로 거부하는 회귀를 되돌린 이력이다. 존재하지 않는 절대경로가
|
||||
* 형태 검사만으로 통과해야 그 회귀가 구조적으로 재발하지 않는다.
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects getPhpBinary_passes_through_legitimate_paths
|
||||
*/
|
||||
#[Test]
|
||||
public function it_does_not_depend_on_filesystem_stat(): void
|
||||
{
|
||||
$missing = '/usr/local/php99/bin/php';
|
||||
|
||||
$this->assertFileDoesNotExist($missing);
|
||||
$this->assertTrue(installer_binary_path_shape_ok($missing));
|
||||
$this->assertTrue(installer_is_composer_binary_path('/usr/local/php99/bin/composer'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 통과해야 하는 토큰 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function shapeAllowedProvider(): array
|
||||
{
|
||||
return [
|
||||
'bare php' => ['php', '시스템 기본'],
|
||||
'bare composer' => ['composer', '시스템 기본'],
|
||||
'POSIX 절대경로' => ['/usr/bin/php', '일반 설치'],
|
||||
'버전 붙은 이름' => ['/usr/bin/php8.3', '멀티 PHP'],
|
||||
'Plesk 경로' => ['/opt/plesk/php/8.2/bin/php', '패널 환경'],
|
||||
'Windows 드라이브' => ['C:\\php\\php.exe', 'Windows'],
|
||||
'Windows 슬래시' => ['C:/php/php.exe', 'Windows 정방향 슬래시'],
|
||||
'UNC 경로' => ['\\\\server\\share\\php.exe', '네트워크 공유'],
|
||||
'점 포함 디렉토리' => ['/usr/local/php.d/bin/php', '단일 점은 상위 참조가 아님'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 거부해야 하는 토큰 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function shapeRejectedProvider(): array
|
||||
{
|
||||
return [
|
||||
'빈 문자열' => ['', '입력 없음'],
|
||||
'하이픈 선두 (-r)' => ['-rphpinfo();', '코드 실행 플래그 — 이번 취약점'],
|
||||
'하이픈 선두 (-d)' => ['-dauto_prepend_file=/tmp/x', 'ini 주입'],
|
||||
'롱옵션' => ['--define=x', '옵션'],
|
||||
'상대경로' => ['bin/composer', 'CWD 의존'],
|
||||
'단순 이름' => ['evilbinary', 'bare 허용은 php/composer 뿐'],
|
||||
'부모 참조' => ['/usr/local/../../tmp/composer', '.. 세그먼트'],
|
||||
'부모 참조 (윈도우 구분자)' => ['C:\\php\\..\\..\\tmp\\evil.exe', '.. 세그먼트'],
|
||||
'해시 주석' => ['/usr/bin/php#.phar', '접미사 위장'],
|
||||
'공백 포함' => ['/usr/bin/my php', '토큰 분리 불가'],
|
||||
'세미콜론' => ['/usr/bin/php;id', '셸 메타문자'],
|
||||
'백틱' => ['/usr/bin/`id`', '셸 메타문자'],
|
||||
'달러 괄호' => ['/usr/bin/$(id)', '셸 메타문자'],
|
||||
'따옴표' => ['/usr/bin/"php"', '셸 메타문자'],
|
||||
'개행' => ["/usr/bin/php\nid", '제어문자'],
|
||||
'NUL 바이트' => ["/usr/bin/php\x00", '제어문자'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리 판정 목록.
|
||||
*
|
||||
* @return array<string, array{string, bool, string}>
|
||||
*/
|
||||
public static function composerSlotProvider(): array
|
||||
{
|
||||
return [
|
||||
'composer' => ['composer', true, 'bare 기본'],
|
||||
'절대경로 composer' => ['/usr/local/bin/composer', true, '일반 설치'],
|
||||
'composer2' => ['/usr/local/bin/composer2', true, '버전 붙은 이름'],
|
||||
'composer.phar' => ['/opt/composer.phar', true, 'phar 아카이브'],
|
||||
'임의 이름 phar' => ['/opt/tools/mytool.phar', true, 'phar 는 이름 무관 허용'],
|
||||
'composer.bat' => ['C:\\laragon\\bin\\composer\\composer.bat', true, 'Windows 배치'],
|
||||
'composer.exe' => ['C:\\tools\\composer.exe', true, 'Windows 실행 파일'],
|
||||
'임의 스크립트' => ['/tmp/evil.py', false, '인터프리터가 실행할 임의 스크립트 — 이번 취약점'],
|
||||
'임의 PHP 스크립트' => ['/tmp/evil.php', false, '임의 PHP 스크립트'],
|
||||
'셸 스크립트' => ['/tmp/evil.sh', false, '임의 스크립트'],
|
||||
'composer 접두 위장' => ['/tmp/composer-evil.sh', false, 'basename 완전 일치가 아님'],
|
||||
'하이픈 선두' => ['-rphpinfo();', false, '옵션'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리에 허용되어야 하는 이름 목록.
|
||||
*
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function phpSlotNameProvider(): array
|
||||
{
|
||||
return [
|
||||
'래퍼 스크립트' => ['/usr/local/bin/php-8.2-wrapper.sh'],
|
||||
'커스텀 이름' => ['/opt/mycompany/run-php'],
|
||||
'버전 접미사' => ['/usr/bin/php8.3'],
|
||||
'DSM 경로' => ['/usr/local/php84/bin/php'],
|
||||
'Windows exe' => ['C:\\php\\php.exe'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 2토큰 해석 목록.
|
||||
*
|
||||
* @return array<string, array{string, array{php: string, composer: string}|null, string}>
|
||||
*/
|
||||
public static function pairProvider(): array
|
||||
{
|
||||
return [
|
||||
'멀티 PHP 정상' => [
|
||||
'/usr/local/php84/bin/php /usr/local/bin/composer.phar',
|
||||
['php' => '/usr/local/php84/bin/php', 'composer' => '/usr/local/bin/composer.phar'],
|
||||
'운영 패턴',
|
||||
],
|
||||
'래퍼 + composer' => [
|
||||
'/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer',
|
||||
['php' => '/usr/local/bin/php-8.2-wrapper.sh', 'composer' => '/usr/local/bin/composer'],
|
||||
'PHP 자리 이름 무제한',
|
||||
],
|
||||
'Windows 2토큰' => [
|
||||
'C:\\php\\php.exe D:\\composer\\composer.phar',
|
||||
['php' => 'C:\\php\\php.exe', 'composer' => 'D:\\composer\\composer.phar'],
|
||||
'Windows',
|
||||
],
|
||||
'인자 주입 (-r)' => ['/usr/bin/php -rphpinfo();', null, '둘째 토큰이 코드 실행 플래그'],
|
||||
'인터프리터 + 스크립트' => ['/usr/bin/python3 /tmp/evil.py', null, '둘째 토큰이 임의 스크립트'],
|
||||
'PHP 자리 옵션' => ['-rphpinfo(); /usr/bin/composer', null, '첫 토큰이 옵션'],
|
||||
'공백 없음' => ['/usr/bin/composer', null, '2토큰 입력이 아님'],
|
||||
'공백 포함 디렉토리' => [
|
||||
'C:\\Program Files\\PHP\\php.exe C:\\composer\\composer.phar',
|
||||
null,
|
||||
'#361 이 명시한 기존 known_limitation — 악화가 아님',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionClass;
|
||||
use ValidationApi;
|
||||
@@ -30,7 +31,7 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
// ValidationApi 는 글로벌 네임스페이스이므로 \lang() 으로 조회됨 →
|
||||
// 글로벌 스코프에 정의된 스텁이 필요.
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
@@ -48,14 +49,14 @@ class ComposerPathValidationTest extends TestCase
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
|
||||
define('STATE_PATH', BASE_PATH.'/storage/installer-state.json');
|
||||
}
|
||||
|
||||
require_once $projectRoot . '/public/install/api/check-configuration.php';
|
||||
require_once $projectRoot.'/public/install/api/check-configuration.php';
|
||||
// applyInstallerComposerEnvVars() 는 functions.php 에 정의. stat 가드 완화 회복
|
||||
// 이후 시스템 기본 'composer' 또는 정상 절대경로 입력이 exec 단계까지 도달하면서
|
||||
// 이 함수를 호출하므로 사전 로드 필요.
|
||||
require_once $projectRoot . '/public/install/includes/functions.php';
|
||||
require_once $projectRoot.'/public/install/includes/functions.php';
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ class ComposerPathValidationTest extends TestCase
|
||||
*/
|
||||
private function invoke(string $method, array $args): array
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$ref = new ReflectionClass($api);
|
||||
$m = $ref->getMethod($method);
|
||||
|
||||
@@ -74,8 +75,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_composer_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
@@ -86,8 +87,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_composer_path_with_semicolon_injection_is_rejected(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = '/bin/sh; touch ' . $marker;
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = '/bin/sh; touch '.$marker;
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
@@ -112,14 +113,14 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_phar_path_with_invalid_php_path_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
|
||||
$tmpPhar = tempnam(sys_get_temp_dir(), 'g7-fake-composer-') . '.phar';
|
||||
$tmpPhar = tempnam(sys_get_temp_dir(), 'g7-fake-composer-').'.phar';
|
||||
file_put_contents($tmpPhar, '');
|
||||
chmod($tmpPhar, 0755);
|
||||
|
||||
try {
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
$result = $this->invoke('validateComposerPath', [$tmpPhar, $payload]);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
@@ -131,8 +132,8 @@ class ComposerPathValidationTest extends TestCase
|
||||
|
||||
public function test_php_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$marker = sys_get_temp_dir().'/g7_kve_test_'.bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > '.$marker.'"';
|
||||
|
||||
$result = $this->invoke('validatePhpPath', [$payload]);
|
||||
|
||||
@@ -161,4 +162,171 @@ class ComposerPathValidationTest extends TestCase
|
||||
// shell injection 메시지 패턴이 들어가지 않는지 확인.
|
||||
$this->assertIsString($result['message']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 인자 주입 (KVE-2026-1677)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 둘째 토큰이 임의 스크립트면 exec 에 도달하지 않는다.
|
||||
*
|
||||
* KVE-2026-1677 의 실제 실행 경로다. escapeshellarg 는 "이 문자열이 하나의 인자" 임만
|
||||
* 보장할 뿐, 그 인자가 실행 파일인지 인터프리터가 실행할 스크립트인지는 보장하지 않는다.
|
||||
* 기존 문자 블랙리스트는 `-` `(` `)` `.` `/` 를 모두 허용해 인자 자리를 열어 두었다.
|
||||
*
|
||||
* 실측 근거: 명령 끝에 붙는 ` --version` 은 스크립트 인자로 넘어갈 뿐이라
|
||||
* `php <스크립트> --version` 은 그 스크립트를 그대로 실행한다. 실행되면 마커가
|
||||
* 만들어지므로 마커 부재가 곧 미도달의 증거다.
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=interpreter_plus_script
|
||||
*
|
||||
* @effects argument_injection_never_reaches_exec
|
||||
*/
|
||||
public function test_interpreter_with_arbitrary_script_never_reaches_exec(): void
|
||||
{
|
||||
$marker = $this->argumentInjectionMarkerPath();
|
||||
@unlink($marker);
|
||||
|
||||
// 실행 파일 자리에는 이 환경에 실제로 존재하는 PHP 를 쓴다 — 검증을 통과하면
|
||||
// 실제로 실행되므로 "환경에 없어서 실패" 로 초록이 되는 가짜 통과를 배제한다.
|
||||
$script = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7i527_evil.php';
|
||||
file_put_contents(
|
||||
$script,
|
||||
'<?php file_put_contents('.var_export($marker, true).", '1');"
|
||||
);
|
||||
|
||||
try {
|
||||
$result = $this->invoke('validateComposerPath', [PHP_BINARY.' '.$script, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], '인자 자리에 임의 스크립트를 넣은 입력이 유효로 판정됨');
|
||||
$this->assertFileDoesNotExist($marker, '페이로드가 exec 에 도달해 임의 스크립트가 실행됨');
|
||||
} finally {
|
||||
@unlink($marker);
|
||||
@unlink($script);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 둘째 토큰이 코드 실행 플래그면 형태 검사에서 거부된다.
|
||||
*
|
||||
* 이 호출 지점은 명령 끝에 ` --version` 을 붙이는데, PHP CLI 는 `--version` 을 만나면
|
||||
* 버전만 출력하고 종료하므로 `-r` 코드가 실행되지 않는다(실측 확인). 즉 여기서는
|
||||
* 실행까지 가지 않지만, ` --version` 을 붙이지 않는 호출 지점(설치 워커의 실제 명령
|
||||
* 실행)에서는 그대로 실행된다. 따라서 자리 자체를 닫아 두 지점을 같은 규칙으로 막는다.
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects leading_hyphen_token_is_rejected
|
||||
*/
|
||||
public function test_leading_hyphen_token_is_rejected_in_the_argument_slot(): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [PHP_BINARY.' -rphpinfo();', 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], '하이픈 선두 인자가 유효로 판정됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리(첫 토큰·단일 토큰)에도 하이픈 선두 토큰은 올 수 없다.
|
||||
*
|
||||
* @scenario vector=validatePhpPath, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects php_slot_rejects_leading_hyphen
|
||||
*/
|
||||
public function test_php_path_rejects_leading_hyphen_token(): void
|
||||
{
|
||||
$result = $this->invoke('validatePhpPath', ['-rphpinfo();']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상대경로·`..` 세그먼트는 거부된다 (CWD 의존 실행 차단).
|
||||
*
|
||||
* @param string $payload 거부되어야 하는 경로
|
||||
* @param string $reason 거부 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=relative_path
|
||||
*
|
||||
* @effects relative_and_traversal_paths_are_rejected
|
||||
*/
|
||||
#[DataProvider('rejectedShapeProvider')]
|
||||
public function test_rejects_paths_outside_the_allowed_shape(string $payload, string $reason): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], "거부되어야 하는 입력이 통과함 ({$reason}): {$payload}");
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 입력은 계속 통과한다 (stat 미사용 — open_basedir 환경 회귀 가드).
|
||||
*
|
||||
* 존재하지 않는 절대경로도 사전 거부되지 않고 exec 까지 도달해야 한다. `#361` 이
|
||||
* `is_file()`/`is_executable()` 가드로 시놀로지 DSM 등에서 정상 경로를 false negative
|
||||
* 로 거부한 회귀를 되돌린 이력이 있다.
|
||||
*
|
||||
* @param string $payload 통과해야 하는 경로
|
||||
* @param string $reason 통과 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=validateComposerPath, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects legitimate_paths_still_reach_exec
|
||||
*/
|
||||
#[DataProvider('acceptedShapeProvider')]
|
||||
public function test_legitimate_paths_are_not_rejected_before_exec(string $payload, string $reason): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
// 실행 결과는 환경 의존이므로 "사전 거부 메시지" 가 아닌지로 판정한다.
|
||||
$this->assertStringNotContainsString(
|
||||
'not_allowed',
|
||||
(string) $result['message'],
|
||||
"정상 입력이 형태 검사에서 사전 거부됨 ({$reason}): {$payload}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙에 걸려야 하는 입력 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function rejectedShapeProvider(): array
|
||||
{
|
||||
return [
|
||||
'상대경로' => ['bin/composer', 'bare 명령이 아닌 상대경로'],
|
||||
'부모 참조' => ['/usr/local/../../tmp/composer', '.. 세그먼트'],
|
||||
'해시 주석 위장' => ['-rphpinfo()#.phar', '# + 하이픈 선두'],
|
||||
'인터프리터 + 스크립트' => ['/usr/bin/python3 /tmp/evil.py', 'Composer 자리 형태 위반'],
|
||||
'Composer 자리 임의 이름' => ['/usr/bin/php /tmp/evil.sh', 'composer 계열도 .phar 도 아님'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 형태 규칙을 통과해야 하는 정상 입력 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function acceptedShapeProvider(): array
|
||||
{
|
||||
return [
|
||||
'bare composer' => ['composer', '시스템 기본'],
|
||||
'절대경로 composer' => ['/usr/local/bin/composer', '일반 설치'],
|
||||
'버전 붙은 이름' => ['/usr/local/bin/composer2', 'composer 계열'],
|
||||
'phar' => ['/opt/composer.phar', 'phar 아카이브'],
|
||||
'Windows bat' => ['C:\\laragon\\bin\\composer\\composer.bat', 'Windows 배치'],
|
||||
'존재하지 않는 절대경로' => ['/usr/local/php99/bin/composer', 'stat 미사용 회귀 가드'],
|
||||
'2토큰 멀티 PHP' => ['/usr/local/php84/bin/php /usr/local/bin/composer.phar', '멀티 PHP 운영 패턴'],
|
||||
'래퍼 스크립트 PHP' => ['/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer.phar', 'PHP 자리 이름 무제한'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 인자 주입 페이로드가 실행되었을 때 만들어지는 마커 경로.
|
||||
*
|
||||
* 페이로드에는 따옴표를 넣을 수 없어(셸 메타문자 차단) 같은 경로를 `chr()` 연결로
|
||||
* 조립한다. 두 값이 어긋나면 증명이 성립하지 않으므로 여기서 한 번만 정의한다.
|
||||
*/
|
||||
private function argumentInjectionMarkerPath(): string
|
||||
{
|
||||
return sys_get_temp_dir().chr(47).chr(103).chr(55).chr(105).chr(53).chr(50).chr(55);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ use ValidationApi;
|
||||
class InstallerSecurityHardeningTest extends TestCase
|
||||
{
|
||||
private static bool $loaded = false;
|
||||
|
||||
private static string $tempBase = '';
|
||||
|
||||
private static string $skipReason = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
@@ -28,7 +30,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
return;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
@@ -45,11 +47,11 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
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);
|
||||
self::$tempBase = sys_get_temp_dir().'/g7-installer-hardening-'.bin2hex(random_bytes(4));
|
||||
@mkdir(self::$tempBase.'/storage/app', 0755, true);
|
||||
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', self::$tempBase . '/storage/installer-state.json');
|
||||
define('STATE_PATH', self::$tempBase.'/storage/installer-state.json');
|
||||
}
|
||||
|
||||
// 안전 가드: STATE_PATH 는 PHP 상수라 한 프로세스에서 단 한 번만 정의된다.
|
||||
@@ -59,18 +61,18 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||
$resolvedState = realpath(dirname((string) STATE_PATH)) ?: dirname((string) STATE_PATH);
|
||||
if (strpos($resolvedState, $tempPrefix) !== 0) {
|
||||
self::$skipReason = 'STATE_PATH (' . STATE_PATH . ') 가 시스템 temp 하위가 아님 — '
|
||||
. '다른 Installer 테스트의 상수 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
|
||||
. '격리 실행: php vendor/bin/phpunit --filter=InstallerSecurityHardeningTest';
|
||||
self::$skipReason = 'STATE_PATH ('.STATE_PATH.') 가 시스템 temp 하위가 아님 — '
|
||||
.'다른 Installer 테스트의 상수 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
|
||||
.'격리 실행: php vendor/bin/phpunit --filter=InstallerSecurityHardeningTest';
|
||||
self::$loaded = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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';
|
||||
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;
|
||||
}
|
||||
@@ -88,6 +90,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
{
|
||||
$ref = new ReflectionClass($obj);
|
||||
$m = $ref->getMethod($method);
|
||||
|
||||
return $m->invokeArgs($obj, $args);
|
||||
}
|
||||
|
||||
@@ -123,7 +126,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Critical-1 — getComposerCommand 공백 분기 RCE 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_rejects_space_containing_input_falls_back_to_composer(): void
|
||||
public function test_get_composer_command_rejects_space_containing_input_falls_back_to_composer(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'sh -c "id > /tmp/g7_should_not_run"']);
|
||||
|
||||
@@ -133,7 +136,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_shell_metachars_falls_back_to_composer(): void
|
||||
public function test_get_composer_command_rejects_shell_metachars_falls_back_to_composer(): void
|
||||
{
|
||||
foreach ([
|
||||
'/bin/sh; touch /tmp/x',
|
||||
@@ -149,7 +152,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_passes_through_safe_absolute_path(): void
|
||||
public function test_get_composer_command_passes_through_safe_absolute_path(): void
|
||||
{
|
||||
// open_basedir 같은 PHP 런타임 제약 환경의 false negative 를 피하기 위해
|
||||
// stat 의존 가드가 제거됨. 메타문자 없는 단일 절대경로는 escape 후 그대로 사용.
|
||||
@@ -162,7 +165,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_empty_returns_default(): void
|
||||
public function test_get_composer_command_empty_returns_default(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '']);
|
||||
|
||||
@@ -170,7 +173,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload(): void
|
||||
public function test_get_composer_command_for_display_does_not_leak_shell_payload(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'rm -rf /']);
|
||||
|
||||
@@ -181,15 +184,15 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_metachars(): void
|
||||
public function test_is_installer_executable_path_rejects_metachars(): void
|
||||
{
|
||||
// 백슬래시는 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));
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), '메타문자 거부: '.bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_accepts_windows_paths(): void
|
||||
public function test_is_installer_executable_path_accepts_windows_paths(): void
|
||||
{
|
||||
// Windows 절대경로는 백슬래시 포함이지만 공백·메타문자 없으면 통과.
|
||||
// 공백 포함 디렉토리(예: 'C:\\Program Files\\...') 는 공백 분리 입력 형식의 토큰
|
||||
@@ -204,7 +207,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_windows_path_with_space_known_limitation(): void
|
||||
public function test_is_installer_executable_path_rejects_windows_path_with_space_known_limitation(): void
|
||||
{
|
||||
// 'C:\\Program Files\\...' 같은 공백 포함 Windows 경로는 본 회복 범위 외.
|
||||
// 공백 분리 입력(PHP + Composer 합성) 형식 휴리스틱과 충돌 — escapeshellarg 단일 토큰
|
||||
@@ -221,7 +224,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
* stat 가드가 제거되어 시놀로지 DSM 등 open_basedir 환경에서도
|
||||
* 정상 절대경로 입력이 통과해야 함. 실제 실행 가능 여부는 exec 결과로 판정.
|
||||
*/
|
||||
public function test_isInstallerExecutablePath_accepts_safe_absolute_path_without_stat(): void
|
||||
public function test_is_installer_executable_path_accepts_safe_absolute_path_without_stat(): void
|
||||
{
|
||||
// 실제로 존재하지 않는 경로지만 메타문자 없음 — stat 가드 제거로 true
|
||||
$this->assertTrue(isInstallerExecutablePath('/usr/local/bin/php83'));
|
||||
@@ -233,7 +236,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Composer 공백 분리 입력 안전 복원 — 멀티 PHP 환경 호환성
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_accepts_php_composer_space_separated_input(): void
|
||||
public function test_get_composer_command_accepts_php_composer_space_separated_input(): void
|
||||
{
|
||||
// 시놀로지/cPanel/Plesk 멀티 PHP 환경의 운영 패턴
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
@@ -241,12 +244,12 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
// 두 토큰 각각 escapeshellarg 적용 후 공백으로 합성
|
||||
$expected = escapeshellarg('/usr/local/bin/php83') . ' ' . escapeshellarg('/usr/local/bin/composer');
|
||||
$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
|
||||
public function test_get_composer_command_rejects_space_separated_with_metachar_in_first_token(): void
|
||||
{
|
||||
// 첫 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php$(id) /usr/local/bin/composer']);
|
||||
@@ -257,7 +260,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_space_separated_with_metachar_in_second_token(): void
|
||||
public function test_get_composer_command_rejects_space_separated_with_metachar_in_second_token(): void
|
||||
{
|
||||
// 두 번째 토큰에 메타문자 → 거부, composer 폴백
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer;id']);
|
||||
@@ -268,7 +271,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_three_or_more_tokens(): void
|
||||
public function test_get_composer_command_rejects_three_or_more_tokens(): void
|
||||
{
|
||||
// 3 토큰 이상은 두 번째 토큰에 공백이 남음 → 두 번째 토큰의 메타문자(공백) 로 거부
|
||||
$this->writeState(['composer_binary' => '/bin/php /bin/composer extra_arg']);
|
||||
@@ -279,7 +282,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_shows_human_friendly_space_separated_form(): void
|
||||
public function test_get_composer_command_for_display_shows_human_friendly_space_separated_form(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php83 /usr/local/bin/composer']);
|
||||
|
||||
@@ -290,7 +293,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload_in_space_separated(): void
|
||||
public function test_get_composer_command_for_display_does_not_leak_shell_payload_in_space_separated(): void
|
||||
{
|
||||
// 두 토큰 중 하나라도 메타문자 포함이면 display 도 composer 폴백
|
||||
$this->writeState(['composer_binary' => '/bin/php `id`']);
|
||||
@@ -306,9 +309,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// validatePhpPath / validateComposerPath stat 가드 완화 (인스톨러 검증 API)
|
||||
// ========================================================================
|
||||
|
||||
public function test_validatePhpPath_rejects_shell_metachars(): void
|
||||
public function test_validate_php_path_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/usr/local/bin/php; id',
|
||||
'/usr/local/bin/php$(id)',
|
||||
@@ -321,28 +324,28 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_rejects_empty(): void
|
||||
public function test_validate_php_path_rejects_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'validatePhpPath', ['']);
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_validatePhpPath_safe_path_reaches_exec_phase(): void
|
||||
public function test_validate_php_path_safe_path_reaches_exec_phase(): void
|
||||
{
|
||||
// 메타문자 없는 절대경로는 stat 가드 없이 exec 단계까지 도달.
|
||||
// 존재하지 않으면 exec 실패 (return code != 0) 로 거부 — 단, 거부 메시지는
|
||||
// 'error_php_exec_failed' 로 stat 거부와 동일. 핵심: stat 가드가 사라졌다는 점.
|
||||
$api = new ValidationApi();
|
||||
$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
|
||||
public function test_validate_composer_path_rejects_shell_metachars(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/usr/local/bin/composer; id',
|
||||
'/usr/local/bin/composer$(id)',
|
||||
@@ -354,10 +357,10 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_validateComposerPath_rejects_space_separated_with_metachar(): void
|
||||
public function test_validate_composer_path_rejects_space_separated_with_metachar(): void
|
||||
{
|
||||
// 공백 분리 입력의 토큰별 메타문자 검증
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
foreach ([
|
||||
'/bin/php$(id) /bin/composer',
|
||||
'/bin/php /bin/composer;id',
|
||||
@@ -369,23 +372,23 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_splitPhpComposerTokens_helper_splits_into_two_tokens(): void
|
||||
public function test_split_php_composer_tokens_helper_splits_into_two_tokens(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$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
|
||||
public function test_split_php_composer_tokens_helper_returns_null_for_single_token(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$result = $this->invokePrivate($api, 'splitPhpComposerTokens', ['/usr/local/bin/composer']);
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_accepts_safe_paths(): void
|
||||
public function test_is_installer_safe_path_arg_helper_accepts_safe_paths(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
|
||||
foreach ([
|
||||
'/usr/local/bin/php83',
|
||||
@@ -401,14 +404,14 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_isInstallerSafePathArg_helper_rejects_metachars_and_empty(): void
|
||||
public function test_is_installer_safe_path_arg_helper_rejects_metachars_and_empty(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$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));
|
||||
$this->assertFalse($this->invokePrivate($api, 'isInstallerSafePathArg', [$bad]), '메타문자 거부: '.bin2hex($bad));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,7 +419,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// 워커 정합 — 검증 통과한 입력이 워커에서도 silent fallback 없이 전달
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_passes_through_single_absolute_path_without_silent_fallback(): void
|
||||
public function test_get_composer_command_passes_through_single_absolute_path_without_silent_fallback(): void
|
||||
{
|
||||
// 검증 단계에서 통과한 단일 절대경로가 워커에서도 그대로 사용됨을 보장.
|
||||
// stat 가드 제거 후 회귀 — 정상 입력이 silent fallback 으로 사라지지 않음.
|
||||
@@ -433,9 +436,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// High-2 — checkCorePendingPath traversal 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_checkCorePendingPath_rejects_parent_traversal(): void
|
||||
public function test_check_core_pending_path_rejects_parent_traversal(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
|
||||
foreach (['../../../etc', '..', 'foo/../bar', 'foo/..\\bar'] as $bad) {
|
||||
$_GET = ['path' => $bad];
|
||||
@@ -452,9 +455,9 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_rejects_null_byte(): void
|
||||
public function test_check_core_pending_path_rejects_null_byte(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$api = new ValidationApi;
|
||||
$_GET = ['path' => "valid\0../etc"];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
@@ -465,10 +468,10 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_returns_uniform_message_for_nonexistent(): void
|
||||
public function test_check_core_pending_path_returns_uniform_message_for_nonexistent(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$_GET = ['path' => '/nonexistent/g7-test-' . bin2hex(random_bytes(4))];
|
||||
$api = new ValidationApi;
|
||||
$_GET = ['path' => '/nonexistent/g7-test-'.bin2hex(random_bytes(4))];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
$body = ob_get_clean();
|
||||
@@ -484,7 +487,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Medium-1 — escapeEnvValue 개행 제거
|
||||
// ========================================================================
|
||||
|
||||
public function test_escapeEnvValue_strips_newlines(): void
|
||||
public function test_escape_env_value_strips_newlines(): void
|
||||
{
|
||||
$payload = "secret\nINJECTED=true";
|
||||
$result = escapeEnvValue($payload);
|
||||
@@ -499,21 +502,21 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
$this->assertStringEndsWith('"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_strips_crlf(): void
|
||||
public function test_escape_env_value_strips_crlf(): void
|
||||
{
|
||||
$result = escapeEnvValue("a\r\nb");
|
||||
|
||||
$this->assertSame('"ab"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_preserves_normal_password(): void
|
||||
public function test_escape_env_value_preserves_normal_password(): void
|
||||
{
|
||||
$result = escapeEnvValue('p@ssw0rd!#$%');
|
||||
|
||||
$this->assertSame('"p@ssw0rd!#$%"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_escapes_quotes_and_backslashes(): void
|
||||
public function test_escape_env_value_escapes_quotes_and_backslashes(): void
|
||||
{
|
||||
$result = escapeEnvValue('a"b\\c');
|
||||
|
||||
@@ -524,7 +527,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
// Medium-2 — PDO DSN 파라미터 sanitize
|
||||
// ========================================================================
|
||||
|
||||
public function test_getDatabaseConnection_rejects_semicolon_in_host(): void
|
||||
public function test_get_database_connection_rejects_semicolon_in_host(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -537,7 +540,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_equals_in_database(): void
|
||||
public function test_get_database_connection_rejects_equals_in_database(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -550,7 +553,7 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_newline_in_port(): void
|
||||
public function test_get_database_connection_rejects_newline_in_port(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
@@ -562,4 +565,102 @@ class InstallerSecurityHardeningTest extends TestCase
|
||||
'db_write_password' => '',
|
||||
], false);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// KVE-2026-1677 — 설치 워커의 실행 바이너리 경로
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 저장된 php_binary 가 형태 규칙을 위반하면 시스템 기본값으로 폴백한다.
|
||||
*
|
||||
* 이 값은 설치 워커에서 실제 명령의 실행 바이너리가 된다(`--version` 이 붙지 않는
|
||||
* 호출 지점). 이전에는 아무 검증 없이 그대로 반환해, 저장만 되면 인자 자리가 열렸다.
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=argument_injection_dash_r
|
||||
*
|
||||
* @effects getPhpBinary_falls_back_to_default_for_disallowed_shape
|
||||
*/
|
||||
public function test_get_php_binary_falls_back_to_default_for_disallowed_shape(): void
|
||||
{
|
||||
foreach ([
|
||||
'-rphpinfo();' => '코드 실행 플래그',
|
||||
'-dauto_prepend_file=/tmp/x' => 'ini 주입',
|
||||
'bin/php' => '상대경로',
|
||||
'/usr/local/../../tmp/php' => '.. 세그먼트',
|
||||
'/usr/bin/php$(id)' => '셸 메타문자',
|
||||
] as $payload => $reason) {
|
||||
$this->writeState(['php_binary' => $payload]);
|
||||
|
||||
$this->assertSame(
|
||||
'php',
|
||||
getPhpBinary(),
|
||||
"형태 위반 값이 그대로 실행 바이너리가 됨 ({$reason}): {$payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 절대경로는 그대로 사용된다 (stat 미사용 — 존재하지 않아도 통과).
|
||||
*
|
||||
* @scenario vector=getPhpBinary, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects getPhpBinary_passes_through_legitimate_paths
|
||||
*/
|
||||
public function test_get_php_binary_passes_through_legitimate_paths(): void
|
||||
{
|
||||
foreach ([
|
||||
'/usr/local/php84/bin/php',
|
||||
'/usr/local/bin/php-8.2-wrapper.sh',
|
||||
'C:\\php\\php.exe',
|
||||
'/usr/local/php99/bin/php',
|
||||
] as $path) {
|
||||
$this->writeState(['php_binary' => $path]);
|
||||
|
||||
$this->assertSame($path, getPhpBinary(), "정상 경로가 폴백됨: {$path}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리에 인터프리터 + 임의 스크립트를 넣으면 기본값으로 폴백한다.
|
||||
*
|
||||
* 하이픈 선두만 막으면 `PHP경로 /tmp/올려둔파일` 형태가 남는다.
|
||||
*
|
||||
* @scenario vector=getComposerCommand, payload_class=interpreter_plus_script
|
||||
*
|
||||
* @effects getComposerCommand_rejects_interpreter_plus_arbitrary_script
|
||||
*/
|
||||
public function test_get_composer_command_rejects_interpreter_plus_arbitrary_script(): void
|
||||
{
|
||||
foreach ([
|
||||
'/usr/bin/php /tmp/evil.php',
|
||||
'/usr/bin/python3 /tmp/evil.py',
|
||||
'/usr/bin/php -rphpinfo();',
|
||||
'/usr/bin/php /tmp/composer-evil.sh',
|
||||
] as $payload) {
|
||||
$this->writeState(['composer_binary' => $payload]);
|
||||
|
||||
$this->assertSame(
|
||||
'composer',
|
||||
getComposerCommand(),
|
||||
"인자 자리에 임의 스크립트/옵션이 통과함: {$payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 멀티 PHP 입력은 계속 두 토큰으로 실행된다 (비파괴).
|
||||
*
|
||||
* @scenario vector=getComposerCommand, payload_class=wrapper_script_name
|
||||
*
|
||||
* @effects getComposerCommand_keeps_multi_php_pair_support
|
||||
*/
|
||||
public function test_get_composer_command_keeps_multi_php_pair_support(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/usr/local/bin/php-8.2-wrapper.sh /usr/local/bin/composer.phar']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertStringContainsString('php-8.2-wrapper.sh', $cmd);
|
||||
$this->assertStringContainsString('composer.phar', $cmd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Step 3 저장 시점의 바이너리 경로 형태 강제 회귀 테스트 (KVE-2026-1677)
|
||||
*
|
||||
* `php_binary` / `composer_binary` 는 설치 워커에서 실제 명령의 실행 바이너리가 된다.
|
||||
* 실행 시점(task-runner)과 진단 시점(check-configuration)에도 같은 정책이 걸려 있지만,
|
||||
* 형태 위반 값이 애초에 `.env` / 설치 상태 파일에 기록되지 않도록 저장 시점에서도 막는다.
|
||||
* 세 지점 중 하나라도 빠지면 "저장은 되는데 실행만 폴백" 같은 어긋난 상태가 남는다.
|
||||
*
|
||||
* 본 테스트는 저장/리다이렉트 분기에 도달하지 않도록 DB 검증을 일부러 실패시켜
|
||||
* (`db_write_host` 공백) 상태 파일·세션을 건드리지 않는다. 그래서 `STATE_PATH` 를
|
||||
* 정의하지 않으며, 인접 Installer 테스트의 상수 선점과도 무관하다.
|
||||
*
|
||||
* @scenario vector=handleStep3Post, payload_class=argument_injection_dash_r, expected_outcome=return_invalid_message
|
||||
*
|
||||
* @effects step3_post_rejects_disallowed_binary_paths_before_save
|
||||
*/
|
||||
class InstallerStep3BinaryPathStoreGuardTest extends TestCase
|
||||
{
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
require_once __DIR__.'/stubs/lang_stub.php';
|
||||
|
||||
$projectRoot = dirname(__DIR__, 3);
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $projectRoot);
|
||||
}
|
||||
if (! defined('SUPPORTED_LANGUAGES')) {
|
||||
define('SUPPORTED_LANGUAGES', ['ko' => '한국어', 'en' => 'English']);
|
||||
}
|
||||
|
||||
require_once $projectRoot.'/public/install/includes/functions.php';
|
||||
require_once $projectRoot.'/public/install/includes/binary-path-policy.php';
|
||||
require_once $projectRoot.'/public/install/includes/request-handler.php';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$_POST = [];
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 3 POST 를 실행하고 에러 배열을 돌려줍니다.
|
||||
*
|
||||
* @param array<string, string> $post POST 본문 (DB 검증은 일부러 실패시킨다)
|
||||
* @return array<string, string> 에러 배열
|
||||
*/
|
||||
private function runStep3(array $post): array
|
||||
{
|
||||
// 저장/리다이렉트 분기에 도달하지 않도록 DB 검증을 실패시킨다.
|
||||
$_POST = $post + [
|
||||
'db_write_host' => '',
|
||||
'db_write_database' => '',
|
||||
'db_write_username' => '',
|
||||
'admin_email' => 'not-an-email',
|
||||
'admin_language' => 'ko',
|
||||
'admin_password' => '',
|
||||
'admin_password_confirm' => '',
|
||||
];
|
||||
|
||||
$formData = [];
|
||||
$errors = [];
|
||||
handleStep3Post('ko', $formData, $errors);
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP 자리에 코드 실행 플래그를 넣으면 저장 시점에 거부된다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_php_binary_with_code_execution_flag(): void
|
||||
{
|
||||
$errors = $this->runStep3(['php_binary' => '-r file_put_contents("g7","x");']);
|
||||
|
||||
$this->assertArrayHasKey(
|
||||
'php_binary',
|
||||
$errors,
|
||||
'PHP 자리의 선두 하이픈 토큰이 저장 시점에 통과했다 — 형태 위반 값이 설치 상태에 기록된다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리에 셸 메타문자가 있으면 저장 시점에 거부된다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_composer_binary_with_shell_metachars(): void
|
||||
{
|
||||
$errors = $this->runStep3(['composer_binary' => 'sh -c "id > /tmp/g7"']);
|
||||
|
||||
$this->assertArrayHasKey('composer_binary', $errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer 자리의 공백 분리 입력에서 둘째 토큰이 임의 스크립트면 거부된다.
|
||||
*
|
||||
* `escapeshellarg` 는 "하나의 인자" 임만 보장하므로, 인터프리터 + 임의 스크립트
|
||||
* 조합은 그 스크립트를 그대로 실행한다. 이 자리를 저장 시점에서도 닫는다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_step3_rejects_interpreter_plus_arbitrary_script_pair(): void
|
||||
{
|
||||
$errors = $this->runStep3(['composer_binary' => '/usr/bin/php /tmp/evil.php']);
|
||||
|
||||
$this->assertArrayHasKey(
|
||||
'composer_binary',
|
||||
$errors,
|
||||
'Composer 자리의 둘째 토큰이 임의 스크립트인데 저장 시점에 통과했다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 입력은 저장 시점 검증을 통과한다 (비파괴 확인).
|
||||
*
|
||||
* @param array<string, string> $post POST 본문
|
||||
* @param string $field 통과해야 하는 필드
|
||||
*
|
||||
* @scenario vector=handleStep3Post, payload_class=normal, expected_outcome=accept_normal
|
||||
*
|
||||
* @effects step3_post_accepts_legitimate_binary_paths
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
#[DataProvider('legitimateBinaryInputProvider')]
|
||||
public function test_step3_accepts_legitimate_binary_paths(array $post, string $field): void
|
||||
{
|
||||
$errors = $this->runStep3($post);
|
||||
|
||||
$this->assertArrayNotHasKey(
|
||||
$field,
|
||||
$errors,
|
||||
'정상 경로가 저장 시점에 거부됐다 — 설치가 불가능해진다: '.json_encode($post)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장 시점 검증을 통과해야 하는 정상 입력 목록.
|
||||
*
|
||||
* @return array<string, array{array<string, string>, string}>
|
||||
*/
|
||||
public static function legitimateBinaryInputProvider(): array
|
||||
{
|
||||
return [
|
||||
'PHP 미입력' => [[], 'php_binary'],
|
||||
'PHP 기본값' => [['php_binary' => 'php'], 'php_binary'],
|
||||
'PHP 절대경로' => [['php_binary' => '/usr/bin/php8.2'], 'php_binary'],
|
||||
'PHP Windows 절대경로' => [['php_binary' => 'C:\\php\\php.exe'], 'php_binary'],
|
||||
'Composer 미입력' => [[], 'composer_binary'],
|
||||
'Composer 기본값' => [['composer_binary' => 'composer'], 'composer_binary'],
|
||||
'Composer 절대경로' => [['composer_binary' => '/usr/local/bin/composer'], 'composer_binary'],
|
||||
'Composer phar' => [['composer_binary' => '/opt/composer.phar'], 'composer_binary'],
|
||||
'PHP+phar 쌍' => [['composer_binary' => '/usr/bin/php /opt/composer.phar'], 'composer_binary'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Services\LanguagePack\LanguagePackPhpArrayValidator;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 언어팩 PHP 파일 문법 검사기 테스트.
|
||||
*
|
||||
* KVE-2026-1678: 언어팩의 PHP 파일은 활성화되면 `require` 되어 그대로 실행된다. 기존 검사는
|
||||
* 위험 함수 11개를 정규식으로 나열해 막았고, 목록에 없는 함수·문법으로 전부 우회됐다.
|
||||
* 본 검사기는 "번역 배열만" 통과시키는 화이트리스트 문법이므로, 우회 매트릭스는
|
||||
* **함수 이름이 아니라 문법 형태**를 축으로 전개한다.
|
||||
*
|
||||
* DB·프레임워크 부팅이 필요 없는 순수 판정 유틸이라 PHPUnit\Framework\TestCase 를 직접 상속한다.
|
||||
*/
|
||||
class LanguagePackPhpArrayValidatorTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 번역 배열만 담은 정상 파일은 통과한다 (기존 자산 비파괴).
|
||||
*
|
||||
* @param string $source PHP 소스
|
||||
*
|
||||
* @scenario vector=php_syntax_validator, actor_permission=cli_system
|
||||
*
|
||||
* @effects translation_array_files_are_accepted
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('safeSourceProvider')]
|
||||
public function it_accepts_translation_array_files(string $source): void
|
||||
{
|
||||
$violation = LanguagePackPhpArrayValidator::inspect($source);
|
||||
|
||||
$this->assertNull(
|
||||
$violation,
|
||||
'정상 언어팩 파일이 거부됨: '.($violation['reason'] ?? '').' — '.$source
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 번역 배열 외의 문법은 전부 거부한다.
|
||||
*
|
||||
* 기존 블록리스트가 놓치던 함수들(`file_put_contents` `fopen` `call_user_func` `assert`
|
||||
* 백틱)과, 함수 이름을 아예 쓰지 않는 우회(문자열 리터럴 호출·가변 변수·heredoc·
|
||||
* 닫는 태그 뒤 인라인 코드)를 같은 규칙 하나로 막는지 확인한다.
|
||||
*
|
||||
* @param string $source PHP 소스
|
||||
* @param string $vector 우회 수법 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=php_syntax_validator, actor_permission=cli_system
|
||||
*
|
||||
* @effects function_calls_are_rejected_regardless_of_name, name_free_bypasses_are_rejected
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('unsafeSourceProvider')]
|
||||
public function it_rejects_anything_that_is_not_a_translation_array(string $source, string $vector): void
|
||||
{
|
||||
$this->assertFalse(
|
||||
LanguagePackPhpArrayValidator::isSafe($source),
|
||||
"차단되어야 하는 소스가 통과함 ({$vector}): {$source}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 깨진 소스는 파싱 단계에서 조기 거부한다.
|
||||
*
|
||||
* @scenario vector=php_syntax_validator, actor_permission=cli_system
|
||||
*
|
||||
* @effects broken_and_oversized_sources_are_rejected_early
|
||||
*/
|
||||
#[Test]
|
||||
public function it_rejects_sources_that_do_not_parse(): void
|
||||
{
|
||||
$violation = LanguagePackPhpArrayValidator::inspect('<?php return [ ;');
|
||||
|
||||
$this->assertNotNull($violation);
|
||||
$this->assertSame('parse_error', $violation['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 크기 상한을 넘는 소스는 파서를 돌리지 않고 거부한다.
|
||||
*/
|
||||
#[Test]
|
||||
public function it_rejects_sources_over_the_size_limit(): void
|
||||
{
|
||||
$source = '<?php return ['.str_repeat("'a' => 'b', ", 200000).'];';
|
||||
|
||||
$this->assertGreaterThan(LanguagePackPhpArrayValidator::MAX_BYTES, strlen($source));
|
||||
|
||||
$violation = LanguagePackPhpArrayValidator::inspect($source);
|
||||
|
||||
$this->assertNotNull($violation);
|
||||
$this->assertSame('file_too_large', $violation['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 중첩 깊이 상한을 넘는 배열은 거부한다.
|
||||
*/
|
||||
#[Test]
|
||||
public function it_rejects_arrays_deeper_than_the_depth_limit(): void
|
||||
{
|
||||
$depth = LanguagePackPhpArrayValidator::MAX_DEPTH + 5;
|
||||
$source = '<?php return '.str_repeat('[', $depth).str_repeat(']', $depth).';';
|
||||
|
||||
$this->assertFalse(LanguagePackPhpArrayValidator::isSafe($source));
|
||||
}
|
||||
|
||||
/**
|
||||
* 위반 지점의 줄 번호를 보고한다 (운영자가 어느 줄을 고쳐야 하는지 알 수 있어야 한다).
|
||||
*
|
||||
* @scenario vector=php_syntax_validator, actor_permission=cli_system
|
||||
*
|
||||
* @effects violation_line_is_reported
|
||||
*/
|
||||
#[Test]
|
||||
public function it_reports_the_line_of_the_violation(): void
|
||||
{
|
||||
$source = "<?php\n\nreturn [\n 'a' => 'b',\n 'c' => system('id'),\n];\n";
|
||||
|
||||
$violation = LanguagePackPhpArrayValidator::inspect($source);
|
||||
|
||||
$this->assertNotNull($violation);
|
||||
$this->assertSame(5, $violation['line']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통과해야 하는 소스 목록.
|
||||
*
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function safeSourceProvider(): array
|
||||
{
|
||||
return [
|
||||
'빈 배열' => ["<?php\n\nreturn [];\n"],
|
||||
'단순 문자열 배열' => ["<?php\n\nreturn ['hello' => 'こんにちは'];\n"],
|
||||
'중첩 배열' => ["<?php\nreturn ['a' => ['b' => ['c' => 'd']]];\n"],
|
||||
'숫자 키' => ["<?php\nreturn [0 => 'zero', 1 => 'one'];\n"],
|
||||
'키 없는 항목' => ["<?php\nreturn ['first', 'second'];\n"],
|
||||
'후행 쉼표' => ["<?php\nreturn [\n 'a' => 'b',\n];\n"],
|
||||
'declare 프리픽스' => ["<?php\n\ndeclare(strict_types=1);\n\nreturn ['a' => 'b'];\n"],
|
||||
'문자열 리터럴 연결' => ["<?php\nreturn ['a' => 'long '.'message'];\n"],
|
||||
'숫자·bool·null' => ["<?php\nreturn ['n' => 1, 'f' => 1.5, 'neg' => -3, 't' => true, 'f2' => false, 'x' => null];\n"],
|
||||
'주석 포함' => ["<?php\n// 인사말\nreturn [\n /* 그룹 */ 'a' => 'b', // 항목\n];\n"],
|
||||
'array() 레거시 문법' => ["<?php\nreturn array('a' => 'b');\n"],
|
||||
'닫는 태그 포함' => ["<?php\nreturn ['a' => 'b'];\n?>\n"],
|
||||
'이스케이프 포함 문자열' => ["<?php\nreturn ['a' => 'It\\'s ok', 'b' => \"tab\\there\"];\n"],
|
||||
'대문자 상수 표기' => ["<?php\nreturn ['a' => TRUE, 'b' => NULL];\n"],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 차단되어야 하는 소스 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function unsafeSourceProvider(): array
|
||||
{
|
||||
return [
|
||||
// 기존 블록리스트가 잡던 것
|
||||
'eval' => ["<?php\neval(\$_GET['c']);\nreturn [];\n", '기존 목록 — eval'],
|
||||
// 기존 블록리스트가 놓치던 것
|
||||
'file_put_contents' => ["<?php\nfile_put_contents('/tmp/g7','x');\nreturn [];\n", '목록 누락 — 파일 쓰기'],
|
||||
'fopen/fwrite' => ["<?php\n\$h = fopen('/tmp/g7','w');\nfwrite(\$h,'x');\nreturn [];\n", '목록 누락 — 스트림'],
|
||||
'unlink' => ["<?php\nunlink('/etc/passwd');\nreturn [];\n", '목록 누락 — 삭제'],
|
||||
'call_user_func' => ["<?php\ncall_user_func('system','id');\nreturn [];\n", '목록 누락 — 간접 호출'],
|
||||
'assert' => ["<?php\nassert(\"system('id')\");\nreturn [];\n", '목록 누락 — assert'],
|
||||
'백틱 실행 연산자' => ["<?php\n\$o = `id`;\nreturn [];\n", '목록 누락 — 백틱'],
|
||||
'file_get_contents 반환' => ["<?php\nreturn ['a' => file_get_contents('/etc/passwd')];\n", '목록 누락 — 값 자리 호출'],
|
||||
|
||||
// 함수 이름을 쓰지 않는 우회 (블록리스트로는 원리적으로 불가)
|
||||
'문자열 리터럴 호출' => ["<?php\nreturn [('system')('id')];\n", '이름 없는 호출 — 토큰 집합 검사 우회'],
|
||||
'가변 변수 호출' => ["<?php\n\$a='system';\$a('id');\nreturn [];\n", '가변 변수'],
|
||||
'변수 사용' => ["<?php\nreturn ['a' => \$GLOBALS['x']];\n", '변수'],
|
||||
'heredoc 보간' => ["<?php\n\$x = <<<EOT\n{\$_GET['c']}\nEOT;\nreturn [];\n", 'heredoc'],
|
||||
'닫는 태그 뒤 인라인 코드' => ["<?php\nreturn [];\n?>\n<?php system('id');\n", '닫는 태그 뒤 두 번째 블록'],
|
||||
'닫는 태그 뒤 출력' => ["<?php\nreturn [];\n?>\nleaked\n", '닫는 태그 뒤 인라인 출력'],
|
||||
'new 객체' => ["<?php\nreturn ['a' => new \\stdClass];\n", 'new'],
|
||||
'상수 참조' => ["<?php\nreturn ['a' => PHP_OS];\n", '상수 — 정보 노출'],
|
||||
'삼항 연산' => ["<?php\nreturn ['a' => 1 > 0 ? 'y' : 'n'];\n", '연산자'],
|
||||
'함수 선언' => ["<?php\nfunction g7_evil(){ system('id'); }\nreturn [];\n", '함수 선언'],
|
||||
'클래스 선언' => ["<?php\nclass Evil { }\nreturn [];\n", '클래스 선언'],
|
||||
'use 문' => ["<?php\nuse App\\Models\\User;\nreturn [];\n", 'use'],
|
||||
'return 없음' => ["<?php\n\$a = 1;\n", 'return 부재'],
|
||||
'return 뒤 추가 구문' => ["<?php\nreturn [];\nsystem('id');\n", 'return 뒤 잔여 토큰'],
|
||||
'단축 에코 태그' => ["<?= system('id') ?>\n", '단축 태그'],
|
||||
'선행 인라인 HTML' => ["leaked\n<?php\nreturn [];\n", '여는 태그 앞 출력'],
|
||||
'괄호 그룹화' => ["<?php\nreturn ('a');\n", '괄호 — array 뒤가 아님'],
|
||||
'declare 위장' => ["<?php\ndeclare(ticks=1);\nreturn [];\n", 'declare 다른 지시자'],
|
||||
'스프레드' => ["<?php\nreturn [...\$a];\n", '스프레드 연산자'],
|
||||
'함수 호출을 키로' => ["<?php\nreturn [system('id') => 'x'];\n", '키 자리 호출'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\LanguagePack\LanguagePackPhpArrayValidator;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
@@ -53,7 +54,7 @@ class LanguagePackSecurityTest extends TestCase
|
||||
private function makeZip(array $files): string
|
||||
{
|
||||
$zipPath = $this->tempDir.DIRECTORY_SEPARATOR.uniqid('pack_', true).'.zip';
|
||||
$zip = new ZipArchive();
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($zipPath, ZipArchive::CREATE);
|
||||
foreach ($files as $name => $content) {
|
||||
$zip->addFromString($name, $content);
|
||||
@@ -109,7 +110,9 @@ class LanguagePackSecurityTest extends TestCase
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/허용되지 않/u');
|
||||
// 판정이 "위험 함수 목록" 에서 "번역 배열만 허용" 으로 바뀌었으므로 메시지도 바뀐다.
|
||||
// 이 테스트의 의도(backend 안의 eval 이 차단된다)는 그대로 유지한다.
|
||||
$this->expectExceptionMessageMatches('/번역 배열만/u');
|
||||
|
||||
$this->service->installFromFile($file, false, null);
|
||||
}
|
||||
@@ -130,4 +133,238 @@ class LanguagePackSecurityTest extends TestCase
|
||||
// 활성 디렉토리 정리
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 기존 블록리스트가 놓치던 페이로드가 설치 단계에서 거부된다.
|
||||
*
|
||||
* KVE-2026-1678 주 시나리오. 정규식 블록리스트는 위험 함수 11개만 봤기 때문에
|
||||
* `file_put_contents` 한 줄로 우회됐고, 활성화되면 `require` 되어 그대로 실행됐다.
|
||||
*
|
||||
* @param string $payload backend PHP 파일 내용
|
||||
* @param string $vector 우회 수법 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects install_rejects_php_that_is_not_a_translation_array
|
||||
*/
|
||||
#[DataProvider('blocklistBypassPayloadProvider')]
|
||||
public function test_install_rejects_payloads_the_old_blocklist_missed(string $payload, string $vector): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/ja/messages.php' => $payload,
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
|
||||
try {
|
||||
$this->service->installFromFile($file, false, null);
|
||||
} finally {
|
||||
// 거부되지 않고 설치되었다면 잔여물을 남기지 않는다.
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
|
||||
$this->fail("차단되어야 하는 페이로드가 설치됨 ({$vector})");
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자 밖의 파일은 거부된다 (대소문자 무관).
|
||||
*
|
||||
* 이전 판정은 `str_ends_with($absolute, '.php')` 라 `EVIL.PHP` 를 PHP 로 보지 않았고,
|
||||
* `.phar` `.phtml` 처럼 실행 가능한 다른 확장자도 아무 검사 없이 통과했다.
|
||||
*
|
||||
* @param string $path ZIP 안의 파일 경로
|
||||
* @param string $reason 차단 사유 (실패 메시지용)
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects install_rejects_files_outside_the_extension_whitelist
|
||||
*/
|
||||
#[DataProvider('disallowedFilePathProvider')]
|
||||
public function test_install_rejects_files_outside_the_extension_whitelist(string $path, string $reason): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/ja/messages.php' => "<?php\nreturn [];\n",
|
||||
$path => "<?php\nsystem('id');\n",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
|
||||
try {
|
||||
$this->service->installFromFile($file, false, null);
|
||||
} finally {
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
|
||||
$this->fail("차단되어야 하는 파일이 설치됨 ({$reason}): {$path}");
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 의 locale 과 다른 디렉토리에 놓인 PHP 는 거부된다.
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects install_rejects_php_outside_the_declared_locale_directory
|
||||
*/
|
||||
public function test_install_rejects_php_in_a_different_locale_directory(): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/ko/messages.php' => "<?php\nreturn [];\n",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/backend/i');
|
||||
|
||||
try {
|
||||
$this->service->installFromFile($file, false, null);
|
||||
} finally {
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 언어팩 구성(declare 프리픽스·문자열 연결·중첩 배열·json·md)은 그대로 설치된다.
|
||||
*
|
||||
* 확장(`modules/`·`plugins/`) 의 lang 파일에 실제로 나타나는 형태이므로
|
||||
* 이 케이스가 깨지면 기존 자산이 설치 불가가 된다.
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects install_accepts_real_world_translation_files
|
||||
*/
|
||||
public function test_install_accepts_real_world_translation_files(): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/ja/messages.php' => "<?php\n\ndeclare(strict_types=1);\n\nreturn [\n 'a' => 'long '.'message',\n 'nested' => ['x' => ['y' => 1, 'z' => null]],\n];\n",
|
||||
'frontend/ja.json' => '{"hello":"こんにちは"}',
|
||||
'README.md' => "# pack\n",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$pack = $this->service->installFromFile($file, false, null);
|
||||
|
||||
$this->assertSame('test-core-ja', $pack->identifier);
|
||||
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 심볼릭 링크가 포함된 패키지는 거부된다 (패키지 밖 파일을 끌어들이는 통로 차단).
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects install_rejects_packages_containing_symlinks
|
||||
*/
|
||||
public function test_install_rejects_packages_containing_symlinks(): void
|
||||
{
|
||||
$packageRoot = $this->tempDir.DIRECTORY_SEPARATOR.'symlink_pack';
|
||||
File::ensureDirectoryExists($packageRoot.DIRECTORY_SEPARATOR.'backend'.DIRECTORY_SEPARATOR.'ja');
|
||||
File::put($packageRoot.DIRECTORY_SEPARATOR.'language-pack.json', $this->validManifestJson());
|
||||
File::put($packageRoot.DIRECTORY_SEPARATOR.'backend'.DIRECTORY_SEPARATOR.'ja'.DIRECTORY_SEPARATOR.'messages.php', "<?php\nreturn [];\n");
|
||||
|
||||
$target = $this->tempDir.DIRECTORY_SEPARATOR.'outside.json';
|
||||
File::put($target, '{}');
|
||||
|
||||
if (! @symlink($target, $packageRoot.DIRECTORY_SEPARATOR.'linked.json')) {
|
||||
$this->markTestSkipped('이 환경에서는 심볼릭 링크를 만들 수 없어 (권한 부족) 링크 거부를 실측할 수 없다.');
|
||||
}
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
|
||||
$this->invokeAssertSecurityRules($packageRoot, json_decode($this->validManifestJson(), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장소에 동봉된 번들 언어팩 전부가 새 검사를 통과한다.
|
||||
*
|
||||
* 회귀 방지의 핵심 — 검사를 조인 결과로 기존 자산이 설치 불가가 되면 안 된다.
|
||||
* 번들에도 같은 검사를 적용하기로 했으므로(검사 경로 단일화) 전수로 확인한다.
|
||||
*
|
||||
* @scenario vector=assert_security_rules, actor_permission=cli_system
|
||||
*
|
||||
* @effects every_bundled_pack_passes_the_new_validator
|
||||
*/
|
||||
public function test_all_bundled_packs_pass_the_validator(): void
|
||||
{
|
||||
$root = base_path('lang-packs/_bundled');
|
||||
|
||||
$this->assertDirectoryExists($root);
|
||||
|
||||
$files = [];
|
||||
foreach (File::allFiles($root) as $file) {
|
||||
if (strtolower($file->getExtension()) === 'php') {
|
||||
$files[] = $file->getPathname();
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotEmpty($files, '번들 언어팩 PHP 파일이 하나도 수집되지 않았다 — 전수 검사가 공전한다');
|
||||
|
||||
$violations = [];
|
||||
foreach ($files as $path) {
|
||||
$violation = LanguagePackPhpArrayValidator::inspectFile($path);
|
||||
|
||||
if ($violation !== null) {
|
||||
$violations[] = str_replace($root, '', $path)." (line {$violation['line']}: {$violation['reason']})";
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertSame([], $violations, '번들 언어팩이 새 검사에서 거부됨: '.implode(', ', $violations));
|
||||
}
|
||||
|
||||
/**
|
||||
* private 보안 검사를 직접 호출합니다 (ZIP 으로는 심볼릭 링크를 넣을 수 없다).
|
||||
*
|
||||
* @param string $packageRoot 패키지 루트
|
||||
* @param array<string, mixed> $manifest manifest 데이터
|
||||
*/
|
||||
private function invokeAssertSecurityRules(string $packageRoot, array $manifest): void
|
||||
{
|
||||
$method = new \ReflectionMethod($this->service, 'assertSecurityRules');
|
||||
$method->invoke($this->service, $packageRoot, $manifest);
|
||||
}
|
||||
|
||||
/**
|
||||
* 기존 정규식 블록리스트가 놓치던 페이로드 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function blocklistBypassPayloadProvider(): array
|
||||
{
|
||||
return [
|
||||
'file_put_contents' => ["<?php\nfile_put_contents('/tmp/g7_lp_proof','x');\nreturn [];\n", '파일 쓰기'],
|
||||
'fopen + fwrite' => ["<?php\n\$h=fopen('/tmp/g7_lp_proof','w');fwrite(\$h,'x');\nreturn [];\n", '스트림'],
|
||||
'call_user_func' => ["<?php\ncall_user_func('system','id');\nreturn [];\n", '간접 호출'],
|
||||
'assert' => ["<?php\nassert(\"system('id')\");\nreturn [];\n", 'assert'],
|
||||
'백틱' => ["<?php\n\$o=`id`;\nreturn [];\n", '백틱 실행 연산자'],
|
||||
'문자열 리터럴 호출' => ["<?php\nreturn [('system')('id')];\n", '이름 없는 호출'],
|
||||
'닫는 태그 뒤 코드' => ["<?php\nreturn [];\n?>\n<?php system('id');\n", '두 번째 PHP 블록'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자 밖이라 거부되어야 하는 파일 경로 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function disallowedFilePathProvider(): array
|
||||
{
|
||||
return [
|
||||
'대문자 확장자' => ['backend/ja/EVIL.PHP', '확장자 판정이 대소문자를 구분하면 통과한다'],
|
||||
'phar' => ['backend/ja/evil.phar', '실행 가능한 아카이브'],
|
||||
'phtml' => ['backend/ja/evil.phtml', 'PHP 템플릿 확장자'],
|
||||
'php5' => ['backend/ja/evil.php5', '레거시 PHP 확장자'],
|
||||
'확장자 없음' => ['backend/ja/htaccess_like', '확장자 화이트리스트 밖'],
|
||||
'루트 PHP' => ['evil.php', 'backend 밖 PHP'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@ namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Exceptions\LanguagePackOperationException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -225,7 +229,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
@@ -249,7 +253,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
@@ -274,7 +278,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
@@ -411,7 +415,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->assertFileExists($installedDir.'/seed/permissions.json');
|
||||
|
||||
// cleanup — 활성 디렉토리 제거 (RefreshDatabase 와 별개)
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($installedDir);
|
||||
File::deleteDirectory($installedDir);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -445,7 +449,257 @@ class LanguagePackServiceTest extends TestCase
|
||||
'재설치 시 자기 자신을 슬롯 충돌로 오인하여 active → installed 로 강등되면 안 됨 (회귀)');
|
||||
|
||||
// cleanup
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/g7-core-ja'));
|
||||
File::deleteDirectory(base_path('lang-packs/g7-core-ja'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동 활성화는 `activated` 훅을 정확히 한 번만 발화한다.
|
||||
*
|
||||
* 이전 구현은 설치 트랜잭션에서 status 를 직접 active 로 쓴 뒤 훅을 발화했고,
|
||||
* 활성화 경로(activate)도 같은 훅을 발화해 두 경로가 공존했다. 활성화를 activate()
|
||||
* 한 곳으로 모았으므로 발화도 한 번이어야 한다 — 두 번 발화되면 훅 구독자가
|
||||
* 캐시 재생성·알림 등을 중복 수행한다.
|
||||
*
|
||||
* @scenario vector=finalize_install_activation, actor_permission=cli_system
|
||||
*
|
||||
* @effects activated_hook_fires_exactly_once_on_auto_activate
|
||||
*/
|
||||
public function test_activated_hook_fires_exactly_once_on_auto_activate(): void
|
||||
{
|
||||
$bundledPath = base_path('lang-packs/_bundled/g7-core-ja');
|
||||
if (! is_dir($bundledPath) || ! is_file($bundledPath.'/language-pack.json')) {
|
||||
$this->markTestSkipped('g7-core-ja 번들이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
|
||||
$fired = 0;
|
||||
HookManager::addAction('core.language_packs.activated', function () use (&$fired) {
|
||||
$fired++;
|
||||
});
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $pack->status);
|
||||
$this->assertSame(1, $fired, 'activated 훅이 정확히 1회 발화되지 않음');
|
||||
} finally {
|
||||
HookManager::clearAction('core.language_packs.activated');
|
||||
File::deleteDirectory(base_path('lang-packs/g7-core-ja'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 같은 슬롯에 이미 다른 활성 팩이 있으면 자동 활성화를 건너뛴다 (기존 동작 유지).
|
||||
*
|
||||
* 활성화를 activate() 경유로 바꾸면서 슬롯이 점유된 경우 예외가 새로 터지지 않아야 한다 —
|
||||
* 설치 자체는 성공하고 상태만 installed 로 남는 것이 기존 동작이다.
|
||||
*
|
||||
* @scenario vector=finalize_install_activation, actor_permission=cli_system
|
||||
*
|
||||
* @effects auto_activate_skipped_when_slot_occupied
|
||||
*/
|
||||
public function test_auto_activate_skipped_when_slot_occupied(): void
|
||||
{
|
||||
$bundledPath = base_path('lang-packs/_bundled/g7-core-ja');
|
||||
if (! is_dir($bundledPath) || ! is_file($bundledPath.'/language-pack.json')) {
|
||||
$this->markTestSkipped('g7-core-ja 번들이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
|
||||
// 같은 슬롯(core / ja)을 다른 팩이 이미 점유한 상태
|
||||
$this->makePack('other', 'ja', LanguagePackStatus::Active->value);
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
|
||||
|
||||
$this->assertSame(
|
||||
LanguagePackStatus::Installed->value,
|
||||
$pack->status,
|
||||
'슬롯이 점유되어 있으면 설치는 성공하되 활성화는 건너뛰어야 한다'
|
||||
);
|
||||
} finally {
|
||||
File::deleteDirectory(base_path('lang-packs/g7-core-ja'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동 활성화는 트랜잭션의 직접 기록이 아니라 activate() 를 경유하며,
|
||||
* 그 경로에는 의존성 검사가 실제로 걸린다.
|
||||
*
|
||||
* 두 가지를 각각 단언한다.
|
||||
* (1) 경로 — `installed` 훅이 발화하는 시점(트랜잭션 직후)의 DB 상태가 `installed` 여야
|
||||
* 한다. 예전처럼 트랜잭션이 status 를 active 로 직접 썼다면 이 시점에 이미 active 다.
|
||||
* 그 뒤 `activated` 훅이 발화하고 최종 상태가 active 가 되는 순서까지 확인하면
|
||||
* 활성 승격이 activate() 에서 일어났다는 것이 확정된다.
|
||||
* (2) 검사 — activate() 는 저장된 manifest 로 의존성을 검사한다. 코어 로케일이
|
||||
* 활성이 아닌 확장 스코프 팩은 activate() 단계에서 거부되어야 한다.
|
||||
*
|
||||
* @scenario vector=finalize_install_activation, actor_permission=cli_system
|
||||
*
|
||||
* @effects auto_activate_goes_through_activate_and_enforces_dependencies
|
||||
*/
|
||||
public function test_finalize_install_with_auto_activate_goes_through_activate_and_runs_dependency_checks(): void
|
||||
{
|
||||
$identifier = 'actpath-core-ja';
|
||||
$bundledDir = $this->createBundledFixture($identifier, $this->coreJaManifest($identifier, 'actpath', '1.0.0'));
|
||||
|
||||
/** @var list<string> $order 훅 발화 순서 */
|
||||
$order = [];
|
||||
$statusAtInstalledHook = null;
|
||||
|
||||
HookManager::addAction('core.language_packs.installed', function () use (&$order, &$statusAtInstalledHook, $identifier) {
|
||||
$order[] = 'installed';
|
||||
$statusAtInstalledHook = DB::table('language_packs')
|
||||
->where('identifier', $identifier)
|
||||
->value('status');
|
||||
});
|
||||
HookManager::addAction('core.language_packs.activated', function () use (&$order) {
|
||||
$order[] = 'activated';
|
||||
});
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled($identifier, autoActivate: true);
|
||||
|
||||
// (1) 경로 — 트랜잭션은 installed 로만 기록하고, 활성 승격은 그 뒤 activate() 에서 일어난다.
|
||||
$this->assertSame(
|
||||
LanguagePackStatus::Installed->value,
|
||||
$statusAtInstalledHook,
|
||||
'설치 트랜잭션이 status 를 active 로 직접 기록했다 — activate() 를 경유하지 않는다'
|
||||
);
|
||||
$this->assertSame(['installed', 'activated'], $order, '활성화가 설치 트랜잭션보다 먼저/동시에 일어났다');
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $pack->status);
|
||||
} finally {
|
||||
HookManager::clearAction('core.language_packs.installed');
|
||||
HookManager::clearAction('core.language_packs.activated');
|
||||
File::deleteDirectory($bundledDir);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
|
||||
// (2) 검사 — activate() 는 저장된 manifest 의 의존성을 실제로 검사한다.
|
||||
// 코어 로케일이 활성이 아닌 상태에서 모듈 스코프 팩을 활성화하면 거부되어야 한다.
|
||||
// (위에서 설치한 팩이 코어 ja 를 점유하므로 의존성이 미충족인 다른 로케일을 쓴다)
|
||||
$dependent = LanguagePack::query()->create([
|
||||
'identifier' => 'actpath-module-de',
|
||||
'vendor' => 'actpath',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'acme-demo',
|
||||
'locale' => 'de',
|
||||
'locale_name' => 'DE',
|
||||
'locale_native_name' => 'Deutsch',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Installed->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [
|
||||
'identifier' => 'actpath-module-de',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'acme-demo',
|
||||
'locale' => 'de',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertFalse(
|
||||
$this->registry->hasActiveCoreLocale('de'),
|
||||
'전제 조건 붕괴 — 코어 de 가 활성이면 의존성 검사가 통과해버려 이 단언이 무의미해진다'
|
||||
);
|
||||
|
||||
$this->expectException(LanguagePackOperationException::class);
|
||||
$this->service->activate($dependent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 팩의 업데이트는 활성 상태를 유지한다 — activate() 경유 전환의 회귀 가드.
|
||||
*
|
||||
* `performUpdate` 는 `$autoActivate = $pack->isActive()` 로 활성 여부를 승계해
|
||||
* 재설치 경로로 넘긴다. 활성화가 트랜잭션 직접 기록에서 activate() 경유로 바뀌면서
|
||||
* 이 경로에 의존성 검사·슬롯 충돌 검사가 새로 끼어들었으므로, 활성 팩의 업데이트가
|
||||
* 조용히 installed 로 떨어지거나 예외로 막히지 않는지 고정한다.
|
||||
*
|
||||
* @scenario vector=finalize_install_activation, actor_permission=cli_system
|
||||
*
|
||||
* @effects update_of_an_active_pack_keeps_it_active
|
||||
*/
|
||||
public function test_perform_update_of_active_pack_keeps_it_active(): void
|
||||
{
|
||||
$identifier = 'updact-core-ja';
|
||||
$bundledDir = $this->createBundledFixture($identifier, $this->coreJaManifest($identifier, 'updact', '1.0.0'));
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled($identifier, autoActivate: true);
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $pack->status, '전제 조건 — 업데이트 대상은 활성 팩이어야 한다');
|
||||
|
||||
// 번들에 신버전 배치 후 업데이트 (bundled 소스 강제)
|
||||
$this->createBundledFixture($identifier, $this->coreJaManifest($identifier, 'updact', '1.0.1'));
|
||||
|
||||
$updated = $this->service->performUpdate($pack, force: true);
|
||||
|
||||
$this->assertSame('1.0.1', $updated->version);
|
||||
$this->assertSame(
|
||||
LanguagePackStatus::Active->value,
|
||||
$updated->status,
|
||||
'활성 팩을 업데이트했더니 활성 상태를 잃었다 — activate() 경유 전환의 회귀'
|
||||
);
|
||||
} finally {
|
||||
File::deleteDirectory($bundledDir);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비활성 팩의 업데이트는 활성으로 승격되지 않는다 (기존 동작 유지).
|
||||
*
|
||||
* @scenario vector=finalize_install_activation, actor_permission=cli_system
|
||||
*
|
||||
* @effects update_of_an_inactive_pack_does_not_promote_it
|
||||
*/
|
||||
public function test_perform_update_of_inactive_pack_does_not_promote_it(): void
|
||||
{
|
||||
$identifier = 'updinact-core-ja';
|
||||
$bundledDir = $this->createBundledFixture($identifier, $this->coreJaManifest($identifier, 'updinact', '1.0.0'));
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled($identifier, autoActivate: false);
|
||||
$this->assertSame(LanguagePackStatus::Installed->value, $pack->status);
|
||||
|
||||
$this->createBundledFixture($identifier, $this->coreJaManifest($identifier, 'updinact', '1.0.1'));
|
||||
|
||||
$updated = $this->service->performUpdate($pack, force: true);
|
||||
|
||||
$this->assertSame('1.0.1', $updated->version);
|
||||
$this->assertSame(
|
||||
LanguagePackStatus::Installed->value,
|
||||
$updated->status,
|
||||
'비활성 팩이 업데이트만으로 활성 승격되면 안 된다'
|
||||
);
|
||||
} finally {
|
||||
File::deleteDirectory($bundledDir);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 ja 번들 픽스처용 manifest 를 만듭니다.
|
||||
*
|
||||
* @param string $identifier 번들 식별자
|
||||
* @param string $vendor 벤더
|
||||
* @param string $version 버전
|
||||
* @return array<string, mixed> manifest 데이터
|
||||
*/
|
||||
private function coreJaManifest(string $identifier, string $vendor, string $version): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $identifier,
|
||||
'namespace' => $vendor,
|
||||
'vendor' => $vendor,
|
||||
'name' => ['ko' => $identifier, 'en' => $identifier, 'ja' => $identifier],
|
||||
'description' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => $version,
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'JA',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
];
|
||||
}
|
||||
|
||||
public function test_install_blocks_downgrade_without_force(): void
|
||||
@@ -485,11 +739,11 @@ class LanguagePackServiceTest extends TestCase
|
||||
]);
|
||||
|
||||
// force=false → 다운그레이드 차단 예외
|
||||
$this->expectException(\App\Exceptions\LanguagePackOperationException::class);
|
||||
$this->expectException(LanguagePackOperationException::class);
|
||||
$this->service->installFromBundled($identifier);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($bundledDir);
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
File::deleteDirectory($bundledDir);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,8 +787,8 @@ class LanguagePackServiceTest extends TestCase
|
||||
$pack = $this->service->installFromBundled($identifier, force: true);
|
||||
$this->assertSame('1.0.0-beta.1', $pack->version);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($bundledDir);
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
File::deleteDirectory($bundledDir);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,8 +802,8 @@ class LanguagePackServiceTest extends TestCase
|
||||
private function createBundledFixture(string $identifier, array $manifest): string
|
||||
{
|
||||
$path = base_path('lang-packs/_bundled/'.$identifier);
|
||||
\Illuminate\Support\Facades\File::ensureDirectoryExists($path);
|
||||
\Illuminate\Support\Facades\File::put(
|
||||
File::ensureDirectoryExists($path);
|
||||
File::put(
|
||||
$path.DIRECTORY_SEPARATOR.'language-pack.json',
|
||||
json_encode($manifest, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
|
||||
);
|
||||
@@ -584,7 +838,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->assertFalse($match->exists, '가상 레코드는 exists=false 여야 함');
|
||||
$this->assertNull($match->id, '가상 레코드는 id 가 null 이어야 함');
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,7 +878,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$match = $packs->firstWhere('identifier', $identifier);
|
||||
$this->assertNull($match, '동일 슬롯에 DB 레코드가 있으면 가상 레코드가 반환되지 않아야 함');
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,7 +914,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->assertNotNull($virtual);
|
||||
$this->assertSame(LanguagePackStatus::Uninstalled->value, $virtual->status);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,7 +943,7 @@ class LanguagePackServiceTest extends TestCase
|
||||
$this->assertNotNull($items->firstWhere('identifier', $identifier));
|
||||
$this->assertNull($items->firstWhere('status', LanguagePackStatus::Active->value));
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace Tests\Unit\Support;
|
||||
|
||||
use App\Support\ScheduleCommandValidator;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Modules\G7Testing\Console\FakeExtensionScheduleCommand;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
@@ -145,6 +147,10 @@ class ScheduleCommandValidatorTest extends TestCase
|
||||
* 차단목록에 오른 artisan 명령은 거부한다 (코드 실행형·파괴적 명령).
|
||||
*
|
||||
* @param string $command 차단되어야 하는 command
|
||||
*
|
||||
* @scenario command_class=denylisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects denylist_blocks_destructive_and_code_executing_commands
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('deniedArtisanCommandProvider')]
|
||||
@@ -160,6 +166,10 @@ class ScheduleCommandValidatorTest extends TestCase
|
||||
* 차단목록에 없는 artisan 명령은 허용한다 (기본 허용).
|
||||
*
|
||||
* @param string $command 허용되어야 하는 command
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects allowlisted_maintenance_commands_still_run
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('allowedArtisanCommandProvider')]
|
||||
@@ -177,10 +187,331 @@ class ScheduleCommandValidatorTest extends TestCase
|
||||
#[Test]
|
||||
public function it_extracts_the_artisan_command_name_from_the_first_token(): void
|
||||
{
|
||||
$this->assertSame('cache:clear', ScheduleCommandValidator::extractArtisanCommandName(' cache:clear --force '));
|
||||
$this->assertSame('cache:clear', ScheduleCommandValidator::extractArtisanCommandName(' cache:clear --tags=a '));
|
||||
$this->assertNull(ScheduleCommandValidator::extractArtisanCommandName(' '));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Artisan — 파서 분기 (KVE-2026-1679 추가 발견분)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 검증기가 본 이름과 Symfony 가 해석하는 이름이 갈리는 입력은 거부한다.
|
||||
*
|
||||
* 검증기는 `preg_split` 첫 토큰을 명령명으로 봤지만 실행부는 문자열 전체를
|
||||
* StringInput 으로 재파싱했다. 따옴표·백슬래시·선행 옵션 한 쌍이면 차단목록에 있는
|
||||
* `tinker` 가 그대로 실행됐다. 판정이 거부라는 것뿐 아니라, 명령명 추출이
|
||||
* **다른 이름을 돌려주지 않는 것**까지 단언한다 — 이름이 돌아오면 그 이름으로 실행하는
|
||||
* 호출부가 언제든 다시 생길 수 있다.
|
||||
*
|
||||
* @param string $command 파서 분기를 유발하는 command
|
||||
* @param string $symfonyName Symfony 가 실제로 해석하는 명령명
|
||||
*
|
||||
* @scenario command_class=parser_divergent, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects parser_divergent_input_is_rejected, extracted_name_equals_executed_name
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('parserDivergenceArtisanCommandProvider')]
|
||||
public function it_blocks_artisan_commands_whose_parsed_name_diverges(string $command, string $symfonyName): void
|
||||
{
|
||||
$this->assertFalse(
|
||||
ScheduleCommandValidator::isArtisanCommandAllowed($command),
|
||||
"파서 분기 입력이 통과함: {$command}"
|
||||
);
|
||||
|
||||
$this->assertNull(
|
||||
ScheduleCommandValidator::extractArtisanCommandName($command),
|
||||
"정규 형태가 아닌 입력에서 명령명이 반환됨 (Symfony 는 '{$symfonyName}' 으로 해석): {$command}"
|
||||
);
|
||||
|
||||
$this->assertNull(
|
||||
ScheduleCommandValidator::resolveArtisanCommand($command),
|
||||
"파서 분기 입력에 실행 계획이 만들어짐: {$command}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파서 분기 입력의 거부 사유는 형식 오류로 보고된다.
|
||||
*
|
||||
* @scenario command_class=malformed, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects rejection_reason_is_reported_per_category
|
||||
*/
|
||||
#[Test]
|
||||
public function it_reports_malformed_as_the_reason_for_parser_divergent_input(): void
|
||||
{
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand('"tinker" --execute=1');
|
||||
|
||||
$this->assertFalse($verdict['allowed']);
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_MALFORMED, $verdict['reason']);
|
||||
$this->assertNull($verdict['name']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Artisan — 허용목록 / 옵션 / 인자
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 허용목록에 없는 명령은 무해하더라도 거부한다 (허용목록 전환의 증명).
|
||||
*
|
||||
* @param string $command 허용목록 밖 command
|
||||
*
|
||||
* @scenario command_class=core_not_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects commands_outside_the_allowlist_are_rejected
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('notAllowlistedArtisanCommandProvider')]
|
||||
public function it_blocks_artisan_commands_outside_the_allowlist(string $command): void
|
||||
{
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($command);
|
||||
|
||||
$this->assertFalse($verdict['allowed'], "허용목록 밖 명령이 통과함: {$command}");
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_NOT_ALLOWED, $verdict['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용된 명령이라도 선언되지 않은 옵션·위치 인자·단축 옵션은 거부한다.
|
||||
*
|
||||
* @param string $command 차단되어야 하는 command
|
||||
* @param string $reason 기대 거부 사유 코드
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects undeclared_options_and_positional_arguments_are_rejected
|
||||
*/
|
||||
#[Test]
|
||||
#[DataProvider('blockedOptionArtisanCommandProvider')]
|
||||
public function it_blocks_allowlisted_commands_with_denied_usage(string $command, string $reason): void
|
||||
{
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($command);
|
||||
|
||||
$this->assertFalse($verdict['allowed'], "거부되어야 하는 사용법이 통과함: {$command}");
|
||||
$this->assertSame($reason, $verdict['reason'], "거부 사유가 다름: {$command}");
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용된 명령은 (명령명, 인자배열) 실행 계획으로 변환된다.
|
||||
*
|
||||
* 이 배열을 `Artisan::call()` 에 넘겨야 StringInput 재파싱 경로가 사라진다.
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects allowed_command_resolves_to_name_and_parameter_array
|
||||
*/
|
||||
#[Test]
|
||||
public function it_returns_the_execution_plan_for_allowed_commands(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
['name' => 'queue:work', 'parameters' => ['--stop-when-empty' => true, '--max-time' => '300']],
|
||||
ScheduleCommandValidator::resolveArtisanCommand('queue:work --stop-when-empty --max-time=300')
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
['name' => 'cache:clear', 'parameters' => []],
|
||||
ScheduleCommandValidator::resolveArtisanCommand('cache:clear')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 차단목록은 허용목록보다 먼저 평가된다 (최종 거부권).
|
||||
*
|
||||
* 허용목록에 올라 있어도 차단목록에 있으면 거부되어야 한다 — 확장이 코어 명령 이름을
|
||||
* 가로채 등록하는 경우를 같은 규칙으로 막기 위함이다.
|
||||
*
|
||||
* @scenario command_class=denylisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects denylist_is_evaluated_before_the_allowlist
|
||||
*/
|
||||
#[Test]
|
||||
public function it_evaluates_the_denylist_before_the_allowlist(): void
|
||||
{
|
||||
config(['schedule_security.artisan.denylist' => ['cache:clear']]);
|
||||
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand('cache:clear');
|
||||
|
||||
$this->assertFalse($verdict['allowed']);
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_DENIED, $verdict['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* `make:` 접두사는 41개 명령을 개별 나열 없이 일괄 차단한다.
|
||||
*
|
||||
* @scenario command_class=code_generating, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects make_prefix_blocks_all_code_generating_commands
|
||||
*/
|
||||
#[Test]
|
||||
public function it_blocks_every_command_matching_a_denylisted_prefix(): void
|
||||
{
|
||||
foreach (['make:migration', 'make:command', 'make:controller'] as $command) {
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($command);
|
||||
|
||||
$this->assertFalse($verdict['allowed'], "접두사 차단이 적용되지 않음: {$command}");
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_DENIED, $verdict['reason']);
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Artisan — 확장 소유 명령 계층
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 게이트가 켜져 있으면 설치된 확장이 소유한 명령을 자동으로 허용한다.
|
||||
*
|
||||
* 이름 패턴이 아니라 등록된 명령 인스턴스의 클래스 네임스페이스로 판정하므로,
|
||||
* `{확장}:{작업}` 형태를 따르지 않는 확장 명령도 함께 허용된다.
|
||||
*
|
||||
* @scenario command_class=extension_owned, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects extension_owned_commands_are_allowed_by_namespace
|
||||
*/
|
||||
#[Test]
|
||||
public function it_allows_commands_owned_by_installed_extensions(): void
|
||||
{
|
||||
$command = $this->registerExtensionCommand();
|
||||
|
||||
$this->assertTrue(
|
||||
ScheduleCommandValidator::isArtisanCommandAllowed($command),
|
||||
"확장 소유 명령이 차단됨: {$command}"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 게이트를 끄면 확장 소유 명령도 거부된다 (설정으로 좁힐 수 있어야 한다).
|
||||
*
|
||||
* @scenario command_class=extension_owned, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects extension_gate_can_be_turned_off
|
||||
*/
|
||||
#[Test]
|
||||
public function it_blocks_extension_commands_when_the_gate_is_disabled(): void
|
||||
{
|
||||
$command = $this->registerExtensionCommand();
|
||||
|
||||
config(['schedule_security.artisan.allow_extension_commands' => false]);
|
||||
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($command);
|
||||
|
||||
$this->assertFalse($verdict['allowed'], "게이트를 껐는데 확장 명령이 통과함: {$command}");
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_NOT_ALLOWED, $verdict['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 소유 명령이라도 자기 정의에 없는 옵션은 거부한다.
|
||||
*
|
||||
* @scenario command_class=extension_owned, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects extension_commands_only_accept_their_own_options
|
||||
*/
|
||||
#[Test]
|
||||
public function it_blocks_undefined_options_on_extension_commands(): void
|
||||
{
|
||||
$command = $this->registerExtensionCommand();
|
||||
|
||||
$verdict = ScheduleCommandValidator::inspectArtisanCommand($command.' --g7-not-a-real-option');
|
||||
|
||||
$this->assertFalse($verdict['allowed']);
|
||||
$this->assertSame(ScheduleCommandValidator::ARTISAN_REASON_OPTION, $verdict['reason']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 네임스페이스를 비워도 코어 허용목록은 그대로 동작한다 (계층 독립성).
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects extension_gate_can_be_turned_off
|
||||
*/
|
||||
#[Test]
|
||||
public function it_keeps_core_allowlist_working_without_extension_namespaces(): void
|
||||
{
|
||||
config(['schedule_security.artisan.extension_namespaces' => []]);
|
||||
|
||||
$this->assertTrue(ScheduleCommandValidator::isArtisanCommandAllowed('cache:clear'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Artisan — config 불변식
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 허용목록과 차단목록은 겹치지 않아야 한다.
|
||||
*
|
||||
* 겹치면 거부권이 허용목록 항목을 조용히 무력화해, 설정만 보고는 무엇이 실행 가능한지
|
||||
* 알 수 없게 된다.
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects allowlist_and_denylist_stay_disjoint
|
||||
*/
|
||||
#[Test]
|
||||
public function it_keeps_the_allowlist_and_denylist_disjoint(): void
|
||||
{
|
||||
$allowlist = array_map('strtolower', array_keys((array) config('schedule_security.artisan.allowlist')));
|
||||
$denylist = array_map('strtolower', (array) config('schedule_security.artisan.denylist'));
|
||||
|
||||
$this->assertSame([], array_values(array_intersect($allowlist, $denylist)));
|
||||
|
||||
foreach ((array) config('schedule_security.artisan.denylist_prefixes') as $prefix) {
|
||||
foreach ($allowlist as $name) {
|
||||
$this->assertStringStartsNotWith(
|
||||
strtolower((string) $prefix),
|
||||
$name,
|
||||
"차단 접두사가 허용목록 항목을 무력화함: {$name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용목록의 명령과 옵션은 실제로 등록된 시그니처에 존재해야 한다.
|
||||
*
|
||||
* 오타나 시그니처 변경으로 허용 옵션이 실체와 어긋나면, 정상 운영 스케줄이
|
||||
* 저장 시점에 거부되거나 반대로 존재하지 않는 옵션이 허용된 것처럼 보인다.
|
||||
*
|
||||
* @scenario command_class=core_allowlisted, enforcement_point=validator_unit
|
||||
*
|
||||
* @effects allowlist_matches_real_command_signatures
|
||||
*/
|
||||
#[Test]
|
||||
public function it_keeps_the_allowlist_in_sync_with_real_command_signatures(): void
|
||||
{
|
||||
$registered = Artisan::all();
|
||||
|
||||
foreach ((array) config('schedule_security.artisan.allowlist') as $name => $spec) {
|
||||
$this->assertArrayHasKey($name, $registered, "허용목록에 없는 명령이 등재됨: {$name}");
|
||||
|
||||
$definition = $registered[$name]->getDefinition();
|
||||
|
||||
foreach ((array) ($spec['options'] ?? []) as $option) {
|
||||
$this->assertTrue(
|
||||
$definition->hasOption($option),
|
||||
"허용 옵션이 실제 시그니처에 없음: {$name} --{$option}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 소유 명령 계층 검증에 쓸 명령을 레지스트리에 등록하고 그 이름을 돌려줍니다.
|
||||
*
|
||||
* 설치된 확장 중 하나를 골라 쓰면 확장 구성에 따라 테스트가 조용히 skip 되어
|
||||
* 계층 자체가 검증되지 않는다. `Modules\` 네임스페이스의 픽스처를 실제 레지스트리에
|
||||
* 등록해 판정 결과를 고정한다 — 판정은 이름이 아니라 등록된 인스턴스의
|
||||
* 클래스 네임스페이스로 이뤄지므로 이 등록이 실제 확장과 동일한 경로를 탄다.
|
||||
*/
|
||||
private function registerExtensionCommand(): string
|
||||
{
|
||||
require_once __DIR__.'/../../Fixtures/Extension/FakeExtensionScheduleCommand.php';
|
||||
|
||||
$command = new FakeExtensionScheduleCommand;
|
||||
|
||||
Artisan::registerCommand($command);
|
||||
|
||||
return $command->getName();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Data Providers
|
||||
// ========================================================================
|
||||
@@ -259,6 +590,19 @@ class ScheduleCommandValidatorTest extends TestCase
|
||||
'env:decrypt' => ['env:decrypt'],
|
||||
'schedule:run' => ['schedule:run'],
|
||||
'빈 명령' => [''],
|
||||
// 보고서 2단계 체인 — 코드 생성 후 실행
|
||||
'make:migration — 접두사 차단' => ['make:migration evil --create=x --path=/tmp/g7 --realpath'],
|
||||
'migrate — 임의 경로 실행' => ['migrate --path=/tmp/g7 --realpath --force'],
|
||||
'db:seed — 임의 클래스 실행' => ['db:seed --class=Evil'],
|
||||
'test' => ['test'],
|
||||
'serve' => ['serve'],
|
||||
'core:update' => ['core:update'],
|
||||
'extension:composer-install' => ['extension:composer-install'],
|
||||
'playwright:issue-token' => ['playwright:issue-token'],
|
||||
'invoke-serialized-closure' => ['invoke-serialized-closure'],
|
||||
'stub:publish' => ['stub:publish'],
|
||||
'vendor:publish' => ['vendor:publish'],
|
||||
'migrate:refresh — 기존 목록 누락분' => ['migrate:refresh'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -273,6 +617,64 @@ class ScheduleCommandValidatorTest extends TestCase
|
||||
'cache:clear' => ['cache:clear'],
|
||||
'인자 포함' => ['queue:work --stop-when-empty'],
|
||||
'inspire' => ['inspire'],
|
||||
'optimize:clear' => ['optimize:clear'],
|
||||
'값 있는 옵션' => ['queue:prune-batches --hours=48'],
|
||||
'옵션 2개' => ['queue:work --stop-when-empty --max-time=300'],
|
||||
'seo:warmup --layout' => ['seo:warmup --layout=home'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 무해하지만 허용목록에 없어 거부되어야 하는 artisan command 목록.
|
||||
*
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function notAllowlistedArtisanCommandProvider(): array
|
||||
{
|
||||
return [
|
||||
'route:list — 정보 노출' => ['route:list'],
|
||||
'about — 환경 정보 노출' => ['about'],
|
||||
'queue:failed' => ['queue:failed'],
|
||||
'storage:link' => ['storage:link'],
|
||||
'schedule:list' => ['schedule:list'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증기와 Symfony 의 해석이 갈리는 command 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function parserDivergenceArtisanCommandProvider(): array
|
||||
{
|
||||
return [
|
||||
'큰따옴표 위장' => ['"tinker" --execute=1', 'tinker'],
|
||||
'작은따옴표 위장' => ["'tinker' --execute=1", 'tinker'],
|
||||
'백슬래시 위장' => ['tin\\ker --execute=1', 'tinker'],
|
||||
'선행 옵션으로 명령명 밀어내기' => ['--env=local tinker', 'tinker'],
|
||||
'선행 옵션 + 마이그레이션 체인' => ['--no-interaction migrate --path=/tmp/x --realpath', 'migrate'],
|
||||
'따옴표로 허용목록 위장' => ['"cache:clear" --execute=1', 'cache:clear'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용목록에 있으나 사용법이 거부되어야 하는 command 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function blockedOptionArtisanCommandProvider(): array
|
||||
{
|
||||
return [
|
||||
'미허용 옵션 (cache:clear --tags)' => ['cache:clear --tags=a', ScheduleCommandValidator::ARTISAN_REASON_OPTION],
|
||||
'워커 상주 (--daemon)' => ['queue:work --daemon', ScheduleCommandValidator::ARTISAN_REASON_OPTION],
|
||||
'안전장치 무력화 (--force)' => ['queue:work --force', ScheduleCommandValidator::ARTISAN_REASON_OPTION],
|
||||
'정의에 없는 옵션' => ['optimize:clear --whatever', ScheduleCommandValidator::ARTISAN_REASON_OPTION],
|
||||
'경로 지정 옵션 (model:prune --path)' => ['model:prune --path=/tmp/g7', ScheduleCommandValidator::ARTISAN_REASON_OPTION],
|
||||
'클래스 지정 옵션 (model:prune --model)' => ['model:prune --model=App\\\\Models\\\\User', ScheduleCommandValidator::ARTISAN_REASON_MALFORMED],
|
||||
'단축 옵션' => ['cache:clear -v', ScheduleCommandValidator::ARTISAN_REASON_MALFORMED],
|
||||
'위치 인자' => ['cache:clear redis', ScheduleCommandValidator::ARTISAN_REASON_ARGUMENT],
|
||||
'중복 옵션' => ['queue:work --tries=1 --tries=9', ScheduleCommandValidator::ARTISAN_REASON_MALFORMED],
|
||||
'옵션 구분자 단독' => ['cache:clear --', ScheduleCommandValidator::ARTISAN_REASON_MALFORMED],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user