fix(installer): 설치 상태 파일에 관리자 비밀번호가 평문으로 잔존하는 문제

비밀을 state.json(0664, 실패 시 무기한 잔존)에 기록하지 않고
runtime.php(0600, finalize 시 삭제)로 채널을 일원화한다.

정상 완료 경로에서는 finalize 가 state.json 을 삭제하지만, finalize
미호출 / unlink 실패 / 설치 중단 시에는 평문이 영구히 남았고, finalize
가드가 재호출을 410 차단해 자가 회복도 불가능했다. 삭제라는 단일 경로에
의존해 평문을 보호하던 구조 자체를 제거한다.

SSE 워커는 세션에 접근할 수 없어 파일 경유가 불가피한데, 그 파일이 0664 의
state.json 이었던 것이 구조적 원인이다. 세션을 보유한 유일한 공통 시작점인
install-process.php 를 비밀 이송 지점으로 삼고, db_seed 가 소비한 즉시
제거한다. 레거시 / 실패 경로는 완료·중단·초기화·finalize 시점 redact 로 방어.

동반 수정:
- 세션 config 재병합으로 무력화되던 기존 DB 비밀번호 마스킹 복구
- db_seed 후 putenv 미해제로 모든 exec 자식에 평문이 ENV 상속되던 누출 차단
- runtime read 비밀번호 폴백이 write 값으로 잘못 대체되던 문제 ( 인접)

이미 설치된 사이트는 7.0.4 업그레이드 스텝이 잔존 파일을 정리한다.
완료 증거가 있으면 삭제하고, 설치 진행 중일 수 있으면 비밀만 제거한다.
This commit is contained in:
HeuJung committed 2026-07-13 17:00:59 +09:00
1 parent ae447c9cc4
commit 9be8faaea2
16 files changed
+1534 -119

No files matched your search

