fix(core,admin-template): GC 스케줄 허용목록 동기 + 스토리지 잔존물 GC 신설 + 스케줄 모달 저장 회귀 수정

공개 후속 전수 조사의 실작업:
- attachments:prune-orphans 관리자 예약 허용목록 등재 + 가드 테스트 도출 규칙을
 런타임 validator 와 일치 (옵션 포함 키는 영원히 매칭되지 않는 죽은 항목)
- layout-previews:cleanup 을 gc-schedules 가드 구간으로 편입 (+onOneServer)
- storage:prune-leftovers 신설: 중단된 업데이트/설치의 _pending 스테이징·코어 임시·
 vendor 스테이징(3일)과 오래된 백업(30일, 최신 1개 상시 보존), 레거시 browser.log 회수
 — 산출물 누적 + 회수 경로 부재( 동형) 7건 해소
- 언어팩 설치 임시 디렉토리 정리를 finally 로 이동 (설치 성공 시 100% 누수)
- 브라우저 콘솔 로그를 daily(7일) 로테이션으로 전환 (단일 파일 989MB 실측)
- 검수 중 발견한 스케줄 등록/수정 모달 저장 불능 수정 (Form id 부재 + 커스텀
 Select/Toggle 값 미전송) + 동형 재발 차단 audit 룰 2종 신설
This commit is contained in:
HeuJung committed 2026-08-17 15:17:20 +09:00
1 parent db49e8b9b8
commit febffb173e
21 files changed
+1185 -29

No files matched your search

