fix(core,admin_basic): 정적 게시 재게시 누락 3건 수정 + 관리자 수동 복구 UI + sudo core:update 소유권 정합

- 템플릿 update 는 레이아웃 변경 여부와 무관하게 캐시 버전을 올리고(실패 복원 뒤에도), 자산 주소 방식 전환 3경로도 bump 한다
- config:cache 가 컨테이너 인스턴스를 덮어 이후 terminating 재게시가 사라지던 결함을 복원 헬퍼로 차단
- custom/ 변경 감지와 게시가 같은 열거자(재귀·크기 포함)를 쓰고, 서명은 호스트별로 저장
- 캐시 버전·서명 키를 만료시키지 않는다(기본 TTL 24h 로 매일 전체 재생성되던 문제)
- 관리자 > 환경설정 > 일반 「초기 화면 정적 파일」 카드: 상태 조회 + 지금 다시 만들기(확인 모달), 대시보드 알림 버튼 연결, CLI 와 같은 statusReport 소비
- sudo core:update 경로의 root 소유 잔존(설정 디렉토리·임시 폴더·로그·업그레이드 마이그레이션 산출물) 상속·정합화, ext-static 명령 root 경고와 sudo -u 힌트
- 안내·문서·트러블슈팅 4건·audit 룰 ext-cache-version-raw-read·ja 언어팩 동기
This commit is contained in:
HeuJung committed 2026-09-06 15:22:52 +09:00
1 parent d263f74cae
commit de18159986
105 files changed
+4055 -208

No files matched your search

