From 19220039177960cd295d00177a9e822e56394c95 Mon Sep 17 00:00:00 2001 From: HeuJung Date: Mon, 13 Jul 2026 16:24:20 +0900 Subject: [PATCH] =?UTF-8?q?fix(installer):=20=EC=84=A4=EC=B9=98=20?= =?UTF-8?q?=EC=8B=9C=EC=9E=91=20=EC=A6=89=EC=8B=9C=20=EB=B9=88=20=EC=9D=91?= =?UTF-8?q?=EB=8B=B5=20=E2=80=94=20escapeEnvValue=20=EC=9E=AC=EC=84=A0?= =?UTF-8?q?=EC=96=B8=20fatal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 직전 커밋이 install-process.php 에 installer-runtime.php require 를 functions.php 앞에 추가하면서 발생한 회귀. installer-runtime.php 는 escapeEnvValue 를 function_exists 가드와 함께 polyfill 로 선언하는데, functions.php 는 같은 함수를 가드 없이 선언하고 있었다. 로드 순서가 뒤바뀌자 "Cannot redeclare escapeEnvValue" fatal 이 발생하고, JSON 이 출력되기 전에 스크립트가 죽어 응답 본문이 비었다. 브라우저의 res.json 이 이를 "Unexpected end of JSON input" 으로 보고해 설치 시작 즉시 실패했다 (SSE / 폴링 양 모드 — 둘 다 install-process.php 를 경유). 수정: - functions.php 의 escapeEnvValue 에 function_exists 가드 추가 (근본 방어 — require 순서만 되돌리면 다음 사람이 순서를 바꿀 때 재발한다) - install-process.php 의 require 순서를 다른 엔드포인트와 동일하게 정렬 인스톨러 전역 전수 스캔 결과 중복 선언 함수는 escapeEnvValue 하나뿐이며 이제 양쪽 모두 가드를 갖는다. 회귀 가드: InstallerIncludeOrderTest — 격리 프로세스로 로드 순서를 바꿔가며 fatal 부재 검증 + 중복 선언 함수의 가드 보유를 정적 검사 (수정 전 3/4 fail 확인). --- public/install/api/install-process.php | 6 +- public/install/includes/functions.php | 59 +++--- .../Installer/InstallerIncludeOrderTest.php | 175 ++++++++++++++++++ 3 files changed, 213 insertions(+), 27 deletions(-) create mode 100644 tests/Unit/Installer/InstallerIncludeOrderTest.php diff --git a/public/install/api/install-process.php b/public/install/api/install-process.php index 4d7e517a..03e8c8f3 100644 --- a/public/install/api/install-process.php +++ b/public/install/api/install-process.php @@ -15,8 +15,12 @@ require_once __DIR__.'/../includes/config.php'; require_once __DIR__.'/../includes/session.php'; require_once __DIR__.'/../includes/installer-state.php'; -require_once __DIR__.'/../includes/installer-runtime.php'; +// functions.php 를 installer-runtime.php 보다 먼저 로드한다 — 다른 인스톨러 +// 엔드포인트(finalize-env.php / task-runner.php)와 동일한 순서. +// installer-runtime.php 는 escapeEnvValue() 를 function_exists 가드와 함께 +// polyfill 로 선언하므로, functions.php 가 먼저 와야 그 가드가 제 역할을 한다. require_once __DIR__.'/../includes/functions.php'; +require_once __DIR__.'/../includes/installer-runtime.php'; require_once __DIR__.'/_guard.php'; installer_guard_or_410(); diff --git a/public/install/includes/functions.php b/public/install/includes/functions.php index 71c3a45c..9f27fbea 100644 --- a/public/install/includes/functions.php +++ b/public/install/includes/functions.php @@ -1031,33 +1031,40 @@ function loadLicenseFile(string $lang): string return lang('license_not_found'); } -/** - * .env 값 이스케이프 - * - * 특수 문자가 포함된 값을 .env 파일에 안전하게 기록할 수 있도록 큰따옴표로 감싸고 - * 내부 큰따옴표와 백슬래시를 이스케이프합니다. - * - * @param string $value 이스케이프할 값 - * @return string 큰따옴표로 감싸고 내부 큰따옴표와 백슬래시를 이스케이프한 값 - */ -function escapeEnvValue(string $value): string -{ - // 개행 문자는 .env 라인 구분자이므로 사용자 입력에 포함되면 추가 변수 라인이 주입될 수 있다. - // CR/LF 모두 제거 — DB 비밀번호·바이너리 경로·토큰 등 정상 값에는 개행이 들어갈 일이 없다. - if ($value !== '') { - $value = str_replace(["\r", "\n"], '', $value); +if (! function_exists('escapeEnvValue')) { + /** + * .env 값 이스케이프 + * + * 특수 문자가 포함된 값을 .env 파일에 안전하게 기록할 수 있도록 큰따옴표로 감싸고 + * 내부 큰따옴표와 백슬래시를 이스케이프합니다. + * + * installer-runtime.php 가 동일 함수를 polyfill 로 선언하므로 function_exists + * 가드가 필수다. 가드가 없으면 installer-runtime.php 가 functions.php 보다 먼저 + * 로드되는 엔드포인트(install-process.php)에서 "Cannot redeclare" fatal 이 발생해 + * JSON 응답이 통째로 유실된다 (설치 시작 즉시 실패). + * + * @param string $value 이스케이프할 값 + * @return string 큰따옴표로 감싸고 내부 큰따옴표와 백슬래시를 이스케이프한 값 + */ + function escapeEnvValue(string $value): string + { + // 개행 문자는 .env 라인 구분자이므로 사용자 입력에 포함되면 추가 변수 라인이 주입될 수 있다. + // CR/LF 모두 제거 — DB 비밀번호·바이너리 경로·토큰 등 정상 값에는 개행이 들어갈 일이 없다. + if ($value !== '') { + $value = str_replace(["\r", "\n"], '', $value); + } + + // 빈 값은 빈 따옴표로 + if ($value === '') { + return '""'; + } + + // 큰따옴표와 백슬래시를 이스케이프 + $escaped = str_replace(['\\', '"'], ['\\\\', '\\"'], $value); + + // 큰따옴표로 감싸기 + return '"'.$escaped.'"'; } - - // 빈 값은 빈 따옴표로 - if ($value === '') { - return '""'; - } - - // 큰따옴표와 백슬래시를 이스케이프 - $escaped = str_replace(['\\', '"'], ['\\\\', '\\"'], $value); - - // 큰따옴표로 감싸기 - return '"'.$escaped.'"'; } /** diff --git a/tests/Unit/Installer/InstallerIncludeOrderTest.php b/tests/Unit/Installer/InstallerIncludeOrderTest.php new file mode 100644 index 00000000..949ebfe5 --- /dev/null +++ b/tests/Unit/Installer/InstallerIncludeOrderTest.php @@ -0,0 +1,175 @@ +projectRoot = dirname(__DIR__, 3); + } + + /** + * 인스톨러 include 파일 2개를 지정한 순서로 로드하는 격리 PHP 프로세스 실행. + * + * @param array $relativeIncludes BASE_PATH 기준 상대 경로 목록 + * @return array{exitCode:int, output:string} + */ + private function loadInIsolatedProcess(array $relativeIncludes): array + { + $root = str_replace('\\', '/', $this->projectRoot); + + $lines = ['error_reporting(E_ALL);', "define('BASE_PATH', '{$root}');"]; + foreach ($relativeIncludes as $include) { + $lines[] = "require_once '{$root}/{$include}';"; + } + $lines[] = "echo 'LOAD_OK';"; + + $code = implode("\n", $lines); + + $descriptors = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']]; + $process = proc_open([PHP_BINARY, '-r', $code], $descriptors, $pipes); + + $this->assertIsResource($process, 'PHP 하위 프로세스를 띄우지 못함'); + + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $exitCode = proc_close($process); + + return ['exitCode' => $exitCode, 'output' => $stdout.$stderr]; + } + + /** + * 회귀 재현 — installer-runtime.php 를 functions.php 보다 먼저 로드. + * + * 이 순서가 곧 install-process.php 의 require 순서였고, escapeEnvValue() + * 재선언 fatal 로 빈 응답이 발생했다. + */ + public function test_runtime_before_functions_does_not_fatal(): void + { + $result = $this->loadInIsolatedProcess([ + 'public/install/includes/installer-runtime.php', + 'public/install/includes/functions.php', + ]); + + $this->assertStringNotContainsString( + 'Cannot redeclare', + $result['output'], + 'installer-runtime.php 를 functions.php 보다 먼저 로드하면 함수 재선언 fatal 이 발생한다. ' + .'중복 선언되는 함수에 function_exists 가드가 필요하다.', + ); + $this->assertStringContainsString('LOAD_OK', $result['output'], '두 파일 로드가 완료되어야 함'); + $this->assertSame(0, $result['exitCode'], 'fatal 없이 정상 종료해야 함'); + } + + /** + * 기존 순서(functions.php 먼저) 도 계속 동작해야 한다 — 회귀 방지. + * + * finalize-env.php / task-runner.php 가 이 순서를 사용한다. + */ + public function test_functions_before_runtime_does_not_fatal(): void + { + $result = $this->loadInIsolatedProcess([ + 'public/install/includes/functions.php', + 'public/install/includes/installer-runtime.php', + ]); + + $this->assertStringNotContainsString('Cannot redeclare', $result['output']); + $this->assertStringContainsString('LOAD_OK', $result['output']); + $this->assertSame(0, $result['exitCode']); + } + + /** + * install-process.php 의 실제 require 순서를 그대로 재현. + * + * 이 엔드포인트가 SSE / 폴링 양 모드의 공통 시작점이므로, 여기서 fatal 이 나면 + * 두 모드 모두 설치 시작 즉시 실패한다. + */ + public function test_install_process_require_chain_does_not_fatal(): void + { + $result = $this->loadInIsolatedProcess([ + 'public/install/includes/config.php', + 'public/install/includes/installer-state.php', + 'public/install/includes/installer-runtime.php', + 'public/install/includes/functions.php', + ]); + + $this->assertStringNotContainsString( + 'Cannot redeclare', + $result['output'], + 'install-process.php 의 require 체인에서 재선언 fatal 발생 — ' + .'설치 시작 API 가 빈 응답을 반환하여 "Unexpected end of JSON input" 이 된다', + ); + $this->assertSame(0, $result['exitCode']); + } + + /** + * installer-runtime.php 가 polyfill 로 선언하는 함수는 functions.php 에서도 + * function_exists 가드를 가져야 한다 — 정적 계약 검사. + * + * 앞으로 두 파일에 중복 함수가 새로 추가되어도 가드 없이는 통과하지 못한다. + */ + public function test_functions_shared_with_runtime_are_all_guarded(): void + { + $functionsPath = $this->projectRoot.'/public/install/includes/functions.php'; + $runtimePath = $this->projectRoot.'/public/install/includes/installer-runtime.php'; + + $functionsSource = (string) file_get_contents($functionsPath); + $runtimeSource = (string) file_get_contents($runtimePath); + + // installer-runtime.php 가 선언하는 함수 목록 추출 + preg_match_all('/^\s*function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/m', $runtimeSource, $m); + $runtimeFunctions = array_unique($m[1]); + + $this->assertNotEmpty($runtimeFunctions, 'installer-runtime.php 에서 함수를 하나도 못 찾음 — 추출 정규식 점검 필요'); + + foreach ($runtimeFunctions as $fn) { + // functions.php 에도 같은 함수가 선언되어 있는가? + if (! preg_match('/^\s*function\s+'.preg_quote($fn, '/').'\s*\(/m', $functionsSource)) { + continue; // 중복 아님 — 안전 + } + + // 중복이라면 functions.php 쪽에 function_exists 가드가 있어야 한다 + $this->assertMatchesRegularExpression( + "/function_exists\(\s*['\"]".preg_quote($fn, '/')."['\"]\s*\)/", + $functionsSource, + "functions.php 의 {$fn}() 이 installer-runtime.php 와 중복 선언되는데 " + ."function_exists 가드가 없다. 로드 순서에 따라 'Cannot redeclare' fatal 이 발생한다.", + ); + } + } +}