Files
Gnuboard7/tests/Unit/Support/TemplateExternalsTest.php
T
HeuJung 3945b6f1b3 feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)
공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다.

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

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

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

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

동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에
써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
2026-08-27 16:47:14 +09:00

263 lines
11 KiB
PHP

<?php
namespace Tests\Unit\Support;
use App\Support\TemplateExternals;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class TemplateExternalsTest extends TestCase
{
use RefreshDatabase;
public function test_normalizes_supported_externals_and_attributes(): void
{
$externals = TemplateExternals::normalize([
[
'id' => 'style-main',
'type' => 'style',
'url' => 'https://cdn.example.com/main.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => true,
'integrity' => 'sha384-style',
'referrerpolicy' => 'no-referrer',
'media' => 'screen',
],
[
'id' => 'script-default',
'type' => 'script',
'url' => 'https://cdn.example.com/default.js',
'defer' => true,
],
[
'id' => 'preload-font',
'type' => 'preload',
'url' => 'https://cdn.example.com/font.woff2',
'as' => 'font',
'mimeType' => 'font/woff2',
'fetchpriority' => 'high',
'crossorigin' => 'use-credentials',
],
]);
$this->assertCount(3, $externals);
$this->assertSame('anonymous', $externals[0]['crossorigin']);
$this->assertSame('before-template', $externals[1]['position']);
$this->assertTrue($externals[1]['defer']);
$this->assertSame('font/woff2', $externals[2]['mimeType']);
$this->assertSame('high', $externals[2]['fetchpriority']);
$styleAttributes = TemplateExternals::linkAttributes($externals[0]);
$this->assertSame('stylesheet', $styleAttributes['rel']);
$this->assertSame('https://cdn.example.com/main.css', $styleAttributes['href']);
$this->assertSame('style-main', $styleAttributes['id']);
$this->assertSame('screen', $styleAttributes['media']);
$scriptAttributes = TemplateExternals::scriptAttributes($externals[1]);
$this->assertSame('https://cdn.example.com/default.js', $scriptAttributes['src']);
$this->assertTrue($scriptAttributes['defer']);
}
public function test_filters_invalid_and_legacy_external_declarations(): void
{
$externals = TemplateExternals::normalize([
['url' => 'https://legacy.example.com/style.css'],
['type' => 'style', 'url' => 'http://cdn.example.com/insecure.css'],
['type' => 'preload', 'url' => 'https://cdn.example.com/missing-as.woff2'],
['type' => 'script', 'url' => 'https://cdn.example.com/both.js', 'async' => true, 'defer' => true],
['type' => 'script', 'url' => 'https://cdn.example.com/invalid-position.js', 'position' => 'after-core'],
['type' => 'style', 'url' => 'https://cdn.example.com/valid.css'],
['type' => 'style', 'url' => 'https://cdn.example.com/valid.css'],
]);
$this->assertSame([
[
'type' => 'style',
'url' => 'https://cdn.example.com/valid.css',
],
], $externals);
}
public function test_resource_hints_are_deduplicated_by_type_and_origin(): void
{
$externals = TemplateExternals::normalize([
[
'type' => 'preconnect',
'url' => 'https://cdn.example.com',
'crossorigin' => 'anonymous',
],
[
'type' => 'webfont',
'url' => 'https://cdn.example.com/font.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => true,
],
[
'type' => 'dns-prefetch',
'url' => 'https://static.example.com',
],
]);
$hints = TemplateExternals::resourceHints($externals);
$this->assertCount(2, $hints);
$this->assertSame('preconnect', $hints[0]['type']);
$this->assertSame('https://cdn.example.com', $hints[0]['url']);
$this->assertSame('dns-prefetch', $hints[1]['type']);
}
/**
* 자체 제공 자산(asset) 선언은 same-origin 자산 URL 로 해석된다.
*
* @scenario asset_class=vendored, outcome=loaded
*
* @effects template_external_asset_field_resolves_to_asset_url, runtime_asset_served_same_origin
*/
public function test_asset_field_resolves_to_same_origin_asset_url(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'fontawesome', 'type' => 'style', 'asset' => 'vendor/font-awesome/6.4.0/css/all.inlined.css'],
], 'sirsoft-basic', 123);
$this->assertCount(1, $normalized);
$this->assertStringStartsWith('/api/templates/assets/sirsoft-basic', $normalized[0]['url']);
$this->assertStringNotContainsString('/dist/', $normalized[0]['url']);
$this->assertDoesNotMatchRegularExpression('#^(https?:)?//#', $normalized[0]['url']);
}
/**
* same-origin 항목에서는 외부 전용 키를 무시한다.
*
* 자기 서버 자산에 preconnect 를 걸거나 CORS 모드를 붙일 이유가 없다.
*
*
* @effects template_external_same_origin_ignores_preconnect_and_crossorigin
*/
public function test_same_origin_item_drops_external_only_keys(): void
{
$normalized = TemplateExternals::normalize([
[
'id' => 'pretendard',
'type' => 'webfont',
'asset' => 'vendor/pretendard/1.3.9/pretendard-variable.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => 'anonymous',
],
], 'sirsoft-basic', 1);
$this->assertArrayNotHasKey('preconnect', $normalized[0]);
$this->assertArrayNotHasKey('crossorigin', $normalized[0]);
$this->assertSame([], TemplateExternals::resourceHints($normalized));
}
/**
* same-origin 절대 경로 url 도 그대로 통과시킨다.
*
*
* @effects template_external_asset_field_resolves_to_asset_url
*/
public function test_same_origin_path_url_is_accepted(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'x', 'type' => 'style', 'url' => '/api/templates/assets/t/vendor/a.css'],
], 't', null);
$this->assertCount(1, $normalized);
$this->assertSame('/api/templates/assets/t/vendor/a.css', $normalized[0]['url']);
}
/**
* 브라우저가 외부 origin 으로 해석하는 형태는 same-origin 으로 인정하지 않는다.
*
* 접두 문자열만 보면 path 처럼 보이지만 브라우저는 authority 로 읽는 값들이다.
*
* @scenario asset_class=vendored, outcome=failed
*
* @effects template_external_invalid_url_is_logged_not_silently_dropped
*/
public function test_authority_bypass_shapes_are_rejected(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'a', 'type' => 'style', 'url' => '//evil.example.com/x.css'],
['id' => 'b', 'type' => 'style', 'url' => '/\\evil.example.com/x.css'],
['id' => 'c', 'type' => 'style', 'url' => 'ftp://evil.example.com/x.css'],
], 't', null);
$this->assertSame([], $normalized);
}
/**
* asset 경로가 확장 디렉토리를 벗어나면 거부한다.
*
*
* @effects template_external_invalid_url_is_logged_not_silently_dropped
*/
public function test_asset_path_escape_is_rejected(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'a', 'type' => 'style', 'asset' => '../../.env'],
['id' => 'b', 'type' => 'style', 'asset' => '/etc/passwd'],
], 'sirsoft-basic', null);
$this->assertSame([], $normalized);
}
/**
* 구동 자산(style/webfont/script)에는 실패 신호가 붙는다.
*
* 이 태그들은 서버가 HTML 에 직접 심으므로, 브라우저가 자산에 도달하지 못해도
* 자바스크립트에는 아무 신호가 오지 않는다. 실패는 "아이콘이 0×0 으로 사라진 화면"
* 으로만 나타나고 자체 서버 로그에도 흔적이 남지 않아 운영자가 원인을 특정할 수 없다.
* `onerror` 가 그 유일한 통로다.
*/
public function test_runtime_assets_carry_a_failure_signal(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'fontawesome', 'type' => 'style', 'asset' => 'vendor/font-awesome/6.4.0/css/all.css'],
['id' => 'pretendard', 'type' => 'webfont', 'asset' => 'vendor/pretendard/1.3.9/pretendard.css'],
['id' => 'bootstrapper', 'type' => 'script', 'asset' => 'vendor/boot/boot.js'],
], 'sirsoft-basic', 1);
$this->assertCount(3, $normalized);
foreach ($normalized as $item) {
$attributes = $item['type'] === 'script'
? TemplateExternals::scriptAttributes($item)
: TemplateExternals::linkAttributes($item);
$this->assertArrayHasKey('onerror', $attributes, $item['id'].' 에 실패 신호가 있어야 한다');
$this->assertStringContainsString('__g7ExternalAssetFailed', $attributes['onerror']);
$this->assertStringContainsString("'".$item['id']."'", $attributes['onerror']);
}
}
/**
* 힌트(preload/preconnect 등)에는 실패 신호를 붙이지 않는다.
*
* 힌트는 실패해도 화면 기능이 사라지지 않는다. 여기에까지 배너를 띄우면 안내가
* 잡음이 되어 정작 조작 불능을 만드는 실패가 묻힌다.
*/
public function test_resource_hints_do_not_carry_a_failure_signal(): void
{
$normalized = TemplateExternals::normalize([
['id' => 'pre', 'type' => 'preload', 'asset' => 'vendor/font.woff2', 'as' => 'font'],
], 'sirsoft-basic', 1);
$this->assertCount(1, $normalized);
$this->assertArrayNotHasKey('onerror', TemplateExternals::linkAttributes($normalized[0]));
}
/**
* 실패 신호 라벨은 id 가 없으면 파일명으로 떨어진다 (운영자가 대상을 알아볼 수 있어야 한다).
*/
public function test_failure_signal_label_falls_back_to_file_name(): void
{
$normalized = TemplateExternals::normalize([
['type' => 'style', 'asset' => 'vendor/font-awesome/6.4.0/css/all.inlined.css'],
], 'sirsoft-basic', 1);
$this->assertCount(1, $normalized);
$this->assertStringContainsString("'all.inlined.css'", TemplateExternals::linkAttributes($normalized[0])['onerror']);
}
}