@@ -26,6 +26,19 @@ class BackupDirectoryRestoreOwnershipConfigTest extends TestCase
$this->assertContains('storage/app/core_backups', $paths);
}
/**
* 정적 게시 트리(`public/build/ext`)가 두 목록에 포함된다 (#651 F22).
*
* root 프로세스는 자동 게시를 예약하지 않으므로 이 항목의 목적은 "terminating 게시가 만든 root
* 디렉토리" 가 아니라 **실존하는** 게시 트리(웹 계정이 게시한 사이트)의 소유권을 코어 업데이트
* 뒤 되돌리는 것이다 — 빠지면 재게시·GC 가 영구 실패해 정적 fast path 가 꺼진다.
*/
public function test_restore_ownership_includes_static_publish_tree(): void
{
$this->assertContains('public/build/ext', config('app.update.restore_ownership'));
$this->assertContains('public/build/ext', config('app.update.restore_ownership_group_writable'));
}
/**
* restore_ownership_group_writable 목록에 백업 2경로가 포함됨.
*/
@@ -9,6 +9,7 @@ use App\Extension\Traits\ClearsTemplateCaches;
use App\Models\Template;
use App\Services\ExtensionStaticCacheService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
@@ -287,6 +288,49 @@ class ClearsTemplateCachesTest extends TestCase
$this->assertLessThanOrEqual(time(), $newVersion);
}
/**
* 캐시 버전 키는 만료되지 않는다 (#651 F11).
*
* 종전에는 `put()` 에 TTL 을 넘기지 않아 `cache.default_ttl`(86400) 로 **매일 만료**됐고,
* 다음 독자가 `regenerateExtensionCacheVersion()` 으로 새 버전을 만들어 정적 게시본 전체
* (715파일·40MB)를 재생성하고 전 방문자의 자산 URL 을 바꿨다. 재생성은 `cache:clear` 나
* 스토어 소실 때만 일어나야 한다.
*
* @effects cache_version_key_does_not_expire
*/
public function test_version_key_survives_two_days(): void
{
$this->traitUser->callIncrementExtensionCacheVersion();
$version = ClearsTemplateCaches::getExtensionCacheVersion();
$this->assertGreaterThan(0, $version);
try {
Carbon::setTestNow(now()->addDays(2));
$this->assertSame(
$version,
(int) Cache::get('g7:core:ext.cache_version'),
'캐시 버전 키가 이틀 뒤 만료됐다 — 매일 정적 게시본 전체가 재생성되고 전 방문자의 자산 URL 이 바뀐다'
);
$this->assertSame($version, ClearsTemplateCaches::getExtensionCacheVersion());
} finally {
Carbon::setTestNow();
}
}
/**
* 영구 TTL 상수는 `put(…, 0)`(forget) 도, 기본 TTL 도 아닌 명시 양수여야 한다.
*
* @effects cache_version_key_does_not_expire
*/
public function test_persistent_ttl_constant_is_positive_and_longer_than_default(): void
{
$this->assertGreaterThan(
(int) config('cache.default_ttl', 86400) * 365,
ExtensionStaticCacheService::PERSISTENT_TTL_SECONDS
);
}
/**
* 버전 **재생성** 경로도 정적 게시를 예약한다 (D1).
*
@@ -0,0 +1,145 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\Helpers\ExtensionPendingHelper;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 확장 설정 시드·업데이트 임시 폴더의 소유권 상속 회귀 테스트 (#651 B2·B4).
*
* sudo 코어 업데이트(번들 확장 업데이트 프롬프트)가 root 로 `storage/app/{modules,plugins}/{id}/settings/`
* 를 만들면 그 서브트리는 restore_ownership 의도적 제외 경로라 코어 업데이트로도 되돌려지지 않고,
* 이후 웹 프로세스의 설정 저장이 영구 실패한다. 임시 폴더의 부모 `storage/app/temp` 도 최초 생성자가
* root 면 같은 결말이다(자식만 삭제된다). 소유권 축은 Windows 에서 실측할 수 없으므로 저장소 관례
* (소스 훑기)로 상속 호출의 존재를 잠근다.
*/
class ExtensionSettingsDirectoryOwnershipTest extends TestCase
{
/**
* 클래스 소스에서 주석을 제거한 본문을 돌려줍니다.
*/
private function strippedSource(string $class): string
{
$path = (new \ReflectionClass($class))->getFileName();
$stripped = '';
foreach (token_get_all((string) file_get_contents($path)) as $token) {
if (is_array($token) && in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
$stripped .= is_array($token) ? $token[1] : $token;
}
return $stripped;
}
/**
* `makeDirectory($settingsDir …)` 뒤 5줄 안에 상속 호출이 있는지 판정합니다.
*/
private function assertMakeDirectoryInheritsOwnership(string $class): void
{
$source = $this->strippedSource($class);
$offset = 0;
$found = 0;
while (($pos = strpos($source, 'File::makeDirectory($settingsDir', $offset)) !== false) {
$window = substr($source, $pos, 400);
$lines = array_slice(explode("\n", $window), 0, 6);
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($settingsDir)',
implode("\n", $lines),
$class.': settings 디렉토리 생성 뒤 부모 소유권 상속이 없다 — sudo 코어 업데이트 뒤 그 확장의 설정 저장이 영구 실패한다'
);
$found++;
$offset = $pos + 1;
}
$this->assertGreaterThan(0, $found, $class.': settings 디렉토리 생성 지점을 찾지 못했다');
}
/**
* @effects settings_directory_seed_inherits_ownership
*/
#[Test]
public function 모듈_설정_시드_디렉토리와_파일은_부모_소유권을_상속한다(): void
{
$this->assertMakeDirectoryInheritsOwnership(ModuleManager::class);
$source = $this->strippedSource(ModuleManager::class);
$this->assertStringContainsString(
"File::put(\$filePath, \$jsonContent);\n FilePermissionHelper::inheritOwnershipFromParent(\$filePath);",
$source,
'ModuleManager: 설정 시드 파일 쓰기 뒤 부모 소유권 상속이 없다'
);
}
/**
* @effects settings_directory_seed_inherits_ownership
*/
#[Test]
public function 플러그인_설정_시드_디렉토리와_파일은_부모_소유권을_상속한다(): void
{
$this->assertMakeDirectoryInheritsOwnership(PluginManager::class);
$source = $this->strippedSource(PluginManager::class);
$this->assertStringContainsString(
"File::put(\$settingsPath, \$content);\n FilePermissionHelper::inheritOwnershipFromParent(\$settingsPath);",
$source,
'PluginManager: 설정 시드 파일 쓰기 뒤 부모 소유권 상속이 없다'
);
}
/**
* 세 매니저의 업데이트 임시 폴더 확보가 공유 헬퍼를 경유한다 — 복사본은 갈라진다.
*
* @effects update_temp_directory_inherits_ownership
*/
#[Test]
public function 업데이트_임시_폴더는_공유_헬퍼로_확보한다(): void
{
foreach ([ModuleManager::class, PluginManager::class, TemplateManager::class] as $class) {
$source = $this->strippedSource($class);
$this->assertStringContainsString(
'ExtensionPendingHelper::ensureUpdateTempDirectory($tempDir)',
$source,
$class.': 업데이트 임시 폴더를 공유 헬퍼로 확보하지 않는다'
);
$this->assertStringNotContainsString(
"File::ensureDirectoryExists(\$tempDir);\n",
$source,
$class.': 임시 폴더를 직접 생성하는 옛 경로가 남아 있다 — 부모 storage/app/temp 가 root 로 굳는다'
);
}
}
/**
* 공유 헬퍼는 부모를 먼저 확보하고 자식에 소유권을 상속시킨다 (동작).
*
* @effects update_temp_directory_inherits_ownership
*/
#[Test]
public function 공유_헬퍼는_부모와_자식을_함께_확보한다(): void
{
$parent = storage_path('framework/testing/temp-parent-'.uniqid());
$child = $parent.'/module_update_'.uniqid();
try {
ExtensionPendingHelper::ensureUpdateTempDirectory($child);
$this->assertDirectoryExists($parent);
$this->assertDirectoryExists($child);
$this->assertTrue(is_writable($child));
} finally {
File::deleteDirectory($parent);
}
}
}
@@ -41,6 +41,76 @@ class TemplateUpdateConfigCacheInvalidationTest extends TestCase
);
}
/**
* 업데이트 tail 은 활성/비활성과 무관하게 **무조건** 캐시 버전을 올린다 (#651 F1).
*
* 종전에는 `if ($previousStatus !== ExtensionStatus::Active->value)` 가드 안에서만 올렸다.
* 활성 템플릿은 `refreshTemplateLayouts()` 의 조건부 bump(레이아웃 변경 건수 > 0)에
* 위임됐는데, 그 조건은 게시 입력 중 레이아웃 축만 보므로 lang/routes/dist 만 바뀐
* 릴리스는 정적 게시본이 immutable 로 stale 하게 남았다. 모듈·플러그인 update 는
* 무조건 bump 다 — 템플릿만 다를 이유가 없다.
*
* @scenario cache_state=warm_current,lifecycle_trigger=template_update,template_type=admin
*
* @effects template_update_always_bumps_cache_version
*/
#[Test]
public function update_template_tail_bumps_cache_version_unconditionally(): void
{
$body = $this->methodSource(
base_path('app/Extension/TemplateManager.php'),
'updateTemplate'
);
$this->assertStringNotContainsString(
'if ($previousStatus !== ExtensionStatus::Active->value)',
$body,
'updateTemplate() 의 bump 가 previousStatus 가드 안에 있으면 활성 템플릿의 lang/routes/dist 변경이 게시본에 반영되지 않습니다.'
);
// 성공 tail + 실패 catch 두 자리 — 최소 2회
$this->assertGreaterThanOrEqual(
2,
substr_count($body, '$this->incrementExtensionCacheVersion();'),
'updateTemplate() 는 성공 tail 과 실패 복원 경로 양쪽에서 캐시 버전을 올려야 합니다.'
);
}
/**
* 실패·복원 경로도 캐시 버전을 올린다 (#651 F2).
*
* 백업 복원이 실패했거나 부분 반영된 디스크가 남을 수 있어, 게시본을 새 버전으로 다시
* 굽는 쪽이 옛 게시본을 그대로 두는 쪽보다 안전하다. bump 실패는 원래 예외를 가리지
* 않도록 삼킨다.
*
* @scenario cache_state=warm_current,lifecycle_trigger=template_update,template_type=user
*
* @effects template_update_failure_bumps_after_restore
*/
#[Test]
public function update_template_failure_path_bumps_after_restore(): void
{
$body = $this->methodSource(
base_path('app/Extension/TemplateManager.php'),
'updateTemplate'
);
$catchAt = strrpos($body, 'catch (\Throwable $e)');
$this->assertNotFalse($catchAt, 'updateTemplate() 의 최외곽 catch 를 찾지 못했습니다.');
$catchBody = substr($body, $catchAt);
$restoreAt = strpos($catchBody, "'status' => \$previousStatus");
$bumpAt = strpos($catchBody, '$this->incrementExtensionCacheVersion();');
$throwAt = strpos($catchBody, 'throw new \RuntimeException(');
$this->assertNotFalse($restoreAt, '실패 경로의 상태 복원 코드를 찾지 못했습니다.');
$this->assertNotFalse($bumpAt, '실패 경로에 캐시 버전 bump 가 없습니다 — 부분 반영된 디스크가 옛 게시본과 함께 남습니다.');
$this->assertNotFalse($throwAt, '실패 경로의 재던지기를 찾지 못했습니다.');
$this->assertTrue($restoreAt < $bumpAt && $bumpAt < $throwAt, 'bump 는 상태 복원 뒤, 재던지기 앞에 있어야 합니다.');
}
/**
* 대상 메서드 본문을 주석 제거 후 반환합니다.
*
@@ -3,6 +3,7 @@
namespace Tests\Unit\Helpers;
use App\Extension\Helpers\FilePermissionHelper;
use App\Extension\Helpers\SettingsMigrator;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
@@ -96,6 +97,31 @@ class SettingsMigratorOwnershipTest extends TestCase
$this->assertSame($parentOwnerBefore, fileowner($child), '자식 owner 가 부모와 동일');
}
/**
* settings 디렉토리 생성도 파일과 대칭으로 부모 소유권을 상속한다 (#651 B1).
*
* 파일(`writeJsonFile`)만 상속하고 디렉토리(`makeDirectory`)는 상속하지 않던 비대칭 — sudo
* 업그레이드 스텝이 디렉토리를 root 로 만들면 `storage/app/{modules,plugins}` 는 restore_ownership
* 의도적 제외 경로라 되돌려지지 않고, 이후 웹 프로세스의 그 모듈 설정 저장이 영구 실패한다.
*
* @effects settings_directory_seed_inherits_ownership
*/
public function test_settings_migrator_make_directory_invokes_inherit_ownership(): void
{
$body = (string) file_get_contents((new \ReflectionClass(SettingsMigrator::class))->getFileName());
$pos = strpos($body, 'File::makeDirectory($settingsDir');
$this->assertNotFalse($pos, 'SettingsMigrator 의 settings 디렉토리 생성 지점을 찾지 못했다');
$window = implode("\n", array_slice(explode("\n", substr($body, $pos)), 0, 4));
$this->assertStringContainsString(
'FilePermissionHelper::inheritOwnershipFromParent($settingsDir)',
$window,
'SettingsMigrator: settings 디렉토리 생성 뒤 부모 소유권 상속이 없다 (파일만 상속하는 비대칭)'
);
}
/**
* SettingsMigrator::writeJsonFile 호출 후 *.json 의 owner 가 부모와 일치.
*
@@ -107,7 +133,7 @@ class SettingsMigratorOwnershipTest extends TestCase
*/
public function test_settings_migrator_write_json_file_invokes_inherit_ownership(): void
{
$reflection = new \ReflectionClass(\App\Extension\Helpers\SettingsMigrator::class);
$reflection = new \ReflectionClass(SettingsMigrator::class);
$method = $reflection->getMethod('writeJsonFile');
$body = file_get_contents($method->getFileName());
@@ -0,0 +1,54 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 설치기 best-effort 작업 실패 문구 테스트 (#651 C3).
*
* 종전에는 작업 종류와 무관하게 언어팩 전용 문구를 재사용해, 대상이 없는 `static_publish`·
* `config_cache` 실패가 "언어팩 일부 설치에 실패했습니다: (계속 진행)" 으로 찍혔다.
*
* `task-runner.php` 는 진입과 함께 작업을 실행하는 파일이라 테스트에서 include 할 수 없다 —
* 조립 함수의 존재·호출과 문구 키의 형태를 소스로 잠근다.
*/
class InstallerBestEffortMessageTest extends TestCase
{
/**
* @effects installer_best_effort_message_names_the_task
*/
#[Test]
public function best_effort_분기는_작업_라벨_기반_문구_조립_함수를_쓴다(): void
{
$source = (string) file_get_contents(base_path('public/install/includes/task-runner.php'));
$this->assertStringContainsString('function bestEffortFailureMessage(string $taskId, string $target): string', $source);
$this->assertStringContainsString('lang("task_{$taskId}")', $source);
$this->assertStringContainsString("lang('warning_best_effort_task_failed', ['task' => \$display])", $source);
// 실패 분기가 새 조립 함수를 부른다 — 언어팩 전용 키를 직접 부르는 옛 줄은 남아 있지 않다
$this->assertStringContainsString('$warnMsg = bestEffortFailureMessage((string) $taskId, (string) $target);', $source);
$this->assertStringNotContainsString("lang('warning_language_pack_install_partial', ['identifier' => (string) \$target])", $source);
}
/**
* 문구 키가 `:task` 치환 자리를 갖고, best-effort 작업 3종의 라벨 키가 양 로케일에 있다.
*
* @effects installer_best_effort_message_names_the_task
*/
#[Test]
public function 문구_키와_작업_라벨_키가_양_로케일에_있다(): void
{
foreach (['ko', 'en'] as $locale) {
$messages = require base_path("public/install/lang/{$locale}.php");
$this->assertStringContainsString(':task', $messages['warning_best_effort_task_failed'] ?? '', "{$locale}: :task 치환 자리가 없다");
foreach (['task_static_publish', 'task_config_cache', 'task_language_pack_install'] as $key) {
$this->assertNotEmpty($messages[$key] ?? null, "{$locale}: {$key} 라벨이 없다");
}
}
}
}
@@ -293,6 +293,7 @@ class InstallerJsonOutputTest extends TestCase
'error_empty_server_response',
'error_invalid_server_response',
'error_polling_response_invalid',
'warning_best_effort_task_failed',
];
foreach (['ko', 'en'] as $locale) {
@@ -28,6 +28,32 @@ class CoreUpdateRuntimeOwnershipTest extends TestCase
$this->assertTrue(true);
}
/**
* 정상화 타깃에 확장 업데이트 임시 폴더와 로그 디렉토리가 포함된다 (#651 B5).
*
* `storage/app/temp` 의 부모는 sudo 업데이트가 최초 생성자가 되면 root 로 굳어 이후 관리자 화면의
* 확장 업데이트가 임시 폴더를 만들지 못하고, `storage/logs` 는 restore_ownership 복원(Step 11)
* 뒤에 만들어지는 daily 롤오버·신규 로그 파일이 root 로 남는다.
*
* @effects runtime_ownership_targets_cover_temp_and_logs
*/
public function test_runtime_ownership_targets_include_temp_and_logs(): void
{
$method = new \ReflectionMethod(CoreUpdateService::class, 'normalizeRuntimeOwnershipAfterRootRun');
$lines = file($method->getFileName()) ?: [];
$body = implode('', array_slice($lines, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
foreach ([
"storage_path('framework/cache')",
"base_path('bootstrap/cache')",
"storage_path('app/ext-bundles')",
"storage_path('app/temp')",
"storage_path('logs')",
] as $target) {
$this->assertStringContainsString($target, $body, "런타임 소유권 정상화 타깃에 {$target} 이 없다");
}
}
/**
* 부모(CoreUpdateCommand)·자식(ExecuteUpgradeStepsCommand) 흐름 종료부가
* 정상화를 호출한다 — 로그 소유권 정상화(restoreUpgradeLogOwnership)와
@@ -0,0 +1,88 @@
<?php
namespace Tests\Unit\Services;
use App\Exceptions\CustomAssetOperationException;
use App\Services\CustomAssetService;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* `custom/` 디렉토리 생성 실패 안내 테스트 (#651 D6·C2).
*
* `custom/` 은 지연 생성이라 `deploy:deploy 0755` 로 배포된 확장 디렉토리에서 운영자의 첫 저장이
* 여기서 실패한다. 종전 문구는 경로만 적어 무엇을 고쳐야 하는지 알 수 없었다 — 사유·소유자·권한·
* 실행 계정·조치 예시를 함께 싣는다(정적 게시 프리플라이트와 같은 식).
*/
class CustomAssetServiceDirectoryFailureTest extends TestCase
{
/** 테스트용 가짜 플러그인 식별자 */
private const FAKE_PLUGIN = 'g7test-dirfail';
protected function tearDown(): void
{
File::deleteDirectory(base_path('plugins/'.self::FAKE_PLUGIN));
parent::tearDown();
}
/**
* 같은 이름의 **파일**이 `custom/` 자리를 차지하면 사유·조치가 실린 메시지로 실패한다.
*
* (POSIX 권한 거부는 Windows 에서 재현할 수 없어 파일 점유 사유로 실패 경로를 태운다 — 사유 코드는
* 공통 프리미티브가 돌려주므로 매핑 경로는 같다.)
*
* @scenario custom_source=convention_scan, custom_asset=css
*
* @effects custom_directory_failure_explains_reason_and_action
*/
#[Test]
public function 디렉토리_생성_실패는_사유와_조치를_함께_알린다(): void
{
$pluginDir = base_path('plugins/'.self::FAKE_PLUGIN);
File::ensureDirectoryExists($pluginDir);
// `custom` 자리를 파일로 점유 — mkdir 이 실패하는 결정적 조건
File::put($pluginDir.'/custom', 'not a directory');
try {
app(CustomAssetService::class)->save('plugins', self::FAKE_PLUGIN, 'custom.css', '/* x */');
$this->fail('디렉토리를 만들 수 없는데 예외가 나지 않았다');
} catch (CustomAssetOperationException $e) {
$this->assertSame('custom_assets.errors.directory_failed', $e->errorKey);
foreach (['path', 'reason', 'owner', 'perms', 'process_user', 'hint'] as $param) {
$this->assertArrayHasKey($param, $e->params, "실패 메시지 파라미터 {$param} 이 없다");
}
// 사유 코드가 번역된 문장으로 실려야 한다 (키 노출 금지)
$this->assertStringNotContainsString('custom_assets.', (string) $e->params['reason']);
$this->assertStringNotContainsString('custom_assets.', (string) $e->params['hint']);
$this->assertStringContainsString('chown', (string) $e->params['hint']);
// 최종 문장에 치환 자리가 남아 있지 않다
$this->assertStringNotContainsString(':reason', $e->getMessage());
$this->assertStringNotContainsString(':hint', $e->getMessage());
}
}
/**
* 사유 코드 4종은 ko/en 양쪽에 번역이 있다 — 없는 코드는 키 문자열이 화면에 나간다.
*
* @effects custom_directory_failure_explains_reason_and_action
*/
#[Test]
public function 사유_코드_4종은_양_로케일에_번역이_있다(): void
{
foreach (['ko', 'en'] as $locale) {
$messages = require base_path("lang/{$locale}/custom_assets.php");
foreach (['occupied_by_file', 'ancestor_not_writable', 'create_failed', 'not_writable'] as $code) {
$this->assertNotEmpty($messages['errors']['reason'][$code] ?? null, "{$locale}: reason.{$code} 번역이 없다");
}
$this->assertNotEmpty($messages['errors']['directory_failed_hint'] ?? null, "{$locale}: directory_failed_hint 가 없다");
$this->assertStringContainsString(':hint', $messages['errors']['directory_failed']);
}
}
}
@@ -5,9 +5,11 @@ namespace Tests\Unit\Services;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\AttachmentRepositoryInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Services\SettingsService;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
/**
@@ -144,6 +146,140 @@ class SettingsServiceSetSettingSideEffectsTest extends TestCase
$this->assertFalse($service->setSetting('drivers.queue_driver', 'redis'));
}
/**
* 자산 URL 방식을 단건으로 바꾸면 확장 캐시 버전이 오른다 — 실제 키 관측 (#651 F5).
*
* 병합 번들 CSS 에는 그 시점의 자산 URL 형태(확장자 / `?file=`)가 구워져 있고, 디스크 번들과
* 정적 게시본은 캐시 버전으로 키드된다. 버전이 오르지 않으면 모드를 바꿔도 옛 형태의
* `url()` 이 남아 글꼴·이미지가 404 가 된다.
*
* @effects asset_url_mode_change_bumps_extension_cache_version
*/
public function test_asset_url_mode_change_bumps_extension_cache_version(): void
{
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
Artisan::shouldReceive('call')->zeroOrMoreTimes();
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
Cache::put('g7:core:ext.cache_version', 1000);
$service = $this->makeService(existingValue: 'extensionless');
$this->assertTrue($service->setSetting('general.asset_url_mode', 'extension'));
$this->assertGreaterThan(
1000,
(int) Cache::get('g7:core:ext.cache_version'),
'자산 URL 방식 단건 변경이 확장 캐시 버전을 올리지 않았다 — 번들 CSS 의 옛 url() 형태가 남는다.'
);
}
/**
* 값이 그대로면 확장 캐시 버전도 그대로다.
*
* @effects asset_url_mode_change_bumps_extension_cache_version
*/
public function test_same_asset_url_mode_keeps_extension_cache_version(): void
{
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
Artisan::shouldReceive('call')->zeroOrMoreTimes();
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
Cache::put('g7:core:ext.cache_version', 1000);
$service = $this->makeService(existingValue: 'extension');
$this->assertTrue($service->setSetting('general.asset_url_mode', 'extension'));
$this->assertSame(1000, (int) Cache::get('g7:core:ext.cache_version'));
}
/**
* 벌크 저장(saveSettings) 경로도 같은 부수효과를 갖는다 — 화면 [저장] 버튼이 타는 경로다.
*
* @effects asset_url_mode_change_bumps_extension_cache_version
*/
public function test_bulk_save_asset_url_mode_change_bumps_extension_cache_version(): void
{
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
Artisan::shouldReceive('call')->zeroOrMoreTimes();
$existing = ['asset_url_mode' => 'extensionless'];
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
$configRepository->shouldReceive('getCategory')->with('general')->andReturnUsing(function () use (&$existing): array {
return $existing;
});
$configRepository->shouldReceive('saveCategory')->andReturn(true);
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
Cache::put('g7:core:ext.cache_version', 1000);
$service = app(SettingsService::class);
$this->assertTrue($service->saveSettings(['_tab' => 'general', 'general' => ['asset_url_mode' => 'extension']]));
$this->assertGreaterThan(1000, (int) Cache::get('g7:core:ext.cache_version'));
// 같은 값 재저장은 올리지 않는다
Cache::put('g7:core:ext.cache_version', 2000);
$existing = ['asset_url_mode' => 'extension'];
$this->assertTrue($service->saveSettings(['_tab' => 'general', 'general' => ['asset_url_mode' => 'extension']]));
$this->assertSame(2000, (int) Cache::get('g7:core:ext.cache_version'));
}
/**
* 설정 복원으로 자산 URL 방식이 바뀌면 SEO 캐시 삭제 + 확장 캐시 버전 bump 가 따른다.
*
* 복원은 설정 전체를 갈아엎는 쓰기라 두 저장 경로와 같은 부수효과를 받아야 한다 —
* 종전에는 변경 감지 자체가 없었다.
*
* @effects asset_url_mode_change_bumps_extension_cache_version
*/
public function test_restore_asset_url_mode_change_bumps_extension_cache_version(): void
{
$this->mock(SeoCacheManagerInterface::class)->shouldReceive('clearAll')->once();
Artisan::shouldReceive('call')->zeroOrMoreTimes();
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
// 복원 전 / 복원 후 순서대로 읽힌다
$configRepository->shouldReceive('get')->with('general.asset_url_mode')->andReturn('extensionless', 'extension');
$configRepository->shouldReceive('restore')->andReturn(true);
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
Cache::put('g7:core:ext.cache_version', 1000);
$service = app(SettingsService::class);
$this->assertTrue($service->restoreSettings('/tmp/backup.json'));
$this->assertGreaterThan(1000, (int) Cache::get('g7:core:ext.cache_version'));
}
/**
* 복원 전후 값이 같으면 두 부수효과 모두 없다.
*
* @effects asset_url_mode_change_bumps_extension_cache_version
*/
public function test_restore_with_same_asset_url_mode_has_no_side_effects(): void
{
$this->mock(SeoCacheManagerInterface::class)->shouldReceive('clearAll')->never();
Artisan::shouldReceive('call')->zeroOrMoreTimes();
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
$configRepository->shouldReceive('get')->with('general.asset_url_mode')->andReturn('extensionless');
$configRepository->shouldReceive('restore')->andReturn(true);
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
Cache::put('g7:core:ext.cache_version', 1000);
$service = app(SettingsService::class);
$this->assertTrue($service->restoreSettings('/tmp/backup.json'));
$this->assertSame(1000, (int) Cache::get('g7:core:ext.cache_version'));
}
/**
* 단건 저장은 받은 키를 변형 없이 저장소에 넘긴다. (벌크 위임 금지 — 계약 고정)
*
@@ -0,0 +1,77 @@
<?php
namespace Tests\Unit\Support;
use App\Support\ConfigCacheHelper;
use Illuminate\Container\Container;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* `ConfigCacheHelper` 가 `config:cache` 뒤 전역 컨테이너 인스턴스를 되돌리는지 (#651 F2 실측 파생).
*
* `config:cache` 는 새 Application 을 부팅하고 그 생성자가 `Container::setInstance()` 를 호출한다.
* 되돌리지 않으면 같은 프로세스의 후속 `app()->terminating()` 이 종료되지 않는 일회용 앱에 등록되어
* 정적 재게시 예약이 조용히 사라진다 — 예외도 로그도 없이 "다음 렌더에야 반영" 으로만 나타난다.
*/
class ConfigCacheHelperContainerTest extends TestCase
{
/**
* 콜백이 전역 인스턴스를 바꿔 놓아도 실행 후 원래 앱으로 돌아온다.
*
* @effects config_cache_rebuild_preserves_container_instance
*/
#[Test]
public function 콜백이_전역_인스턴스를_바꿔도_원래_앱으로_되돌린다(): void
{
$original = Container::getInstance();
$stray = new Container;
ConfigCacheHelper::withPreservedContainer(static function () use ($stray): void {
Container::setInstance($stray);
});
$this->assertSame($original, Container::getInstance(), 'config:cache 뒤 app() 이 일회용 앱을 가리킨 채 남는다 — 후속 terminating 예약이 사라진다');
$this->assertSame($original, app());
}
/**
* 콜백이 예외를 던져도 인스턴스는 되돌린다.
*
* @effects config_cache_rebuild_preserves_container_instance
*/
#[Test]
public function 콜백이_실패해도_원래_앱으로_되돌린다(): void
{
$original = Container::getInstance();
try {
ConfigCacheHelper::withPreservedContainer(static function (): void {
Container::setInstance(new Container);
throw new \RuntimeException('boom');
});
$this->fail('예외가 전파되어야 한다');
} catch (\RuntimeException) {
// 기대한 예외
}
$this->assertSame($original, Container::getInstance());
}
/**
* `rebuild()` 가 `config:cache` 호출을 보존 래퍼로 감싼다 (소스 구조).
*
* @effects config_cache_rebuild_preserves_container_instance
*/
#[Test]
public function rebuild_는_config_cache_를_보존_래퍼로_감싼다(): void
{
$method = new \ReflectionMethod(ConfigCacheHelper::class, 'rebuild');
$lines = file($method->getFileName()) ?: [];
$body = implode('', array_slice($lines, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
$this->assertStringContainsString("withPreservedContainer(static fn () => Artisan::call('config:cache'))", $body);
$this->assertStringNotContainsString("\n Artisan::call('config:cache');", $body);
}
}
@@ -0,0 +1,173 @@
<?php
namespace Tests\Unit\Support;
use App\Support\CustomAssets;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* `CustomAssets::publishableFiles()` — 게시·변경 감지가 공유하는 열거자 테스트 (#651 F7).
*
* 정적 게시는 `custom/**` 를 재귀로 복사하고, 변경 감지는 종전에 최상위 css/js 의 mtime 만
* 서명했다. 두 범위를 서로 다른 코드가 정의하면 어긋나고, 그 어긋남은 "글꼴을 바꿨는데
* 반영되지 않는다" 로만 나타난다. 이 열거자 하나가 두 소비자의 집합을 정한다.
*
* DB 를 쓰지 않는다 — 파일 시스템 해석만 검증한다.
*/
class CustomAssetsPublishableFilesTest extends TestCase
{
/** 테스트용 가짜 플러그인 식별자 */
private const FAKE_PLUGIN = 'g7test-publishable';
private function pluginDir(): string
{
return base_path('plugins/'.self::FAKE_PLUGIN);
}
protected function setUp(): void
{
parent::setUp();
CustomAssets::flushCache();
File::ensureDirectoryExists($this->pluginDir().'/custom');
}
protected function tearDown(): void
{
File::deleteDirectory($this->pluginDir());
CustomAssets::flushCache();
parent::tearDown();
}
private function writeCustom(string $relative, string $contents = '/* x */'): void
{
$path = $this->pluginDir().'/custom/'.$relative;
File::ensureDirectoryExists(dirname($path));
File::put($path, $contents);
}
/**
* 하위 디렉토리의 글꼴·이미지까지 열거한다 — 게시와 같은 범위.
*
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 하위_디렉토리의_정적_파일까지_열거한다(): void
{
$this->writeCustom('custom.css');
$this->writeCustom('fonts/x.woff2', 'font');
$this->writeCustom('img/deep/marker.svg', '<svg/>');
$relatives = array_column(CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN), 'relative');
$this->assertSame(['custom.css', 'fonts/x.woff2', 'img/deep/marker.svg'], $relatives);
}
/**
* 허용 확장자 밖(텍스트·PHP)과 소스맵은 뺀다 — 게시 화이트리스트와 동일.
*
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 허용_확장자_밖과_소스맵은_열거하지_않는다(): void
{
$this->writeCustom('custom.css');
$this->writeCustom('notes.txt', 'not an asset');
$this->writeCustom('evil.php', '<?php');
$this->writeCustom('custom.css.map', '{}');
$relatives = array_column(CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN), 'relative');
$this->assertSame(['custom.css'], $relatives);
}
/**
* 항목마다 절대 경로·수정 시각·크기를 싣는다 — 서명 재료이자 게시 복사 원본이다.
*
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=top_level_asset
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 항목은_절대경로_mtime_크기를_갖는다(): void
{
$this->writeCustom('custom.css', '/* twelve b */');
$files = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
$this->assertCount(1, $files);
$this->assertSame('custom.css', $files[0]['relative']);
$this->assertFileExists($files[0]['absolute']);
$this->assertSame(14, $files[0]['size']);
$this->assertGreaterThan(0, $files[0]['mtime']);
}
/**
* 요청 스코프 메모이즈 — 같은 요청에서 두 번 물어도 디스크를 다시 훑지 않고, `flushCache()` 가 비운다.
*
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=no_change
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 결과는_요청_스코프로_메모이즈되고_flush_로_비워진다(): void
{
$this->writeCustom('custom.css');
$first = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
// 메모가 살아 있는 동안 추가한 파일은 보이지 않는다
$this->writeCustom('fonts/x.woff2', 'font');
$this->assertSame($first, CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
CustomAssets::flushCache();
$this->assertCount(2, CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
}
/**
* 디렉토리가 없거나 타입이 유효하지 않으면 빈 목록이다.
*
* @scenario custom_source=none, custom_asset=css, custom_change_detection=no_change
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 디렉토리_부재와_무효_타입은_빈_목록이다(): void
{
File::deleteDirectory($this->pluginDir());
$this->assertSame([], CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
$this->assertSame([], CustomAssets::publishableFiles('unknown', self::FAKE_PLUGIN));
$this->assertSame([], CustomAssets::publishableFiles('plugins', '../escape'));
}
/**
* 로드 목록(`forExtension`)은 그대로 최상위 css/js 만 싣는다 — 열거자 도입이 로드 의미를 바꾸지 않는다.
*
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
*
* @effects custom_signature_covers_publishable_tree
*/
#[Test]
public function 로드_목록은_여전히_최상위_css_js_만_싣는다(): void
{
$this->writeCustom('custom.css');
$this->writeCustom('fonts/inner.css');
$this->writeCustom('img/marker.svg', '<svg/>');
$loaded = CustomAssets::forExtension('plugins', self::FAKE_PLUGIN);
$publishable = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
$this->assertCount(1, $loaded);
$this->assertStringContainsString('custom.css', $loaded[0]['url']);
$this->assertCount(3, $publishable);
}
}
@@ -0,0 +1,78 @@
<?php
namespace Tests\Unit\Upgrade;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 번들 확장 업그레이드 마이그레이션의 파일 쓰기 소유권 상속 패리티 (#651 B3).
*
* 업그레이드 스텝은 sudo 코어 업데이트 안에서 root 로 실행될 수 있다. `File::put()` 으로 설정 파일을
* 쓰는 스텝 중 일부(gdpr 02·ckeditor5·pay_*)는 `inheritOwnershipFromParent` 를 부르고 일부는 부르지
* 않아 진영이 갈렸다 — 지금은 전부 기존 파일 갱신이라 inode 소유자가 보존되지만, "없으면 생성" 으로
* 바뀌는 순간 root 소유 파일이 남는다.
*
* 모집단은 **파일시스템에서 파생**한다 — 8개 파일을 열거하면 9번째 마이그레이션이 사각이 된다.
*/
class BundledUpgradeMigrationOwnershipParityTest extends TestCase
{
/**
* `File::put(` 뒤 5줄 안에 상속 호출이 없는 마이그레이션 파일을 모읍니다.
*
* @return array<int, string> 위반 파일 (base_path 상대)
*/
private function collectViolations(): array
{
$pattern = base_path('{modules,plugins}/_bundled/*/upgrades');
$violations = [];
$population = 0;
foreach (glob($pattern, GLOB_BRACE) ?: [] as $upgradesDir) {
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($upgradesDir, \FilesystemIterator::SKIP_DOTS));
/** @var \SplFileInfo $file */
foreach ($iterator as $file) {
if (! $file->isFile() || strtolower($file->getExtension()) !== 'php') {
continue;
}
$lines = file($file->getPathname(), FILE_IGNORE_NEW_LINES) ?: [];
foreach ($lines as $index => $line) {
if (! str_contains($line, 'File::put(')) {
continue;
}
$population++;
$window = implode("\n", array_slice($lines, $index, 6));
if (! str_contains($window, 'inheritOwnershipFromParent')) {
$violations[] = str_replace('\\', '/', substr($file->getPathname(), strlen(base_path()) + 1)).':'.($index + 1);
}
}
}
}
$this->assertGreaterThan(0, $population, '모집단이 비었다 — 번들 확장 upgrades 에서 File::put 을 찾지 못했다 (판정식 회귀 의심)');
return $violations;
}
/**
* 모든 `File::put(` 은 5줄 안에 `inheritOwnershipFromParent` 를 동반한다.
*
* @effects bundled_upgrade_migrations_inherit_ownership
*/
#[Test]
public function 번들_업그레이드_마이그레이션의_파일_쓰기는_전부_소유권을_상속한다(): void
{
$violations = $this->collectViolations();
$this->assertSame(
[],
$violations,
"File::put 뒤 소유권 상속이 없는 업그레이드 마이그레이션:\n - ".implode("\n - ", $violations)
);
}
}