@@ -0,0 +1,357 @@
<?php
namespace Tests\Feature\Upgrade;
use App\Extension\UpgradeContext;
use App\Upgrades\Data\V7_0_4\Migrations\RedactResidualInstallerStateSecrets;
use Tests\TestCase;
/**
* 7.0.4 잔존 installer-state.json 비밀 정리 회귀 가드 (이슈 #465).
*
* axis 전수:
* 1. state.json 부재 → no-op
* 2. 완료 증거(.env INSTALLER_COMPLETED=true) + state 존재 → 파일 삭제
* 3. 완료 증거(g7_installed 플래그) + state 존재 → 파일 삭제
* 4. 완료 증거 있음 + 삭제 불가 → redact 폴백 (파일 보존, 비밀만 제거)
* 5. 완료 증거 없음 → 파일 보존 + redact 만 (설치 진행 중 파괴 금지)
* 6. JSON 파싱 실패 → 파일 원본 그대로 보존
* 7. 멱등 — 2회 호출해도 동일 결과
*/
class RedactResidualInstallerStateSecretsTest extends TestCase
{
private string $statePath;
private string $envPath;
private string $installedFlagPath;
private bool $originalEnvExisted = false;
private ?string $originalEnvContent = null;
private bool $originalStateExisted = false;
private ?string $originalStateContent = null;
private bool $originalFlagExisted = false;
private ?string $originalFlagContent = null;
protected function setUp(): void
{
parent::setUp();
$this->statePath = base_path('storage/installer-state.json');
$this->envPath = base_path('.env');
$this->installedFlagPath = base_path('storage/app/g7_installed');
// 실 운영 아티팩트 백업 — 본 테스트가 삭제/변조하므로 tearDown 에서 정확히 복원
if (is_file($this->envPath)) {
$this->originalEnvExisted = true;
$this->originalEnvContent = file_get_contents($this->envPath);
}
if (is_file($this->statePath)) {
$this->originalStateExisted = true;
$this->originalStateContent = file_get_contents($this->statePath);
}
if (is_file($this->installedFlagPath)) {
$this->originalFlagExisted = true;
$this->originalFlagContent = file_get_contents($this->installedFlagPath);
}
// DataMigration 은 autoload 대상이 아님 — 동적 require
require_once base_path('upgrades/data/7.0.4/migrations/01_RedactResidualInstallerStateSecrets.php');
$this->clearArtifacts();
}
protected function tearDown(): void
{
$this->clearArtifacts();
if ($this->originalEnvExisted && $this->originalEnvContent !== null) {
file_put_contents($this->envPath, $this->originalEnvContent);
}
if ($this->originalStateExisted && $this->originalStateContent !== null) {
file_put_contents($this->statePath, $this->originalStateContent);
}
if ($this->originalFlagExisted && $this->originalFlagContent !== null) {
file_put_contents($this->installedFlagPath, $this->originalFlagContent);
}
parent::tearDown();
}
/**
* 각 axis 가 완료 증거를 명시 제어할 수 있도록 세 아티팩트를 모두 제거한다.
*/
private function clearArtifacts(): void
{
if (is_file($this->statePath)) {
// axis 4 가 파일을 0444 로 만들 수 있다 — 단언 실패로 조기 종료된 경우에도
// 정리가 가능하도록 권한을 먼저 되돌린다.
@chmod($this->statePath, 0644);
@unlink($this->statePath);
}
if (is_file($this->installedFlagPath)) {
@unlink($this->installedFlagPath);
}
if (is_file($this->envPath)) {
@unlink($this->envPath);
}
}
private function context(): UpgradeContext
{
return new UpgradeContext('7.0.3', '7.0.4', '7.0.4');
}
private function migration(): RedactResidualInstallerStateSecrets
{
return new RedactResidualInstallerStateSecrets;
}
/**
* 평문 비밀이 들어 있는 레거시 state.json (7.0.3 이하 인스톨러가 남긴 형태).
*
* @return array<string, mixed>
*/
private function legacyState(): array
{
return [
'installation_status' => 'completed',
'current_step' => 5,
'completed_tasks' => ['db_migrate', 'db_seed', 'complete_flag'],
'config' => [
'app_name' => 'G7 Site',
'db_write_host' => '127.0.0.1',
'db_write_database' => 'g7',
'db_write_username' => 'root',
'db_write_password' => 'db-plain-pw',
'db_read_password' => 'read-plain-pw',
'admin_email' => 'admin@example.com',
'admin_password' => 'admin-plain-pw',
'admin_password_confirm' => 'admin-plain-pw',
],
];
}
private function writeState(array $state): void
{
file_put_contents($this->statePath, json_encode($state, JSON_PRETTY_PRINT));
}
private function markInstalledViaEnv(): void
{
file_put_contents($this->envPath, "APP_ENV=production\nINSTALLER_COMPLETED=true\n");
}
private function markInstalledViaFlag(): void
{
$dir = dirname($this->installedFlagPath);
if (! is_dir($dir)) {
mkdir($dir, 0775, true);
}
file_put_contents($this->installedFlagPath, date('Y-m-d H:i:s'));
}
/**
* @return array<string, mixed>
*/
private function readState(): array
{
return json_decode((string) file_get_contents($this->statePath), true);
}
private function assertNoPlaintextSecrets(array $config): void
{
foreach (['db_write_password', 'db_read_password', 'admin_password', 'admin_password_confirm'] as $key) {
$this->assertArrayNotHasKey($key, $config, "{$key} 가 state 에 남으면 안 됨");
}
}
// -----------------------------------------------------------------------
// axis 1: state.json 부재 → no-op
// -----------------------------------------------------------------------
public function test_no_op_when_state_file_absent(): void
{
$this->assertFileDoesNotExist($this->statePath);
$this->migration()->run($this->context());
$this->assertFileDoesNotExist($this->statePath);
}
// -----------------------------------------------------------------------
// axis 2: 완료 증거(.env) + state 존재 → 파일 삭제
// -----------------------------------------------------------------------
public function test_deletes_state_file_when_env_marks_installation_complete(): void
{
$this->writeState($this->legacyState());
$this->markInstalledViaEnv();
$this->migration()->run($this->context());
$this->assertFileDoesNotExist($this->statePath, '설치 완료 환경의 잔존 state.json 은 삭제되어야 함');
}
// -----------------------------------------------------------------------
// axis 3: 완료 증거(g7_installed) + state 존재 → 파일 삭제
// -----------------------------------------------------------------------
public function test_deletes_state_file_when_installed_flag_present(): void
{
$this->writeState($this->legacyState());
$this->markInstalledViaFlag();
// .env 는 없음 — g7_installed 단독 신호로도 완료 판정되어야 함
$this->migration()->run($this->context());
$this->assertFileDoesNotExist($this->statePath);
}
// -----------------------------------------------------------------------
// axis 4: 완료 증거 있음 + 삭제 불가 → 예외 없이 계속 진행 (업그레이드 중단 금지)
//
// 파일을 읽기 전용으로 만들어 unlink 를 실제로 실패시킨다. 이 상태에서는
// redact 재저장(file_put_contents) 도 함께 실패하므로 평문 제거는 불가능하다 —
// 파일시스템 레벨 제약이라 코드로 우회할 수 없다. 본 axis 가 고정하는 계약은
// "업그레이드가 중단되지 않고, 파일이 손상되지 않으며, 운영자가 수동 삭제할 수
// 있도록 원본이 보존된다" 이다 (경고 로그는 runInternal 이 기록).
// -----------------------------------------------------------------------
public function test_does_not_abort_upgrade_when_state_file_cannot_be_deleted(): void
{
$original = $this->legacyState();
$this->writeState($original);
$this->markInstalledViaEnv();
$before = file_get_contents($this->statePath);
// 이 환경에서 읽기 전용 파일의 삭제가 실제로 차단되는지 실측 (POSIX 는 삭제 권한이
// 부모 디렉토리 소유라 차단되지 않을 수 있다 — 그 경우 본 axis 는 재현 불가).
if (! $this->unlinkIsBlocked()) {
$this->markTestSkipped(
'이 플랫폼에서는 읽기 전용 파일의 unlink 가 차단되지 않아 삭제 실패 경로를 '
.'결정적으로 재현할 수 없음 (POSIX: 삭제 권한은 부모 디렉토리 소유)'
);
}
@chmod($this->statePath, 0444);
// 예외를 던지지 않아야 한다 (업그레이드 전체 중단 금지)
$this->migration()->run($this->context());
$this->assertFileExists($this->statePath, '삭제 실패 시 파일은 보존되어야 함');
$this->assertSame($before, file_get_contents($this->statePath), '삭제 실패 시 파일이 손상되면 안 됨');
@chmod($this->statePath, 0644);
}
/**
* 현재 플랫폼에서 읽기 전용 파일의 unlink 가 차단되는지 실측한다.
*/
private function unlinkIsBlocked(): bool
{
$probe = base_path('storage/installer-state-unlink-probe.tmp');
file_put_contents($probe, 'x');
@chmod($probe, 0444);
$blocked = @unlink($probe) === false;
@chmod($probe, 0644);
if (is_file($probe)) {
@unlink($probe);
}
return $blocked;
}
// -----------------------------------------------------------------------
// axis 5: 완료 증거 없음 → 파일 보존 + redact 만
// -----------------------------------------------------------------------
public function test_redacts_but_preserves_file_when_installation_not_complete(): void
{
$state = $this->legacyState();
$state['installation_status'] = 'running'; // 설치 진행 중
$this->writeState($state);
// 완료 증거 없음 (.env / g7_installed 모두 부재)
$this->migration()->run($this->context());
$this->assertFileExists($this->statePath, '진행 중인 설치의 state.json 을 삭제하면 안 됨');
$after = $this->readState();
$this->assertNoPlaintextSecrets($after['config']);
// 비-비밀 필드는 보존되어야 설치를 이어갈 수 있다
$this->assertSame('G7 Site', $after['config']['app_name']);
$this->assertSame('127.0.0.1', $after['config']['db_write_host']);
$this->assertSame('root', $after['config']['db_write_username']);
$this->assertSame('admin@example.com', $after['config']['admin_email']);
$this->assertSame(['db_migrate', 'db_seed', 'complete_flag'], $after['completed_tasks']);
$this->assertSame('running', $after['installation_status']);
}
// -----------------------------------------------------------------------
// axis 6: JSON 파싱 실패 → 파일 원본 보존 (파괴 금지)
// -----------------------------------------------------------------------
public function test_preserves_corrupted_state_file(): void
{
$corrupted = '{ this is not valid json';
file_put_contents($this->statePath, $corrupted);
$this->markInstalledViaEnv();
$this->migration()->run($this->context());
$this->assertFileExists($this->statePath, '파싱 실패 파일을 삭제하면 안 됨');
$this->assertSame($corrupted, file_get_contents($this->statePath));
}
// -----------------------------------------------------------------------
// axis 7: 멱등 — 2회 호출해도 동일 결과
// -----------------------------------------------------------------------
public function test_is_idempotent_on_repeated_runs(): void
{
$state = $this->legacyState();
$state['installation_status'] = 'aborted';
$this->writeState($state);
$this->migration()->run($this->context());
$firstPass = file_get_contents($this->statePath);
$this->migration()->run($this->context());
$secondPass = file_get_contents($this->statePath);
$this->assertSame($firstPass, $secondPass, '재실행이 파일을 추가로 변경하면 안 됨');
$this->assertNoPlaintextSecrets($this->readState()['config']);
}
// -----------------------------------------------------------------------
// 삭제 경로 멱등 — 완료 환경에서 2회 호출
// -----------------------------------------------------------------------
public function test_delete_path_is_idempotent(): void
{
$this->writeState($this->legacyState());
$this->markInstalledViaEnv();
$this->migration()->run($this->context());
$this->assertFileDoesNotExist($this->statePath);
// 2회차 — 파일 부재 상태에서 예외 없이 no-op
$this->migration()->run($this->context());
$this->assertFileDoesNotExist($this->statePath);
}
// -----------------------------------------------------------------------
// config 섹션 없는 state → 예외 없이 통과
// -----------------------------------------------------------------------
public function test_handles_state_without_config_section(): void
{
$this->writeState(['installation_status' => 'running', 'completed_tasks' => []]);
$this->migration()->run($this->context());
$this->assertFileExists($this->statePath);
$this->assertSame('running', $this->readState()['installation_status']);
}
}
@@ -408,6 +408,35 @@ ENV;
$this->assertStringContainsString('DB_WRITE_HOST=user-input.com', $merged);
}
/**
* 이슈 #465 불변식 — runtime.php 의 admin 섹션은 절대 `.env` 로 새어나가지 않는다.
*
* mergeRuntimeIntoEnv 는 db/app.key 만 명시 치환하는 화이트리스트 방식이다.
* 이후 누군가 "runtime 배열을 통째로 .env 로 덤프" 하는 방식으로 리팩터링하면
* 관리자 평문 비밀번호가 .env 에 영구 기록되므로, 그 회귀를 여기서 차단한다.
*/
public function test_merge_runtime_into_env_never_writes_admin_section(): void
{
$envContent = "APP_KEY=\nDB_WRITE_PASSWORD=\n";
$runtime = [
'db' => [
'write' => ['host' => 'h', 'port' => '3306', 'database' => 'd', 'username' => 'u', 'password' => 'dbpw'],
],
'app' => ['key' => 'base64:'.base64_encode(str_repeat('k', 32))],
'admin' => ['password' => 'super-secret-admin-pw'],
];
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
$this->assertStringNotContainsString('super-secret-admin-pw', $merged, '관리자 평문이 .env 로 유출되면 안 됨');
$this->assertStringNotContainsString('ADMIN', $merged, 'ADMIN 계열 키가 .env 에 기록되면 안 됨');
// db/app.key 는 정상 기록 (화이트리스트가 좁아지지 않았음을 함께 고정)
$this->assertStringContainsString('DB_WRITE_PASSWORD="dbpw"', $merged);
$this->assertStringContainsString('APP_KEY=base64:', $merged);
}
public function test_merge_escapes_password_with_special_characters(): void
{
$envContent = "DB_WRITE_PASSWORD=\n";
@@ -0,0 +1,327 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\TestCase;
/**
* 인스톨러 state.json 비밀 잔존 결함 회귀 테스트 (이슈 #465)
*
* 결함: 설치 후 storage/installer-state.json 에 admin_password /
* admin_password_confirm 이 평문으로 남았다.
*
* 수정 설계: 비밀은 state.json 에 아예 기록하지 않고 runtime.php(0600) 로
* 일원화한다. 본 테스트는 그 계약을 고정한다.
*
* - sanitizeConfigForState() — state 저장 직전 비밀 4종 제거
* - redactInstallationStateSecrets() — 레거시 state 정리
* - buildInstallerRuntimeFromState() — state 결손 시 기존 runtime 값 보존
* - hydrateDbSecretsFromRuntime() — DB 비밀번호 소비처 폴백
*
* @see https://github.com/gnuboard/dev-g7/issues/465
*/
class InstallerStateSecretsTest extends TestCase
{
private string $skipReason = '';
protected function setUp(): void
{
parent::setUp();
$tempBase = sys_get_temp_dir().'/g7-installer-secrets-'.bin2hex(random_bytes(4));
// 안전 가드: BASE_PATH / INSTALLER_RUNTIME_PATH 는 PHP 상수라 프로세스당 1회만
// 정의된다. 다른 Installer 테스트가 먼저 프로젝트 루트로 BASE_PATH 를 정의하면
// 본 테스트의 writeInstallerRuntime/tearDown 이 실제 운영 runtime.php 를
// (DB 자격증명 보관 파일) 파괴한다. temp 하위가 아니면 skip.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
$this->skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '
.'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 storage/installer/runtime.php '
.'파괴 방지를 위해 skip. 격리 실행: php vendor/bin/phpunit --filter=InstallerStateSecretsTest';
$this->markTestSkipped($this->skipReason);
}
$tempBase = (string) BASE_PATH;
} else {
define('BASE_PATH', $tempBase);
}
if (! is_dir($tempBase.'/storage/installer')) {
@mkdir($tempBase.'/storage/installer', 0755, true);
}
require_once dirname(__DIR__, 3).'/public/install/includes/installer-state.php';
require_once dirname(__DIR__, 3).'/public/install/includes/installer-runtime.php';
}
protected function tearDown(): void
{
if ($this->skipReason === '' && defined('INSTALLER_RUNTIME_PATH') && is_file(INSTALLER_RUNTIME_PATH)) {
@unlink(INSTALLER_RUNTIME_PATH);
}
parent::tearDown();
}
// -----------------------------------------------------------------
// sanitizeConfigForState
// -----------------------------------------------------------------
public function test_sanitize_config_for_state_removes_all_four_secrets(): void
{
$config = [
'app_name' => 'G7 Site',
'db_write_host' => 'localhost',
'db_write_username' => 'root',
'db_write_password' => 'db-secret',
'db_read_password' => 'read-secret',
'use_read_db' => true,
'db_read_host' => 'read-host',
'admin_email' => 'admin@example.com',
'admin_password' => 'plain-admin-pw',
'admin_password_confirm' => 'plain-admin-pw',
];
$safe = sanitizeConfigForState($config);
foreach (installerSecretConfigKeys() as $secretKey) {
$this->assertArrayNotHasKey($secretKey, $safe, "{$secretKey} 가 state 로 유출되면 안 됨");
}
// 비-비밀 키는 보존
$this->assertSame('G7 Site', $safe['app_name']);
$this->assertSame('localhost', $safe['db_write_host']);
$this->assertSame('root', $safe['db_write_username']);
$this->assertSame('admin@example.com', $safe['admin_email']);
// use_read_db=true 이므로 read 필드 보존
$this->assertSame('read-host', $safe['db_read_host']);
}
public function test_installer_secret_config_keys_covers_four_secrets(): void
{
$keys = installerSecretConfigKeys();
$this->assertEqualsCanonicalizing(
['db_write_password', 'db_read_password', 'admin_password', 'admin_password_confirm'],
$keys,
);
}
/**
* 이슈 #63 기존 동작 보존 — use_read_db=false 이면 read 접속 필드 잔존값 제거.
*/
public function test_sanitize_config_for_state_drops_read_fields_when_use_read_db_false(): void
{
$config = [
'use_read_db' => false,
'db_write_host' => 'mysql',
'db_read_host' => 'stale-host',
'db_read_port' => '3307',
'db_read_database' => 'stale_db',
'db_read_username' => 'stale_user',
'db_read_password' => 'stale_pw',
];
$safe = sanitizeConfigForState($config);
$this->assertArrayNotHasKey('db_read_host', $safe);
$this->assertArrayNotHasKey('db_read_port', $safe);
$this->assertArrayNotHasKey('db_read_database', $safe);
$this->assertArrayNotHasKey('db_read_username', $safe);
$this->assertArrayNotHasKey('db_read_password', $safe);
$this->assertSame('mysql', $safe['db_write_host']);
}
// -----------------------------------------------------------------
// redactInstallationStateSecrets
// -----------------------------------------------------------------
public function test_redact_installation_state_secrets_strips_config_secrets(): void
{
$state = [
'installation_status' => 'completed',
'completed_tasks' => ['db_migrate', 'db_seed'],
'config' => [
'app_name' => 'G7',
'admin_password' => 'plain',
'admin_password_confirm' => 'plain',
'db_write_password' => 'dbpw',
'db_read_password' => 'rdpw',
],
];
$redacted = redactInstallationStateSecrets($state);
$this->assertArrayNotHasKey('admin_password', $redacted['config']);
$this->assertArrayNotHasKey('admin_password_confirm', $redacted['config']);
$this->assertArrayNotHasKey('db_write_password', $redacted['config']);
$this->assertArrayNotHasKey('db_read_password', $redacted['config']);
// 비밀이 아닌 것은 불변
$this->assertSame('G7', $redacted['config']['app_name']);
$this->assertSame('completed', $redacted['installation_status']);
$this->assertSame(['db_migrate', 'db_seed'], $redacted['completed_tasks']);
}
public function test_redact_installation_state_secrets_is_noop_without_config(): void
{
$state = ['installation_status' => 'running', 'completed_tasks' => []];
$this->assertSame($state, redactInstallationStateSecrets($state));
}
/**
* redact 는 use_read_db 정리를 수행하지 않는다 — 이미 기록된 state 의 접속
* 정보(비밀 아님)를 지우면 롤백/cleanup 이 깨진다. 비밀 4종만 제거.
*/
public function test_redact_preserves_non_secret_db_fields(): void
{
$state = [
'config' => [
'use_read_db' => false,
'db_read_host' => 'leftover',
'db_write_password' => 'x',
],
];
$redacted = redactInstallationStateSecrets($state);
$this->assertArrayNotHasKey('db_write_password', $redacted['config']);
$this->assertSame('leftover', $redacted['config']['db_read_host']);
}
// -----------------------------------------------------------------
// buildInstallerRuntimeFromState — 결손 폴백
// -----------------------------------------------------------------
public function test_build_runtime_carries_admin_password_when_provided_by_caller(): void
{
// 호출자(install-process.php) 가 세션 비밀번호를 넣는 정상 경로는 admin 섹션을
// 직접 대입한다. 본 테스트는 그 섹션이 기존 runtime 에 있을 때 보존되는지 확인.
writeInstallerRuntime([
'app' => ['key' => generateAppKeyInline()],
'admin' => ['password' => 'kept-admin-pw'],
]);
$built = buildInstallerRuntimeFromState([
'db_write_host' => 'localhost',
'db_write_database' => 'g7',
'db_write_username' => 'root',
]);
$this->assertSame('kept-admin-pw', $built['admin']['password'] ?? null);
}
public function test_build_runtime_preserves_existing_db_password_when_state_config_lacks_it(): void
{
writeInstallerRuntime([
'db' => [
'write' => [
'host' => 'localhost',
'port' => '3306',
'database' => 'g7',
'username' => 'root',
'password' => 'existing-write-pw',
],
],
'app' => ['key' => generateAppKeyInline()],
]);
// state.config 에는 비밀번호가 없다 (sanitize 로 제거됨)
$built = buildInstallerRuntimeFromState([
'db_write_host' => 'localhost',
'db_write_database' => 'g7',
'db_write_username' => 'root',
]);
$this->assertSame('existing-write-pw', $built['db']['write']['password']);
}
public function test_build_runtime_read_password_falls_back_to_existing_runtime_not_write_password(): void
{
writeInstallerRuntime([
'db' => [
'write' => ['host' => 'w-host', 'database' => 'g7', 'username' => 'wu', 'password' => 'write-pw'],
'read' => ['host' => 'r-host', 'database' => 'g7r', 'username' => 'ru', 'password' => 'read-pw'],
],
'app' => ['key' => generateAppKeyInline()],
]);
$built = buildInstallerRuntimeFromState([
'use_read_db' => true,
'db_write_host' => 'w-host',
'db_write_database' => 'g7',
'db_write_username' => 'wu',
'db_read_host' => 'r-host',
'db_read_database' => 'g7r',
'db_read_username' => 'ru',
// db_read_password / db_write_password 는 state 에 없음
]);
$this->assertSame('read-pw', $built['db']['read']['password'], 'read 비밀번호가 write 값으로 대체되면 안 됨');
$this->assertSame('write-pw', $built['db']['write']['password']);
}
public function test_build_runtime_keeps_state_config_password_when_present(): void
{
// 세션이 살아있는 정상 경로 — state 가 아닌 호출자가 넘긴 config 에 비밀번호가
// 있으면 그것이 우선한다 (기존 동작 보존).
writeInstallerRuntime([
'db' => ['write' => ['password' => 'old-pw']],
'app' => ['key' => generateAppKeyInline()],
]);
$built = buildInstallerRuntimeFromState([
'db_write_host' => 'localhost',
'db_write_password' => 'new-pw',
]);
$this->assertSame('new-pw', $built['db']['write']['password']);
}
// -----------------------------------------------------------------
// hydrateDbSecretsFromRuntime
// -----------------------------------------------------------------
public function test_hydrate_db_secrets_from_runtime_fills_empty_passwords(): void
{
writeInstallerRuntime([
'db' => [
'write' => ['password' => 'rt-write-pw'],
'read' => ['password' => 'rt-read-pw'],
],
]);
$config = [
'db_write_host' => 'localhost',
'db_write_username' => 'root',
];
$hydrated = hydrateDbSecretsFromRuntime($config);
$this->assertSame('rt-write-pw', $hydrated['db_write_password']);
$this->assertSame('rt-read-pw', $hydrated['db_read_password']);
$this->assertSame('localhost', $hydrated['db_write_host']);
}
public function test_hydrate_db_secrets_does_not_override_existing_password(): void
{
writeInstallerRuntime(['db' => ['write' => ['password' => 'rt-pw']]]);
$hydrated = hydrateDbSecretsFromRuntime(['db_write_password' => 'session-pw']);
$this->assertSame('session-pw', $hydrated['db_write_password']);
}
public function test_hydrate_db_secrets_returns_config_unchanged_when_runtime_absent(): void
{
@unlink(INSTALLER_RUNTIME_PATH);
$config = ['db_write_host' => 'localhost'];
$this->assertSame($config, hydrateDbSecretsFromRuntime($config));
}
}
@@ -0,0 +1,153 @@
# audit:allow test-scenario-coverage reason: 인스톨러 비밀 수명주기의 시나리오 매트릭스 SSoT. 회귀 가드는 test_files 의 통과 테스트 + Manual 시나리오(실제 설치 2회 + storage grep) 로 커버.
feature: 인스톨러 비밀 수명주기 (state.json 평문 제거 → runtime.php 일원화)
description: |
설치 과정에서 입력받는 비밀(DB 비밀번호 2종, 관리자 비밀번호 2종) 이
storage/installer-state.json 에 평문으로 기록되어, 설치 실패/중단/finalize 미호출
환경에서 무기한 잔존하던 결함을 수정한다 (이슈 #465).
설계:
- state.json(0664, 실패 시 무기한 잔존) 에는 비밀을 아예 기록하지 않는다.
- 비밀 채널은 storage/installer/runtime.php(0600, finalize 시 삭제) 로 일원화.
SSE 워커는 세션 접근이 불가하므로 파일 경유가 불가피하며, 세션을 보유한 유일한
공통 시작점인 install-process.php 가 이송 지점이다 (SSE/폴링 공통, 재시도 포함).
- 관리자 비밀번호는 db_seed 가 소비한 즉시 runtime 에서 제거 + putenv 해제
(해제하지 않으면 이후 모든 exec() 자식이 평문을 ENV 상속).
- 레거시/실패 경로 방어: 완료·중단·초기화·finalize 시점 redact 폴백.
- 이미 설치된 사이트는 7.0.4 업그레이드 스텝이 잔존 파일을 정리.
구조적 제약:
state.config 에서 DB 비밀번호가 사라지므로 그 값을 읽던 소비처(db_cleanup /
롤백 seed truncate) 는 hydrateDbSecretsFromRuntime() 으로 자격증명을 복원한다.
두 소비처 모두 env_update 이후에만 실행되어 runtime.php 가 항상 존재한다.
axes:
installation_mode: [sse, polling]
session_state: [alive, lost_after_step3]
retry_kind: [none, resume_after_failure, drop_tables_reconsent]
runtime_state: [absent, present_with_db_only, present_with_db_and_admin]
seed_outcome: [not_reached, success, failure]
completion_path: [normal_finalize, finalize_unlink_failed, finalize_not_called, aborted, reset]
read_db: [disabled, enabled_separate_host]
legacy_state: [clean, has_plaintext_secrets_from_7_0_3_or_earlier]
upgrade_trigger: [not_applicable, state_present_installed, state_present_not_installed, state_absent, state_corrupted]
exclusions:
- { seed_outcome: not_reached, runtime_state: absent, reason: "env_update 이전 실패 — runtime 미생성이 정상" }
- { session_state: lost_after_step3, runtime_state: absent, retry_kind: resume_after_failure, reason: "세션+runtime 동시 유실은 재개 불가 400 → Step 3 재입력 (의도된 안전 실패)" }
- { upgrade_trigger: state_absent, legacy_state: has_plaintext_secrets_from_7_0_3_or_earlier, reason: "state 파일이 없으면 잔존 평문도 없음" }
- { completion_path: reset, seed_outcome: success, reason: "reset 은 완료 전 상태 초기화 — 시딩 성공 후 경로 아님" }
effects:
# 소스 차단 — state.json 에 비밀 미기록
- step3_post_writes_state_config_without_db_write_password
- step3_post_writes_state_config_without_db_read_password
- step3_post_writes_state_config_without_admin_password
- step3_post_writes_state_config_without_admin_password_confirm
- step3_post_keeps_admin_password_in_session_for_runtime_transfer
- step3_post_drops_admin_password_confirm_from_session_no_consumer_exists
- sanitize_config_for_state_preserves_non_secret_fields_like_app_name_and_db_host
- sanitize_config_for_state_drops_read_connection_fields_when_use_read_db_false
- install_process_writes_admin_password_into_runtime_php_before_state_save
- install_process_writes_state_config_through_sanitize_helper
- install_process_fails_installation_start_when_runtime_write_fails
- step3_form_prefill_never_renders_admin_password_value_even_from_legacy_state
# runtime.php 스키마 + 보존 폴백
- build_runtime_adds_admin_section_only_when_caller_supplies_password
- build_runtime_preserves_existing_admin_section_across_retries
- build_runtime_preserves_existing_db_write_password_when_state_config_lacks_it
- build_runtime_read_password_falls_back_to_existing_runtime_before_write_password
- build_runtime_prefers_caller_supplied_password_over_existing_runtime_value
- build_runtime_preserves_existing_app_key_unchanged_regression_guard
# DB 비밀번호 소비처 hydrate 폴백
- hydrate_db_secrets_fills_empty_write_password_from_runtime
- hydrate_db_secrets_fills_empty_read_password_from_runtime
- hydrate_db_secrets_does_not_override_password_already_present_in_config
- hydrate_db_secrets_returns_config_unchanged_when_runtime_absent
- db_cleanup_drop_tables_connects_successfully_with_hydrated_credentials
- rollback_seed_truncate_connects_successfully_with_hydrated_credentials
- generate_env_content_needs_no_hydration_because_merge_runtime_into_env_overwrites_db_lines
# 소비 즉시 삭제 (redact-on-consume)
- db_seed_reads_admin_password_from_runtime_php_not_state_config
- db_seed_falls_back_to_state_config_admin_password_for_legacy_installs_in_progress
- db_seed_removes_admin_section_from_runtime_php_immediately_after_success
- db_seed_redacts_legacy_state_secrets_immediately_after_success
- db_seed_redact_reloads_state_so_completed_task_markers_are_not_lost
- db_seed_unsets_installer_admin_password_env_after_success
- db_seed_unsets_installer_admin_name_email_language_env_after_success
- subsequent_exec_children_do_not_inherit_plaintext_admin_password_env
- db_seed_leaves_admin_password_intact_in_runtime_when_seeding_fails_so_retry_works
# .env 유출 차단 불변식
- merge_runtime_into_env_never_writes_admin_section_whitelist_invariant
- merge_runtime_into_env_still_writes_db_credentials_and_app_key
- installer_runtime_service_provider_ignores_unknown_admin_section
# 완료/실패 시점 폴백
- complete_flag_task_redacts_state_secrets_before_saving_completed_status
- finalize_deletes_state_json_on_success_when_DELETE_INSTALLER_AFTER_COMPLETE_set
- finalize_redacts_state_json_when_unlink_fails
- finalize_redacts_state_json_when_DELETE_INSTALLER_AFTER_COMPLETE_false
- reset_state_redacts_secrets_in_preserved_config
- abort_installation_redacts_secrets_in_preserved_config
- completed_installer_page_load_clears_install_config_from_session
- completed_installer_page_load_clears_db_test_flags_from_session
# 재시도 / 재개 안전성
- resume_after_failure_with_live_session_reinjects_admin_password_into_runtime
- resume_after_failure_with_lost_session_reuses_admin_password_from_runtime
- resume_after_db_seed_completion_passes_validation_via_completed_task_marker
- resume_with_no_session_and_no_runtime_and_no_seed_marker_returns_400_missing_admin_password
- drop_tables_reconsent_reruns_db_seed_with_password_reinjected_by_install_process
# 업그레이드 스텝 (7.0.4) — 기존 설치 사이트 정리
- upgrade_step_no_op_when_state_json_absent
- upgrade_step_deletes_state_json_when_env_installer_completed_is_true
- upgrade_step_deletes_state_json_when_g7_installed_flag_present
- upgrade_step_does_not_abort_upgrade_when_state_json_cannot_be_deleted
- upgrade_step_preserves_state_json_and_redacts_only_when_installation_not_complete
- upgrade_step_preserves_non_secret_config_fields_so_in_progress_install_can_continue
- upgrade_step_preserves_corrupted_state_json_without_destroying_it
- upgrade_step_is_idempotent_across_repeated_runs
- upgrade_step_handles_state_without_config_section
- upgrade_step_does_not_chmod_or_chown_preserving_existing_file_ownership
test_files:
- tests/Unit/Installer/InstallerStateSecretsTest.php
- tests/Unit/Installer/InstallerRuntimeHelperTest.php
- tests/Feature/Upgrade/RedactResidualInstallerStateSecretsTest.php
manual_verification:
- scenario: A_sse_full_install
description: |
SSE 모드로 실제 설치 1회 완료 → 완료 후 storage/ 하위에서 입력한 관리자
비밀번호 문자열 grep 무일치 (installer-state.json / installer/runtime.php /
logs/installation.log 전부) + 그 비밀번호로 관리자 로그인 성공.
- scenario: B_polling_full_install
description: |
폴링 모드로 동일 검증. SSE 와 동일하게 install-process.php 를 경유하므로
비밀 이송 경로가 같아야 한다.
- scenario: C_abort_midway
description: |
Step 5 진행 중 설치 중단 → 잔존 installer-state.json 에 admin_password /
db_write_password 부재 확인 (redact 폴백). 이후 재개 시 정상 진행.
- scenario: D_drop_tables_retry
description: |
기존 DB 가 있는 상태에서 drop_tables 재동의로 재설치 → db_seed 가 다시 실행되고
관리자 계정이 정상 생성됨 (install-process.php 가 비밀번호를 runtime 에 재주입).
- scenario: E_upgrade_existing_site
description: |
7.0.3 이하에서 설치되어 평문 비밀이 남은 installer-state.json 이 있는 사이트를
7.0.4 로 업그레이드 → 파일 삭제(완료 사이트) 또는 비밀만 redact 확인.
rules_layer_coverage:
- rule: upgrade-step-class-caching
coverage: Upgrade_7_0_4 는 빈 위임자, 로직은 data/7.0.4/migrations/ 의 버전 namespace 클래스에 격리
- rule: installer-pattern-no-copy-to-upgrade-step
coverage: 업그레이드 스텝은 인스톨러 파일을 require 하지 않고 비밀 키 목록/파싱/저장을 로컬 인라인 중복 구현. CLI 컨텍스트이므로 chmod/chown 미시도 (기존 inode 권한 보존)
- rule: service-provider-db-safety
coverage: InstallerRuntimeServiceProvider 무수정 — runtime['db'] / runtime['app']['key'] 만 참조하므로 신규 admin 섹션은 무시됨