@@ -42,6 +42,7 @@ class CoreScheduleRegistrationTest extends TestCase
public function test_core_gc_schedules_are_registered(): void
{
$expected = [
'layout-previews:cleanup' => '*/30 * * * *',
'sanctum:prune-expired' => '0 4 * * *',
'auth:clear-resets' => '5 4 * * *',
'queue:prune-failed' => '10 4 * * *',
@@ -53,6 +54,8 @@ class CoreScheduleRegistrationTest extends TestCase
'identity:prune-logs' => '40 4 * * *',
'activity-log:prune' => '45 4 * * *',
'notification-log:prune' => '50 4 * * *',
'attachments:prune-orphans' => '55 4 * * *',
'storage:prune-leftovers' => '0 5 * * *',
'identity:expire-challenges' => '0 * * * *',
];
@@ -194,6 +197,7 @@ class CoreScheduleRegistrationTest extends TestCase
*
* 손으로 적은 목록은 예약이 늘어도 그대로라 전수를 증명하지 못합니다 —
* 다중 서버 1대 실행(`onOneServer`)으로 선언된 artisan 예약을 그대로 읽습니다.
* 예약 문자열의 옵션은 런타임 validator(`parseArtisanCommand`)와 동일하게 명령명만 남깁니다.
*
* @return array<int, string> 커맨드 이름 목록
*/
@@ -213,7 +217,10 @@ class CoreScheduleRegistrationTest extends TestCase
preg_match_all("/Schedule::command\(\s*'([^']+)'/", $region, $matches);
return array_values(array_unique($matches[1] ?? []));
return array_values(array_unique(array_map(
static fn (string $command): string => (string) strtok($command, ' '),
$matches[1] ?? []
)));
}
/**
@@ -0,0 +1,122 @@
<?php
namespace Tests\Feature\DevTools;
use App\Support\DevTools\BrowserLogWriter;
use Illuminate\Http\Request;
use Monolog\Handler\RotatingFileHandler;
use Psr\Log\LoggerInterface;
use Tests\TestCase;
/**
* 브라우저 콘솔 로그 파일 로테이션 회귀 테스트.
*
* 배경:
* `BrowserLogWriter::channel()` 이 `single` 드라이버로 로거를 만들면
* `storage/logs/browser.log` 단일 파일에 로테이션 없이 무한 append 된다 —
* 개발 도구를 켜 둔 사이트에서 이 파일이 저장소 단일 최대 파일(수백 MB)로
* 자라도 어떤 경로도 회수하지 않는다. 날짜별 파일 + 유한 보존일을 고정한다.
*
* @scenario vector=browser_log_write, actor_permission=debug_gate_enabled
*
* @effects browser_logs_rotate_daily_with_finite_retention
*/
class BrowserLogRotationTest extends TestCase
{
/**
* 브라우저 로그는 날짜별 파일에 기록되고, 단일 browser.log 에는 더 이상 쓰지 않는다.
*/
public function test_browser_logs_are_written_to_a_dated_file(): void
{
$datedPath = storage_path('logs/browser-'.now()->format('Y-m-d').'.log');
$singlePath = storage_path('logs/browser.log');
$datedExistedBefore = file_exists($datedPath);
// 레거시 단일 파일은 수백 MB 일 수 있다 — 내용을 읽지 않고 크기만 대조한다.
$singleSizeBefore = file_exists($singlePath) ? filesize($singlePath) : null;
$marker = 'browser-log-rotation-regression-'.uniqid();
try {
$request = Request::create('/_boost/browser-logs', 'POST', [
'logs' => [
['type' => 'log', 'data' => [$marker], 'url' => 'https://example.test/'],
],
]);
BrowserLogWriter::handle($request);
$this->assertFileExists($datedPath, '브라우저 로그가 날짜별 파일에 기록되지 않았다');
$this->assertStringContainsString(
$marker,
$this->tail($datedPath),
'날짜별 파일 꼬리에서 이번 기록을 찾지 못했다'
);
clearstatcache();
$singleSizeAfter = file_exists($singlePath) ? filesize($singlePath) : null;
$this->assertSame(
$singleSizeBefore,
$singleSizeAfter,
'레거시 단일 browser.log 에 여전히 기록이 추가되고 있다'
);
} finally {
if (! $datedExistedBefore && file_exists($datedPath)) {
@unlink($datedPath);
}
}
}
/**
* 로거는 로테이션 핸들러를 쓰고 보존일이 유한해야 한다 (0 = 무제한 금지).
*/
public function test_browser_log_channel_uses_rotating_handler_with_finite_retention(): void
{
$method = new \ReflectionMethod(BrowserLogWriter::class, 'channel');
/** @var LoggerInterface $logger */
$logger = $method->invoke(null);
$handlers = $logger->getLogger()->getHandlers();
$this->assertNotEmpty($handlers, '로그 핸들러를 확인할 수 없다');
$rotating = null;
foreach ($handlers as $handler) {
if ($handler instanceof RotatingFileHandler) {
$rotating = $handler;
}
}
$this->assertNotNull($rotating, '브라우저 로그 채널이 로테이션(daily) 핸들러를 쓰지 않는다');
$maxFiles = new \ReflectionProperty(RotatingFileHandler::class, 'maxFiles');
$this->assertGreaterThan(
0,
$maxFiles->getValue($rotating),
'보존일이 무제한(0)이다 — 날짜별 파일이 무한 누적된다'
);
}
/**
* 파일 꼬리(마지막 16KB)를 읽습니다 — 큰 로그 파일 전체 적재 방지.
*
* @param string $path 대상 파일 경로
* @return string 꼬리 내용
*/
private function tail(string $path): string
{
$size = (int) filesize($path);
$handle = fopen($path, 'rb');
if ($handle === false) {
return '';
}
try {
fseek($handle, max(0, $size - 16384));
return (string) stream_get_contents($handle);
} finally {
fclose($handle);
}
}
}
@@ -13,6 +13,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/**
@@ -768,6 +769,51 @@ class LanguagePackServiceTest extends TestCase
}
}
/**
* URL 설치가 성공해도 다운로드 임시 디렉토리(storage/app/temp/{uuid})가 남지 않는다.
*
* 임시 디렉토리 삭제가 catch 경로에만 있으면 실패 시에는 정리되고 성공 시에는
* 100% 잔존한다 — 예외도 로그도 없이 설치할 때마다 ZIP 사본이 쌓이는 누수다.
* 성공 경로를 실제로 통과시켜 잔존물이 0건임을 고정한다.
*
* @scenario vector=install_from_url, actor_permission=cli_system
*
* @effects successful_install_leaves_no_temp_directory
*/
public function test_install_from_url_success_leaves_no_temp_directory(): void
{
$identifier = 'tmpleak-core-ja';
$zipPath = tempnam(sys_get_temp_dir(), 'lp_zip');
$zip = new \ZipArchive;
$zip->open($zipPath, \ZipArchive::OVERWRITE);
$zip->addFromString(
'language-pack.json',
(string) json_encode($this->coreJaManifest($identifier, 'tmpleak', '1.0.0'), JSON_UNESCAPED_UNICODE)
);
$zip->close();
Http::fake(['https://packs.example.com/*' => Http::response((string) file_get_contents($zipPath), 200)]);
$tempRoot = storage_path('app/temp');
$before = File::isDirectory($tempRoot) ? File::directories($tempRoot) : [];
try {
$pack = $this->service->installFromUrl('https://packs.example.com/pack.zip', null);
$this->assertSame($identifier, $pack->identifier);
$after = File::isDirectory($tempRoot) ? File::directories($tempRoot) : [];
$this->assertSame(
[],
array_values(array_diff($after, $before)),
'설치가 성공했는데 storage/app/temp 에 다운로드 임시 디렉토리가 남았다'
);
} finally {
@unlink($zipPath);
File::deleteDirectory(base_path('lang-packs/'.$identifier));
}
}
/**
* 코어 ja 번들 픽스처용 manifest 를 만듭니다.
*
@@ -0,0 +1,255 @@
<?php
namespace Tests\Unit\Services;
use App\Services\StorageLeftoverPruneService;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 스토리지 잔존물 정리 서비스 회귀 테스트 (`storage:prune-leftovers`)
*
* 확장/코어 업데이트·설치가 중단되며 남긴 임시 산출물(#120 동형 — 산출물 누적 +
* 회수 경로 부재)을 mtime 기준으로 회수하되, 파괴 방지 가드(정상 대기 확장 불가침 ·
* 최신 백업 상시 보존 · dry-run 무삭제)를 함께 고정한다.
*
* 픽스처는 실제 저장소 경로가 아닌 격리 루트에 만든다 — 서비스 생성자의 루트 주입이
* 그 격리 지점이다.
*/
class StorageLeftoverPruneServiceTest extends TestCase
{
/** @var string 픽스처 격리 루트 */
private string $fixtureRoot;
/** @var string base_path 대응 루트 */
private string $baseRoot;
/** @var string storage_path 대응 루트 */
private string $storageRoot;
private StorageLeftoverPruneService $service;
protected function setUp(): void
{
parent::setUp();
$this->fixtureRoot = storage_path('framework/testing/leftover-prune-'.uniqid());
$this->baseRoot = $this->fixtureRoot.DIRECTORY_SEPARATOR.'base';
$this->storageRoot = $this->fixtureRoot.DIRECTORY_SEPARATOR.'storage';
File::ensureDirectoryExists($this->baseRoot);
File::ensureDirectoryExists($this->storageRoot);
$this->service = new StorageLeftoverPruneService($this->baseRoot, $this->storageRoot);
}
protected function tearDown(): void
{
File::deleteDirectory($this->fixtureRoot);
parent::tearDown();
}
/**
* 보존일이 지난 스테이징·임시·vendor 번들 잔존물만 삭제되고, 신선한 것은 남는다.
*
* @scenario leftover_target=update_staging, leftover_mode=real_delete, leftover_guard=aged_out
*
* @effects aged_leftovers_are_pruned_after_retention, fresh_leftovers_are_kept
*/
public function test_aged_leftovers_are_pruned_and_fresh_ones_are_kept(): void
{
// 업데이트 스테이징 (타임스탬프 접미사) + 교체 임시 마커
$agedStaging = $this->makeDir('base/modules/_pending/acme-shop_20260701_010101', 5);
$agedSwap = $this->makeDir('base/modules/_pending/acme-shop_updating_0123456789abc', 5);
$freshStaging = $this->makeDir('base/plugins/_pending/acme-pay_20260817_010101', 0);
// 코어 임시 (디렉토리 + 파일 혼재)
$agedTempDir = $this->makeDir('storage/app/temp/module_update_deadbeef00000', 5);
$agedTempFile = $this->makeFile('storage/app/temp/core_remote_changelog.md', 5);
$freshTempDir = $this->makeDir('storage/app/temp/plugin_update_cafebabe00000', 0);
// vendor 번들 스테이징
$agedBuild = $this->makeDir('storage/app/vendor-bundle-staging/build-0011223344556.77889900', 5);
$freshBuild = $this->makeDir('storage/app/vendor-bundle-staging/build-aabbccddeeff0.11223344', 0);
$result = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$this->assertDirectoryDoesNotExist($agedStaging);
$this->assertDirectoryDoesNotExist($agedSwap);
$this->assertDirectoryExists($freshStaging, '보존일 이내 스테이징이 삭제되었다');
$this->assertDirectoryDoesNotExist($agedTempDir);
$this->assertFileDoesNotExist($agedTempFile);
$this->assertDirectoryExists($freshTempDir, '보존일 이내 임시 디렉토리가 삭제되었다');
$this->assertDirectoryDoesNotExist($agedBuild);
$this->assertDirectoryExists($freshBuild, '보존일 이내 번들 스테이징이 삭제되었다');
$this->assertCount(2, $result['staging']);
$this->assertCount(2, $result['temp']);
$this->assertCount(1, $result['vendor_bundle_staging']);
}
/**
* 백업은 보존일 경과분만 삭제하되, identifier 별 최신 1개는 나이와 무관하게 보존한다.
*
* @scenario leftover_target=extension_backups, leftover_mode=real_delete, leftover_guard=latest_backup_kept
*
* @effects latest_backup_is_always_kept
*/
public function test_latest_backup_is_kept_regardless_of_age(): void
{
// 확장 백업 — 같은 identifier 의 오래된 2개: 최신(40일)은 보존, 그 이전(50일)은 삭제
$extOldest = $this->makeDir('storage/app/extension_backups/modules/acme-shop_20260601_010101', 50);
$extNewest = $this->makeDir('storage/app/extension_backups/modules/acme-shop_20260708_010101', 40);
// 다른 identifier 의 보존일 이내 백업은 최신이 아니어도 남는다
$extRecentA = $this->makeDir('storage/app/extension_backups/modules/acme-blog_20260810_010101', 7);
$extRecentB = $this->makeDir('storage/app/extension_backups/modules/acme-blog_20260815_010101', 2);
// 코어 백업 — 최신 1개 보존, 그 이전 삭제
$coreOldest = $this->makeDir('storage/app/core_backups/core_20260601_020202', 50);
$coreNewest = $this->makeDir('storage/app/core_backups/core_20260708_020202', 40);
$result = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$this->assertDirectoryDoesNotExist($extOldest);
$this->assertDirectoryExists($extNewest, '나이와 무관하게 최신 백업 1개는 보존해야 한다 (롤백 능력)');
$this->assertDirectoryExists($extRecentA, '보존일 이내 백업은 최신이 아니어도 남아야 한다');
$this->assertDirectoryExists($extRecentB);
$this->assertDirectoryDoesNotExist($coreOldest);
$this->assertDirectoryExists($coreNewest, '코어도 최신 백업 1개는 상시 보존해야 한다');
$this->assertSame([$extOldest], $result['extension_backups']);
$this->assertSame([$coreOldest], $result['core_backups']);
}
/**
* `_pending` 직하위의 정상 대기 확장 디렉토리(타임스탬프 접미사 없음)는 불가침이다.
*
* @scenario leftover_target=update_staging, leftover_mode=real_delete, leftover_guard=normal_pending_untouched
*
* @effects normal_pending_extension_dirs_are_untouched
*/
public function test_normal_pending_extension_directories_are_untouched(): void
{
// 다운로드 대기 정상 확장 — 오래되어도 삭제 대상이 아니다
$pendingModule = $this->makeDir('base/modules/_pending/acme-shop', 90);
$pendingTemplate = $this->makeDir('base/templates/_pending/acme-admin_basic', 90);
$result = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$this->assertDirectoryExists($pendingModule, '정상 대기 확장 디렉토리가 삭제되었다');
$this->assertDirectoryExists($pendingTemplate);
$this->assertSame([], $result['staging']);
}
/**
* dry-run 은 아무것도 삭제하지 않고 삭제 대상 목록만 돌려준다.
*
* @scenario leftover_target=core_temp, leftover_mode=dry_run, leftover_guard=aged_out
*
* @effects dry_run_deletes_nothing
*/
public function test_dry_run_deletes_nothing_and_reports_targets(): void
{
$agedStaging = $this->makeDir('base/modules/_pending/acme-shop_20260701_010101', 5);
$agedTemp = $this->makeDir('storage/app/temp/ext_zip_0123456789abc', 5);
$legacyLog = $this->makeFile('storage/logs/browser.log', 1);
$result = $this->service->prune(days: 3, backupDays: 30, dryRun: true);
$this->assertDirectoryExists($agedStaging, 'dry-run 이 스테이징을 실제로 삭제했다');
$this->assertDirectoryExists($agedTemp, 'dry-run 이 임시 디렉토리를 실제로 삭제했다');
$this->assertFileExists($legacyLog, 'dry-run 이 레거시 로그를 실제로 삭제했다');
$this->assertSame([$agedStaging], $result['staging']);
$this->assertSame([$agedTemp], $result['temp']);
$this->assertSame([$legacyLog], $result['legacy_browser_log']);
}
/**
* 정리 직후 재실행은 아무것도 삭제하지 않는다 (멱등).
*
* @scenario leftover_target=vendor_bundle_staging, leftover_mode=real_delete, leftover_guard=idempotent_second_run
*
* @effects leftover_prune_is_idempotent
*/
public function test_second_run_prunes_nothing(): void
{
$this->makeDir('base/modules/_pending/acme-shop_20260701_010101', 5);
$this->makeDir('storage/app/temp/module_update_deadbeef00000', 5);
$this->makeDir('storage/app/vendor-bundle-staging/build-0011223344556.77889900', 5);
$this->makeDir('storage/app/extension_backups/modules/acme-shop_20260601_010101', 50);
$this->makeDir('storage/app/extension_backups/modules/acme-shop_20260708_010101', 40);
$this->makeDir('storage/app/core_backups/core_20260601_020202', 50);
$this->makeDir('storage/app/core_backups/core_20260708_020202', 40);
$this->makeFile('storage/logs/browser.log', 1);
$first = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$second = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$this->assertGreaterThan(0, array_sum(array_map('count', $first)), '1회차가 아무것도 지우지 않으면 멱등 검증이 무의미하다');
$this->assertSame(0, array_sum(array_map('count', $second)), '2회차가 무언가를 또 지웠다 — 멱등이 아니다');
}
/**
* 레거시 단일 browser.log 는 나이와 무관하게 삭제하되, 날짜별 로그는 건드리지 않는다.
*
* @scenario leftover_target=legacy_browser_log, leftover_mode=real_delete, leftover_guard=aged_out
*
* @effects legacy_browser_log_is_removed
*/
public function test_legacy_browser_log_is_removed_but_dated_logs_are_kept(): void
{
$legacy = $this->makeFile('storage/logs/browser.log', 0);
$dated = $this->makeFile('storage/logs/browser-2026-08-17.log', 10);
$result = $this->service->prune(days: 3, backupDays: 30, dryRun: false);
$this->assertFileDoesNotExist($legacy, '레거시 단일 browser.log 는 writer 가 사라졌으므로 무조건 삭제한다');
$this->assertFileExists($dated, '날짜별 로그는 daily 드라이버가 자체 정리한다 — 대상이 아니다');
$this->assertSame([$legacy], $result['legacy_browser_log']);
}
/**
* 픽스처 디렉토리를 만들고 mtime 을 지정 일수만큼 과거로 되돌립니다.
*
* 내부에 파일을 하나 두어 실제 잔존물 형태(비어 있지 않은 디렉토리)를 재현하고,
* 내용 생성이 디렉토리 mtime 을 갱신하므로 touch 는 마지막에 수행한다.
*
* @param string $relative 픽스처 루트 기준 상대 경로
* @param int $ageDays 현재로부터 며칠 전의 mtime 으로 둘지
* @return string 절대 경로
*/
private function makeDir(string $relative, int $ageDays): string
{
$path = $this->fixtureRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
File::ensureDirectoryExists($path);
file_put_contents($path.DIRECTORY_SEPARATOR.'payload.txt', 'leftover');
$mtime = time() - $ageDays * 86400;
touch($path.DIRECTORY_SEPARATOR.'payload.txt', $mtime);
touch($path, $mtime);
return $path;
}
/**
* 픽스처 파일을 만들고 mtime 을 지정 일수만큼 과거로 되돌립니다.
*
* @param string $relative 픽스처 루트 기준 상대 경로
* @param int $ageDays 현재로부터 며칠 전의 mtime 으로 둘지
* @return string 절대 경로
*/
private function makeFile(string $relative, int $ageDays): string
{
$path = $this->fixtureRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
File::ensureDirectoryExists(dirname($path));
file_put_contents($path, 'leftover');
touch($path, time() - $ageDays * 86400);
return $path;
}
}
+28
View File
@@ -44,6 +44,16 @@ axes:
row_age: [within_retention, beyond_retention]
schedule_axis: [code_registered, admin_registered]
timezone_setting: [configured, empty]
# 스토리지 잔존물 GC (#120 후속 — storage:prune-leftovers): 대상군 × dry-run × 보존 가드
leftover_target:
- update_staging
- core_temp
- vendor_bundle_staging
- extension_backups
- core_backups
- legacy_browser_log
leftover_mode: [real_delete, dry_run]
leftover_guard: [aged_out, fresh_kept, latest_backup_kept, normal_pending_untouched, idempotent_second_run]
exclusions:
- { target: identity_challenges, row_age: beyond_retention, reason: "상태 전환만 수행하며 삭제하지 않음 — 만료 여부는 expires_at 이 판정" }
@@ -65,11 +75,29 @@ effects:
- automated_prune_emits_its_own_hooks
- retention_floor_is_owned_by_the_domain_layer
- large_purge_is_split_into_batches
# 스토리지 잔존물 GC (#120 후속)
- aged_leftovers_are_pruned_after_retention
- fresh_leftovers_are_kept
- latest_backup_is_always_kept
- normal_pending_extension_dirs_are_untouched
- dry_run_deletes_nothing
- leftover_prune_is_idempotent
- legacy_browser_log_is_removed
- browser_logs_rotate_daily_with_finite_retention
- successful_install_leaves_no_temp_directory
# E2E axis 없음 (스토리지 잔존물 GC): 브라우저 표면은 dev-dashboard 의 실행 버튼뿐이고
# blade 는 frontend-change-requires-e2e 룰 대상 경로가 아니다. 판정(패턴 매칭·mtime·
# 보존 가드)은 전부 서버측 파일시스템 연산이라 서버측 단위 테스트가 같은 것을 더 촘촘히
# 고정한다. 대시보드 버튼 노출 자체는 CoreScheduleRegistrationTest 가 소스 대조로 단언한다.
test_files:
- tests/Feature/Console/CoreScheduleRegistrationTest.php
- tests/Feature/Console/DataRetentionCommandsTest.php
- tests/Unit/Repositories/DeletesInBatchesTest.php
- tests/Unit/Services/StorageLeftoverPruneServiceTest.php
- tests/Feature/DevTools/BrowserLogRotationTest.php
- tests/Unit/Services/LanguagePack/LanguagePackServiceTest.php
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Console/PruneExpiredTempOrdersCommandTest.php
rules_layer_coverage: