feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)

공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다.

브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도
남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데
자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기
하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발
대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다.
런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다.

자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그
실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML
에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다.
편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다.

두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의
custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에
의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다.
확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을
고치면 그 변경을 감지해 재게시까지 예약된다.

FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접
넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로
나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린
스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과
분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠
화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를
함께 뒀다.

동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에
써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
HeuJung committed 2026-08-27 16:47:14 +09:00
1 parent 72f2e94c1a
commit 3945b6f1b3
1042 files changed
+107435 -947

No files matched your search

@@ -0,0 +1,318 @@
<?php
namespace Tests\Feature\Extension;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 구동 에셋의 외부 CDN 의존 전수 차단
*
* 브라우저가 화면을 그리기 위해 제3자 origin 에 도달해야 하면, 그 도달 실패는 예외도
* 로그도 남기지 않고 **화면 기능만 조용히 사라진다.** 폐쇄망·방화벽·광고차단기에서
* 재현되며 자체 서버 로그에 흔적이 없어 운영자가 원인을 특정할 수 없다.
*
* 판정 모집단을 한 확장 안에 두지 않고 **코어까지 넓힌다** — 판정기를 한 확장에 두면
* 그 확장 밖의 동형 결함이 red 가 되지 않는다(`GenericCatchStatusCodeContractTest` 선례).
*
* 예외는 두 가지뿐이다:
* 1. 확장 manifest 가 `trusted_script_hosts` + `trusted_script_hosts_reason` 을 **함께**
* 선언한 호스트 (자체 호스팅이 불가능한 서비스 SDK 등)
* 2. 이 테스트가 사유와 함께 명시한 코어 예외 (운영자가 켜야만 출력되는 외부 분석 등)
*
* DB 를 쓰지 않는다 — 저장소 소스 스캔이다.
*/
class BundledExtensionNoExternalAssetTest extends TestCase
{
/**
* 자산으로 간주하는 확장자
*
* API 엔드포인트·문서 링크를 결함으로 오인하지 않도록 **브라우저가 실행/적용하는
* 파일**만 본다.
*/
private const ASSET_EXTENSIONS = 'js|mjs|css|woff2?|ttf|otf|eot';
/**
* 코어의 명시 예외 (사유 필수)
*
* @var array<string, string>
*/
private const CORE_EXEMPTIONS = [
// 운영자가 seo.google_analytics_id 를 설정했을 때만 출력되는 외부 분석 서비스다.
// 자체 제공 대상이 아니며 gdpr 차단 카탈로그가 다루는 영역이다.
'googletagmanager.com' => '운영자 설정 시에만 출력되는 외부 분석 서비스',
'google-analytics.com' => '운영자 설정 시에만 출력되는 외부 분석 서비스',
];
/**
* 스캔 대상 파일 목록을 만듭니다.
*
* @return array<int, string> 절대 경로 목록
*/
private function runtimeSources(): array
{
$patterns = [
// 번들 확장 런타임 소스
'modules/_bundled/*/resources/**/*.{ts,tsx,json}',
'modules/_bundled/*/src/**/*.{ts,tsx}',
'plugins/_bundled/*/resources/**/*.{ts,tsx,json}',
'plugins/_bundled/*/src/**/*.{ts,tsx}',
'templates/_bundled/*/src/**/*.{ts,tsx}',
'templates/_bundled/*/layouts/**/*.json',
'templates/_bundled/*/template.json',
'templates/_bundled/*/seo-config.json',
// 코어 런타임 소스
'resources/js/core/**/*.{ts,tsx}',
'resources/layouts/**/*.json',
'resources/views/*.blade.php',
];
$files = [];
foreach ($patterns as $pattern) {
foreach (glob(base_path($pattern), GLOB_BRACE) as $path) {
$files[] = $path;
}
// glob 은 `**` 를 재귀로 해석하지 않으므로 디렉토리 재귀를 따로 돈다
if (str_contains($pattern, '**')) {
$files = array_merge($files, $this->globRecursive($pattern));
}
}
// 설치 마법사 (SPA 부팅 전 화면)
$files[] = base_path('public/install/index.php');
// 테스트 파일은 제외한다 — 차단 대상 URL 을 픽스처로 담는 것이 그 테스트의 일이다
$files = array_filter($files, function (string $path): bool {
$normalized = str_replace('\\', '/', $path);
return is_file($path)
&& ! str_contains($normalized, '/__tests__/')
&& ! str_contains($normalized, '/tests/');
});
return array_values(array_unique($files));
}
/**
* `**` 를 포함한 패턴을 재귀적으로 해석합니다.
*
* @param string $pattern 상대 패턴
* @return array<int, string> 절대 경로 목록
*/
private function globRecursive(string $pattern): array
{
[$prefix, $suffix] = explode('**', $pattern, 2);
$suffix = ltrim($suffix, '/');
$results = [];
foreach (glob(base_path($prefix), GLOB_ONLYDIR | GLOB_BRACE) as $root) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if (! $file->isFile()) {
continue;
}
if (fnmatch($suffix, $file->getBasename(), FNM_CASEFOLD)
|| fnmatch(basename($suffix), $file->getBasename(), FNM_CASEFOLD)) {
$results[] = $file->getPathname();
}
}
}
return $results;
}
/**
* 파일이 속한 확장의 manifest 에서 사유가 선언된 신뢰 호스트를 읽습니다.
*
* @param string $path 파일 절대 경로
* @return array<int, string> 사유가 함께 선언된 호스트 목록
*/
private function declaredHostsWithReason(string $path): array
{
$relative = str_replace('\\', '/', substr($path, strlen(base_path()) + 1));
if (! preg_match('#^(modules|plugins|templates)/_bundled/([^/]+)/#', $relative, $m)) {
return [];
}
$manifestName = match ($m[1]) {
'modules' => 'module.json',
'plugins' => 'plugin.json',
default => 'template.json',
};
$manifestPath = base_path("{$m[1]}/_bundled/{$m[2]}/{$manifestName}");
if (! is_file($manifestPath)) {
return [];
}
$manifest = json_decode((string) file_get_contents($manifestPath), true) ?: [];
$hosts = $manifest['trusted_script_hosts'] ?? [];
$reasons = $manifest['trusted_script_hosts_reason'] ?? [];
if (! is_array($hosts) || ! is_array($reasons)) {
return [];
}
// 사유 없이 선언된 호스트는 예외로 인정하지 않는다 — 왜 외부로 나가는지가
// 코드에 남아야 "자체 제공이 원칙, 예외는 근거와 함께" 가 강제된다.
return array_values(array_filter(
$hosts,
fn ($host) => is_string($host) && ! empty($reasons[$host])
));
}
/**
* @scenario asset_class=vendored, outcome=loaded
* @scenario asset_class=translation, outcome=loaded
* @scenario asset_class=service_sdk, outcome=loaded
*
* @effects no_third_party_request_on_page_load, runtime_asset_served_same_origin
*/
#[Test]
public function 런타임_소스에_외부_자산_ur_l_이_없다(): void
{
// 구분자로 `~` 를 쓴다 — 패턴 안에 URL 프래그먼트(`#`)가 들어가 `#` 구분자와 충돌한다
// 확장자 뒤에 경계를 둔다 — 새 탭으로 여는 외부 페이지(`.jsp`)가 `.js` 로 오탐되면
// 자산이 아닌 링크를 결함으로 세게 된다 (KG이니시스 영수증 링크가 그 예다).
$pattern = '~(?:https?:)?//([A-Za-z0-9._-]+)/[^"\'\s)]*\.(?:'.self::ASSET_EXTENSIONS.')(?![A-Za-z0-9])(?:[?\#][^"\'\s)]*)?~i';
$violations = [];
foreach ($this->runtimeSources() as $path) {
$contents = (string) file_get_contents($path);
if (! preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER)) {
continue;
}
$allowedHosts = array_merge(
$this->declaredHostsWithReason($path),
array_keys(self::CORE_EXEMPTIONS)
);
foreach ($matches as $match) {
[$url, $host] = $match;
if (in_array($host, $allowedHosts, true)) {
continue;
}
// 주석에 남은 설명 문구는 대상이 아니다 — 실제 로드 경로만 본다
if ($this->isInsideComment($contents, $url)) {
continue;
}
$violations[] = str_replace('\\', '/', substr($path, strlen(base_path()) + 1)).' → '.$url;
}
}
$this->assertSame(
[],
array_values(array_unique($violations)),
"구동 자산을 외부 origin 에서 불러오는 지점이 남아 있습니다.\n"
."자체 제공으로 바꾸거나, 자체 제공이 불가능하면 manifest 에\n"
."`trusted_script_hosts` + `trusted_script_hosts_reason` 을 함께 선언하세요.\n"
.implode("\n", array_unique($violations))
);
}
/**
* URL 이 주석 안에 있는지 판정합니다.
*
* @param string $contents 파일 내용
* @param string $url 검출된 URL
* @return bool 주석 안이면 true
*/
private function isInsideComment(string $contents, string $url): bool
{
foreach (explode("\n", $contents) as $line) {
if (! str_contains($line, $url)) {
continue;
}
$trimmed = ltrim($line);
if (str_starts_with($trimmed, '//')
|| str_starts_with($trimmed, '*')
|| str_starts_with($trimmed, '/*')
|| str_starts_with($trimmed, '#')) {
continue;
}
return false;
}
return true;
}
#[Test]
public function 신뢰_호스트를_선언한_확장은_사유도_함께_선언한다(): void
{
$missing = [];
foreach (['modules' => 'module.json', 'plugins' => 'plugin.json', 'templates' => 'template.json'] as $type => $name) {
foreach (glob(base_path("{$type}/_bundled/*/{$name}")) as $manifestPath) {
$manifest = json_decode((string) file_get_contents($manifestPath), true) ?: [];
$hosts = $manifest['trusted_script_hosts'] ?? [];
if (! is_array($hosts) || $hosts === []) {
continue;
}
$reasons = $manifest['trusted_script_hosts_reason'] ?? [];
foreach ($hosts as $host) {
if (empty($reasons[$host])) {
$missing[] = str_replace('\\', '/', substr($manifestPath, strlen(base_path()) + 1)).' → '.$host;
}
}
}
}
$this->assertSame(
[],
$missing,
"외부 호스트를 신뢰 출처로 선언했으면 그 사유도 manifest 에 남겨야 합니다.\n"
.'`trusted_script_hosts_reason` 에 호스트별 사유를 적으세요.'."\n"
.implode("\n", $missing)
);
}
/**
* @effects template_external_asset_field_resolves_to_asset_url
*/
#[Test]
public function 템플릿_externals_는_자체_제공_경로를_쓴다(): void
{
$violations = [];
foreach (glob(base_path('templates/_bundled/*/template.json')) as $manifestPath) {
$manifest = json_decode((string) file_get_contents($manifestPath), true) ?: [];
foreach ($manifest['externals'] ?? [] as $external) {
if (! is_array($external) || ! isset($external['url'])) {
continue;
}
if (preg_match('#^(https?:)?//#i', (string) $external['url']) === 1) {
$violations[] = str_replace('\\', '/', substr($manifestPath, strlen(base_path()) + 1))
.' → '.$external['id'].' ('.$external['url'].')';
}
}
}
$this->assertSame(
[],
$violations,
"템플릿 externals 는 `asset`(자체 제공 경로) 으로 선언해야 합니다.\n"
.implode("\n", $violations)
);
}
}
@@ -0,0 +1,215 @@
<?php
namespace Tests\Feature\Extension;
use App\Extension\Helpers\ExtensionPendingHelper;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use ReflectionMethod;
use Tests\TestCase;
/**
* 사용자 추가 에셋(`custom/`)의 확장 교체 생존 테스트
*
* `custom/` 은 운영자 소유 자리다. 확장 업데이트가 그것을 덮어쓰면 업데이트할 때마다
* 운영자가 넣은 파일이 사라지고, 그 사실이 어디에도 남지 않는다 — 파일이 조용히
* 없어질 뿐이다. 포럼 질문("custom.css 를 어디에 두나요")의 커뮤니티 답변대로
* `src/styles/` 에 넣으면 정확히 그 일이 벌어진다.
*
* 교체 경로가 **둘**이라는 점이 핵심이다:
* 1. 디렉토리 rename (정상 경로)
* 2. 제자리 파일 동기화 (Windows 에서 하위 트리에 열린 핸들이 있어 rename 이 막힐 때)
*
* 한쪽만 보존하면 잠금 상황에서만 조용히 사라진다 — 재현이 어려운 결함이 된다.
*
* DB 를 쓰지 않는다 — 파일 교체 동작만 검증한다.
*/
class CustomAssetPreservationTest extends TestCase
{
/** 테스트 작업 디렉토리 */
private string $workspace;
/** 기존 활성 디렉토리 */
private string $activePath;
/** 새 배포본 소스 */
private string $sourcePath;
protected function setUp(): void
{
parent::setUp();
$this->workspace = storage_path('framework/testing/custom-preserve-'.uniqid());
$this->activePath = $this->workspace.'/plugins/g7test-preserve';
$this->sourcePath = $this->workspace.'/plugins/_bundled/g7test-preserve';
File::ensureDirectoryExists($this->activePath.'/custom');
File::ensureDirectoryExists($this->activePath.'/dist/js');
File::ensureDirectoryExists($this->sourcePath.'/dist/js');
// 운영자가 넣은 파일
File::put($this->activePath.'/custom/custom.css', 'body{--operator:1}');
File::put($this->activePath.'/custom/assets.json', '{"assets":[]}');
// 구버전 산출물 (교체 시 정리되어야 한다)
File::put($this->activePath.'/dist/js/old-hash.js', '// old');
// 새 배포본
File::put($this->sourcePath.'/dist/js/new-hash.js', '// new');
File::put($this->sourcePath.'/plugin.json', '{"identifier":"g7test-preserve"}');
}
protected function tearDown(): void
{
File::deleteDirectory($this->workspace);
parent::tearDown();
}
/**
* 보존 결과를 단언합니다.
*
* @return void
*/
private function assertPreserved(): void
{
$this->assertFileExists(
$this->activePath.'/custom/custom.css',
'운영자가 넣은 파일이 확장 교체에 사라졌습니다.'
);
$this->assertSame(
'body{--operator:1}',
File::get($this->activePath.'/custom/custom.css'),
'운영자 파일의 내용이 새 배포본으로 덮어써졌습니다.'
);
$this->assertFileExists($this->activePath.'/custom/assets.json');
}
/**
* @scenario custom_source=convention_scan, custom_asset=css
*
* @effects custom_dir_survives_extension_update
*/
#[Test]
public function rename_경로에서_운영자_파일이_보존된다(): void
{
ExtensionPendingHelper::copyToActive($this->sourcePath, $this->activePath);
$this->assertPreserved();
$this->assertFileExists($this->activePath.'/dist/js/new-hash.js');
}
#[Test]
public function rename_경로에서도_구버전_산출물은_정리된다(): void
{
// 보존 계층이 stale 산출물 청소를 무력화하면 배포본이 계속 부푼다
ExtensionPendingHelper::copyToActive($this->sourcePath, $this->activePath);
$this->assertFileDoesNotExist($this->activePath.'/dist/js/old-hash.js');
}
/**
* @scenario custom_source=convention_scan, custom_asset=css
*
* @effects custom_dir_survives_inplace_sync_fallback
*/
#[Test]
public function 제자리_동기화_폴백_경로에서도_운영자_파일이_보존된다(): void
{
// rename 이 막히는 상황(Windows 잠금)의 폴백 경로를 직접 태운다
$sync = new ReflectionMethod(ExtensionPendingHelper::class, 'syncDirectoryContents');
$sync->setAccessible(true);
// 스테이징에는 새 배포본 + 운영자 파일이 함께 있어야 한다 (copyToActive 가 그렇게 만든다)
$staging = $this->workspace.'/staging';
File::copyDirectory($this->sourcePath, $staging);
File::copyDirectory($this->activePath.'/custom', $staging.'/custom');
$sync->invoke(null, $staging, $this->activePath, null);
$this->assertPreserved();
$this->assertFileExists($this->activePath.'/dist/js/new-hash.js');
$this->assertFileDoesNotExist($this->activePath.'/dist/js/old-hash.js');
}
#[Test]
public function 스테이징에_운영자_디렉토리가_없어도_정리_대상이_되지_않는다(): void
{
// 소스에 없는 항목을 지우는 정리 로직이 custom/ 을 지우면 안 된다
$stale = new ReflectionMethod(ExtensionPendingHelper::class, 'removeStaleEntries');
$stale->setAccessible(true);
$failures = [];
$stale->invokeArgs(null, [$this->sourcePath, $this->activePath, &$failures, true]);
$this->assertPreserved();
}
#[Test]
public function 새_배포본이_같은_이름의_디렉토리를_담아도_운영자_파일이_우선한다(): void
{
File::ensureDirectoryExists($this->sourcePath.'/custom');
File::put($this->sourcePath.'/custom/custom.css', 'body{--from-vendor:1}');
ExtensionPendingHelper::copyToActive($this->sourcePath, $this->activePath);
$this->assertPreserved();
}
#[Test]
public function 대상_디렉토리가_없으면_그냥_복사한다(): void
{
$fresh = $this->workspace.'/plugins/g7test-fresh';
ExtensionPendingHelper::copyToActive($this->sourcePath, $fresh);
$this->assertFileExists($fresh.'/dist/js/new-hash.js');
$this->assertDirectoryDoesNotExist($fresh.'/custom');
}
/**
* 삭제는 보존이 아니라 보관이다 — 그리고 보관 사실은 호출자에게 도달해야 한다.
*
* 사본 경로가 로그에만 남으면 운영자는 로그를 뒤지지 않는 한 사본의 존재를 모른다.
* 그러면 "확장을 지웠더니 내 CSS 가 사라졌다" 와 구분되지 않는다.
*
* @effects custom_dir_archived_on_uninstall
*/
#[Test]
public function 삭제는_운영자_파일을_보관하고_그_경로를_반환한다(): void
{
$archived = ExtensionPendingHelper::deleteExtensionDirectory(
$this->workspace.'/plugins',
'g7test-preserve'
);
// 확장은 실제로 지워진다 — 보존이 아니라 보관이다.
$this->assertDirectoryDoesNotExist($this->activePath);
// 보관 경로가 반환값으로 올라온다.
$this->assertCount(1, $archived, '보관된 디렉토리 1건이 반환되어야 한다');
$this->assertSame('custom', $archived[0]['directory']);
// 반환된 경로에 운영자 파일이 실제로 있다 — 경로만 돌려주고 사본이 없으면 무의미하다.
$this->assertFileExists($archived[0]['archive'].'/custom.css');
$this->assertSame('body{--operator:1}', File::get($archived[0]['archive'].'/custom.css'));
File::deleteDirectory(dirname($archived[0]['archive']));
}
/**
* 보관할 것이 없으면 빈 배열이다 — 호출부가 "사본이 있다" 고 오인해선 안 된다.
*/
#[Test]
public function 운영자_파일이_없으면_보관_결과가_비어_있다(): void
{
File::deleteDirectory($this->activePath.'/custom');
$archived = ExtensionPendingHelper::deleteExtensionDirectory(
$this->workspace.'/plugins',
'g7test-preserve'
);
$this->assertSame([], $archived);
}
}
@@ -0,0 +1,159 @@
<?php
namespace Tests\Feature\Extension;
use App\Extension\Helpers\ExtensionInstallRollbackHelper;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 회귀: 실패한 설치가 활성 디렉토리를 고아로 남기지 않는다
*
* 설치 흐름은 원본(`_pending`/`_bundled`)을 활성 디렉토리로 **먼저 복사한 뒤** 확장을
* 로드해 코어 버전·의존성·언어 경로를 검증한다. 검증에 로드된 인스턴스가 필요해 순서를
* 뒤집을 수 없는데, 검증이 실패하면 방금 만든 디렉토리가 그대로 남았다.
*
* 남은 디렉토리는 DB 행이 없어 `plugin:list` 에도 뜨지 않고 번들 병합에도 참여하지 않는다.
* 오류도 경고도 없이 디스크만 점유하는 고아이고, 다음 설치 시도가 그것을 "이미 있는
* 설치본" 으로 보고 원본 복사를 건너뛸 수 있다.
*/
class FailedInstallRollsBackActiveDirectoryTest extends TestCase
{
private string $sandbox;
protected function setUp(): void
{
parent::setUp();
$this->sandbox = storage_path('framework/testing/install-rollback-'.uniqid());
File::ensureDirectoryExists($this->sandbox);
}
protected function tearDown(): void
{
File::deleteDirectory($this->sandbox);
parent::tearDown();
}
/**
* 이번 설치가 만든 디렉토리는 제거한다.
*/
public function test_directory_created_by_this_install_is_removed(): void
{
$active = $this->sandbox.DIRECTORY_SEPARATOR.'vendor-sample';
File::ensureDirectoryExists($active);
File::put($active.DIRECTORY_SEPARATOR.'plugin.json', '{}');
$removed = ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$active,
existedBefore: false,
identifier: 'vendor-sample',
type: 'plugin',
);
$this->assertTrue($removed);
$this->assertDirectoryDoesNotExist($active);
}
/**
* 이미 있던 설치본은 건드리지 않는다.
*
* `--force` 재설치가 검증에서 실패한 경우다. 그 디렉토리는 운영자의 기존 설치본이므로
* 여기서 지우면 실패한 재설치가 멀쩡히 돌던 확장을 없애버린다.
*/
public function test_preexisting_directory_is_left_untouched(): void
{
$active = $this->sandbox.DIRECTORY_SEPARATOR.'vendor-existing';
File::ensureDirectoryExists($active);
File::put($active.DIRECTORY_SEPARATOR.'plugin.json', '{"keep":true}');
$removed = ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$active,
existedBefore: true,
identifier: 'vendor-existing',
type: 'plugin',
);
$this->assertFalse($removed);
$this->assertDirectoryExists($active);
$this->assertStringContainsString('keep', File::get($active.DIRECTORY_SEPARATOR.'plugin.json'));
}
/**
* 디렉토리가 아예 없으면 조용히 넘어간다 (복사 이전에 실패한 경우).
*/
public function test_absent_directory_is_a_no_op(): void
{
$this->assertFalse(ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$this->sandbox.DIRECTORY_SEPARATOR.'never-created',
existedBefore: false,
identifier: 'never-created',
type: 'module',
));
}
/**
* 세 관리자의 설치 경로가 모두 이 되돌리기를 경유한다.
*
* 한 곳만 배선하면 나머지 두 유형에서 같은 고아가 계속 생기고, 그 사실은 오류로
* 드러나지 않는다. 배선이 나중에 조용히 빠지는 것도 여기서 막는다.
*
* @return void
*/
public function test_all_three_managers_wire_the_rollback(): void
{
$targets = [
[app_path('Extension/PluginManager.php'), 'installPlugin'],
[app_path('Extension/ModuleManager.php'), 'installModule'],
[app_path('Extension/TemplateManager.php'), 'installTemplate'],
];
foreach ($targets as [$path, $method]) {
$source = File::get($path);
$body = $this->methodBody($source, $method);
$this->assertNotSame('', $body, "{$method} 본문을 찾지 못했습니다.");
$this->assertStringContainsString(
'ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall',
$body,
"{$method} 이 실패 시 활성 디렉토리를 되돌리지 않습니다."
);
}
}
/**
* 소스에서 메서드 본문을 잘라냅니다 (중괄호 균형).
*
* @param string $source PHP 소스 전문
* @param string $method 메서드명
* @return string 본문 (못 찾으면 빈 문자열)
*/
private function methodBody(string $source, string $method): string
{
$start = strpos($source, 'public function '.$method.'(');
if ($start === false) {
return '';
}
$depth = 0;
$began = false;
$length = strlen($source);
for ($i = $start; $i < $length; $i++) {
if ($source[$i] === '{') {
$depth++;
$began = true;
} elseif ($source[$i] === '}') {
$depth--;
if ($began && $depth === 0) {
return substr($source, $start, $i - $start + 1);
}
}
}
return '';
}
}
@@ -0,0 +1,438 @@
<?php
namespace Tests\Feature\Extension;
use App\Console\Commands\Concerns\PrunesBuildOutput;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Contracts\Repositories\TemplateRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Http\Requests\Public\Template\ServeTemplateAssetRequest;
use App\Models\Plugin;
use App\Models\Template;
use App\Rules\SafeTemplatePath;
use App\Seo\SeoRenderer;
use App\Services\ExtensionStaticCacheService;
use App\Services\PluginService;
use App\Services\TemplateService;
use App\Support\AssetUrl;
use App\Support\CustomAssets;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\File;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 동봉 자산 · 사용자 추가 자산의 서빙 테스트
*
* 확장이 담은 구동 자산(`dist/vendor/**`)과 운영자가 넣은 자산(`custom/**`)이 실제로
* 서빙되는지, 그리고 **비활성 확장은 서빙되지 않는지**를 본다. 자산 404 는 예외를
* 남기지 않고 화면 기능만 사라지므로, 경로 규약이 어긋나면 배포본에서만 드러난다.
*
* DB 대신 저장소를 모킹한다 — 검증 대상은 경로 해석과 활성 게이트이지 DB 스키마가 아니다.
*/
class VendoredAssetServingTest extends TestCase
{
/** 테스트용 가짜 템플릿 식별자 */
private const FAKE_TEMPLATE = 'g7test-serving';
/** 테스트용 가짜 플러그인 식별자 */
private const FAKE_PLUGIN = 'g7test-serving-plugin';
protected function setUp(): void
{
parent::setUp();
CustomAssets::flushCache();
// 템플릿: dist/vendor(동봉) + custom(운영자)
File::ensureDirectoryExists(base_path('templates/'.self::FAKE_TEMPLATE.'/dist/vendor/lib/1.0.0/css'));
File::put(base_path('templates/'.self::FAKE_TEMPLATE.'/dist/vendor/lib/1.0.0/css/lib.css'), '/* vendored */');
File::ensureDirectoryExists(base_path('templates/'.self::FAKE_TEMPLATE.'/custom'));
File::put(base_path('templates/'.self::FAKE_TEMPLATE.'/custom/custom.css'), '/* operator */');
File::put(base_path('templates/'.self::FAKE_TEMPLATE.'/custom/notes.txt'), 'not an asset');
// 플러그인: 확장 루트 기준
File::ensureDirectoryExists(base_path('plugins/'.self::FAKE_PLUGIN.'/dist/vendor/lib/1.0.0'));
File::put(base_path('plugins/'.self::FAKE_PLUGIN.'/dist/vendor/lib/1.0.0/lib.js'), '// vendored');
}
protected function tearDown(): void
{
File::deleteDirectory(base_path('templates/'.self::FAKE_TEMPLATE));
File::deleteDirectory(base_path('plugins/'.self::FAKE_PLUGIN));
CustomAssets::flushCache();
AssetUrl::forceMode(null);
Mockery::close();
parent::tearDown();
}
/**
* 저장되지 않은 템플릿 모델을 만듭니다.
*
* @param string $status 확장 상태 값
* @return Template 모델 인스턴스
*/
private function makeTemplate(string $status): Template
{
$template = new Template;
$template->identifier = self::FAKE_TEMPLATE;
$template->status = $status;
return $template;
}
/**
* 저장되지 않은 플러그인 모델을 만듭니다.
*
* @param string $status 확장 상태 값
* @return Plugin 모델 인스턴스
*/
private function makePlugin(string $status): Plugin
{
$plugin = new Plugin;
$plugin->identifier = self::FAKE_PLUGIN;
$plugin->status = $status;
return $plugin;
}
/**
* 지정 상태의 템플릿을 돌려주는 서비스를 만듭니다.
*
* @param string $status 확장 상태 값
* @return TemplateService 모킹된 저장소를 물린 서비스
*/
private function templateService(string $status): TemplateService
{
$repository = Mockery::mock(TemplateRepositoryInterface::class);
$repository->shouldReceive('findByIdentifier')
->andReturn($this->makeTemplate($status));
$this->app->instance(TemplateRepositoryInterface::class, $repository);
return $this->app->make(TemplateService::class);
}
/**
* 지정 상태의 플러그인을 돌려주는 서비스를 만듭니다.
*
* @param string $status 확장 상태 값
* @return PluginService 모킹된 저장소를 물린 서비스
*/
private function pluginService(string $status): PluginService
{
$repository = Mockery::mock(PluginRepositoryInterface::class);
$repository->shouldReceive('findByIdentifier')
->andReturn($this->makePlugin($status));
$this->app->instance(PluginRepositoryInterface::class, $repository);
return $this->app->make(PluginService::class);
}
/**
* @scenario asset_class=vendored, outcome=loaded
*
* @effects runtime_asset_served_same_origin
*/
#[Test]
public function 템플릿_동봉_자산은_dist_이하로_해석된다(): void
{
$result = $this->templateService(ExtensionStatus::Active->value)
->getAssetFilePath(self::FAKE_TEMPLATE, 'vendor/lib/1.0.0/css/lib.css');
$this->assertTrue($result['success'], (string) ($result['error'] ?? ''));
$this->assertSame('text/css', $result['mimeType']);
$this->assertStringContainsString('/dist/vendor/', str_replace('\\', '/', $result['filePath']));
}
/**
* @scenario custom_source=convention_scan, custom_asset=css
*
* @effects custom_asset_loaded_after_extension_bundles
*/
#[Test]
public function 템플릿_운영자_자산은_dist_밖의_custom_으로_해석된다(): void
{
// custom/ 은 빌드 산출물이 아니라 사람이 넣은 파일이고 확장 교체가 보존하는
// 대상이라 dist/ 안에 둘 수 없다 — 서빙도 그 비대칭을 알아야 한다.
$result = $this->templateService(ExtensionStatus::Active->value)
->getAssetFilePath(self::FAKE_TEMPLATE, 'custom/custom.css');
$this->assertTrue($result['success'], (string) ($result['error'] ?? ''));
$normalized = str_replace('\\', '/', $result['filePath']);
$this->assertStringContainsString('/'.self::FAKE_TEMPLATE.'/custom/custom.css', $normalized);
$this->assertStringNotContainsString('/dist/', $normalized);
}
/**
* @scenario custom_source=convention_scan
*
* @effects inactive_extension_custom_not_served
*/
#[Test]
public function 비활성_템플릿의_자산은_서빙되지_않는다(): void
{
$result = $this->templateService(ExtensionStatus::Inactive->value)
->getAssetFilePath(self::FAKE_TEMPLATE, 'vendor/lib/1.0.0/css/lib.css');
$this->assertFalse($result['success']);
$this->assertSame('template_not_found', $result['error']);
}
/**
* @scenario custom_source=convention_scan, custom_asset=static_file
*
* @effects custom_disallowed_extension_blocked
*/
#[Test]
public function 허용되지_않은_확장자는_서빙되지_않는다(): void
{
$result = $this->templateService(ExtensionStatus::Active->value)
->getAssetFilePath(self::FAKE_TEMPLATE, 'custom/notes.txt');
$this->assertFalse($result['success']);
$this->assertSame('file_type_not_allowed', $result['error']);
}
/**
* @effects custom_path_traversal_blocked
*/
#[Test]
public function 경로_이탈은_차단된다(): void
{
$result = $this->templateService(ExtensionStatus::Active->value)
->getAssetFilePath(self::FAKE_TEMPLATE, '../../../.env');
$this->assertFalse($result['success']);
}
#[Test]
public function 플러그인_동봉_자산은_확장_루트_기준으로_해석된다(): void
{
$result = $this->pluginService(ExtensionStatus::Active->value)
->getAssetFilePath(self::FAKE_PLUGIN, 'dist/vendor/lib/1.0.0/lib.js');
$this->assertTrue($result['success'], (string) ($result['error'] ?? ''));
$this->assertSame('application/javascript', $result['mimeType']);
}
#[Test]
public function 비활성_플러그인의_자산은_서빙되지_않는다(): void
{
$result = $this->pluginService(ExtensionStatus::Inactive->value)
->getAssetFilePath(self::FAKE_PLUGIN, 'dist/vendor/lib/1.0.0/lib.js');
$this->assertFalse($result['success']);
$this->assertSame('plugin_not_found', $result['error']);
}
/**
* @effects runtime_asset_served_same_origin
*/
#[Test]
public function 자산_url_은_두_모드_모두_same_origin_이다(): void
{
foreach (['extension', 'extensionless'] as $mode) {
AssetUrl::forceMode($mode);
$url = AssetUrl::templateAsset(self::FAKE_TEMPLATE, 'vendor/lib/1.0.0/css/lib.css', null, false);
$this->assertStringStartsWith('/api/templates/assets/', $url, "모드: {$mode}");
$this->assertDoesNotMatchRegularExpression('#^(https?:)?//#', $url, "모드: {$mode}");
}
}
/**
* 빌드 산출물 정리는 동봉 자산을 지우지 않는다.
*
* vite 의 `emptyOutDir` 를 끄고 정리 책임을 빌드 커맨드로 옮긴 이유가 이것이다.
* 정리 규칙이 vendor 를 함께 지우면 매 빌드마다 동봉 자산이 사라지고, 그 사실은
* 배포본을 열어보기 전까지 드러나지 않는다.
*
*
* @effects vendored_asset_survives_rebuild
*/
#[Test]
public function 빌드_산출물_정리가_동봉_자산을_보존한다(): void
{
$workspace = storage_path('framework/testing/prune-'.uniqid());
File::ensureDirectoryExists($workspace.'/dist/js');
File::ensureDirectoryExists($workspace.'/dist/vendor/lib/1.0.0');
File::put($workspace.'/dist/js/old.js', '// old');
File::put($workspace.'/dist/index.d.ts', 'export {};');
File::put($workspace.'/dist/vendor/lib/1.0.0/lib.js', '// vendored');
$command = new class
{
use PrunesBuildOutput;
/**
* 정리를 실행합니다.
*
* @param string $path 확장 루트 경로
* @return array<int, string> 삭제된 항목
*/
public function run(string $path): array
{
return $this->pruneBuildOutput($path);
}
};
$removed = $command->run($workspace);
$this->assertFileExists($workspace.'/dist/vendor/lib/1.0.0/lib.js', '동봉 자산이 빌드 정리에 삭제됐습니다.');
$this->assertFileDoesNotExist($workspace.'/dist/js/old.js');
$this->assertFileDoesNotExist($workspace.'/dist/index.d.ts');
$this->assertNotContains('vendor', $removed);
File::deleteDirectory($workspace);
}
/**
* 봇 렌더 경로의 스타일시트도 same-origin 자산으로 해석된다.
*
* 검색엔진이 보는 화면이 사용자 화면과 다른 자산을 쓰면, 자체 제공 전환이 그 경로에서만
* 무력화된다 — 그리고 그 사실은 봇 화면을 따로 열어보기 전까지 드러나지 않는다.
*
*
* @effects bot_render_path_uses_same_origin_asset, runtime_asset_served_same_origin
*/
#[Test]
public function 봇_렌더_경로의_스타일시트가_same_origin_으로_해석된다(): void
{
$renderer = $this->app->make(SeoRenderer::class);
$method = new \ReflectionMethod($renderer, 'resolveConfigStylesheets');
$method->setAccessible(true);
$resolved = $method->invoke($renderer, [
'vendor/font-awesome/6.4.0/css/all.inlined.css',
'https://cdn.example.com/keep-as-is.css',
'/api/templates/assets/t/already-absolute.css',
], self::FAKE_TEMPLATE);
$this->assertStringStartsWith('/api/templates/assets/', $resolved[0]);
$this->assertStringNotContainsString('/dist/', $resolved[0]);
// 절대 URL 과 이미 절대 경로인 항목은 그대로 둔다 (판정 범위를 넘지 않는다)
$this->assertSame('https://cdn.example.com/keep-as-is.css', $resolved[1]);
$this->assertSame('/api/templates/assets/t/already-absolute.css', $resolved[2]);
}
/**
* 자산 요청 검증의 컨테인먼트 기준이 **실제로 읽는 디렉토리**와 일치한다.
*
* 템플릿 자산은 `dist/` 이하가 기본이지만 `custom/` 만은 그 밖에 있다. 검증 기준을
* `dist` 로 고정하면 `custom/**` 은 realpath 가 실패해 문자열 접두 비교로만 통과하므로,
* 검증한 경로와 읽는 경로가 서로 다른 상태가 된다. 그 상태는 오류를 남기지 않는다 —
* 룰이 realpath 존재를 필수로 바꾸는 순간 custom 서빙만 조용히 404 가 된다.
*
* @effects custom_asset_containment_base_matches_serving_root
*/
#[Test]
public function 자산_요청_검증_기준_경로가_서빙_경로와_일치한다(): void
{
$base = fn (string $path): string => (function () {
$rules = $this->rules();
foreach ($rules['path'] as $rule) {
if ($rule instanceof SafeTemplatePath) {
$property = new \ReflectionProperty($rule, 'basePath');
$property->setAccessible(true);
return $property->getValue($rule);
}
}
return '';
})->call($this->makeAssetRequest($path));
// custom/ 은 확장 루트 기준 — TemplateService::getAssetFilePath 와 같은 분기
$this->assertSame(
base_path('templates/'.self::FAKE_TEMPLATE),
$base('custom/custom.css')
);
// 그 외에는 종전대로 dist 기준
$this->assertSame(
base_path('templates/'.self::FAKE_TEMPLATE.'/dist'),
$base('vendor/font-awesome/6.4.0/css/all.inlined.css')
);
}
/**
* 정적 게시가 운영자 소유 자산(`custom/`)을 자기 원본 루트로 싣는다.
*
* 게시하지 않으면 이 자산만 API 경로에 남는데, 그 경로에서는 CSS 내부 상대 `url()`
* 이 해석되지 않는다 — 문서가 안내하는 "폰트·이미지를 custom/ 에 두고 상대 경로로
* 참조" 가 성립하지 않는다. 정적 확장자 URL 은 public 아래 실제 파일일 때만 200 이
* 되므로 게시가 유일한 성립 조건이다.
*
* @effects custom_asset_published_with_extension_assets
*/
#[Test]
public function 정적_게시가_운영자_자산을_자기_루트로_싣는다(): void
{
$service = $this->app->make(ExtensionStaticCacheService::class);
$method = new \ReflectionMethod($service, 'publishTemplate');
$method->setAccessible(true);
// publishTemplate 이 custom 원본을 **자기 호출로** 게시하는지 — 소스에 두 번째
// publishDistAssets 호출이 있고 그 대상이 custom 루트임을 구조로 확인한다.
$source = file_get_contents(app_path('Services/ExtensionStaticCacheService.php'));
$this->assertStringContainsString(
'base_path("templates/{$identifier}/".CustomAssets::DIRECTORY)',
$source,
'custom 원본을 게시하는 호출이 없습니다 — 상대 url() 이 다시 깨집니다.'
);
$this->assertStringContainsString(
'excludeCustom: false',
$source,
'custom 원본 게시에서 custom 제외 가드가 꺼져 있지 않습니다 — 하위가 조용히 누락됩니다.'
);
}
/**
* dist 원본으로 들어온 `custom/` 하위는 여전히 건너뛴다.
*
* 운영자 파일은 자기 원본 루트로 게시되므로, dist 를 통해 한 번 더 실리면 같은
* 파일이 두 경로에 놓여 어느 쪽이 유효한지가 갈린다.
*
* @effects custom_asset_published_with_extension_assets
*/
#[Test]
public function dist_원본에서는_운영자_디렉토리를_건너뛴다(): void
{
$service = $this->app->make(ExtensionStaticCacheService::class);
$method = new \ReflectionMethod($service, 'isCustomAssetPath');
$method->setAccessible(true);
$this->assertTrue($method->invoke($service, CustomAssets::DIRECTORY.'/custom.css'));
$this->assertTrue($method->invoke($service, CustomAssets::DIRECTORY.'/fonts/MyFont.woff2'));
$this->assertTrue($method->invoke($service, CustomAssets::DIRECTORY));
// 이름이 겹치는 정상 산출물까지 막지 않는다
$this->assertFalse($method->invoke($service, 'css/custom-theme.css'));
$this->assertFalse($method->invoke($service, 'vendor/font-awesome/6.4.0/css/all.inlined.css'));
}
/**
* 테스트용 자산 요청을 만든다 (라우트 파라미터 해석까지 재현).
*/
private function makeAssetRequest(string $path): ServeTemplateAssetRequest
{
$request = ServeTemplateAssetRequest::create(
'/api/templates/assets/'.self::FAKE_TEMPLATE.'/'.$path
);
$route = new Route(['GET'], '/api/templates/assets/{identifier}/{path}', []);
$route->parameters = ['identifier' => self::FAKE_TEMPLATE, 'path' => $path];
$request->setRouteResolver(fn () => $route);
$request->merge(['identifier' => self::FAKE_TEMPLATE, 'path' => $path]);
return $request;
}
}