fix(core,extensions): 확장 쓰기 경로 공통화 · HTMLPurifier 정의 캐시 storage 이전
https://github.com/gnuboard/g7/issues/125 — 상품 상세설명을 HTML 로 저장할 때 HTMLPurifier 가 모듈 vendor 폴더 안에 정의 캐시를 만들려다 실패해 저장이 매번 500 으로 끝나던 문제를 고친다. vendor 를 읽기 전용으로 두는 표준 배포에서 그 쓰기는 예외가 아니라 PHP 경고로 나오고 Laravel 이 이를 ErrorException 으로 승격시킨다. 캐시는 설정 해시당 1회만 기록되므로 캐시가 영영 생기지 않아 재시도해도 같은 결과였다. 캐시 경로를 storage 아래로 옮기고, 그 경로마저 확보하지 못하면 캐시만 끄고 정화는 그대로 수행한다 — 캐시는 성능 장치이고 정화는 보안 장치라, 전자의 실패가 후자를 건너뛰게 만들면 안 된다. 저장은 성공하므로 운영자에게 도달하는 흔적이 로그 하나뿐이라 error 수준으로 남긴다 (출하 기본 로그 수준이 error 라 warning 은 기본 설치 상태에서 파일에 남지 않는다). 그 과정에서 갈라져 있던 두 축을 코어 한 곳으로 모은다. - 쓰기 디렉토리 확보: 억제 생성·chmod·setgid·소유권 상속·쓰기 판정 절차가 정적 게시와 정의 캐시 두 곳에 서로 다른 하드닝으로 복제돼 있었다(억제 mkdir·setgid·clearstatcache 가 사본마다 한쪽씩 빠져 있었다). FilePermissionHelper 의 ensureWritableDirectory 와 hardenDirectory 로 통합하고, 실패 사유는 out 파라미터로 올려 정책(조용한 성능 저하 대 시끄러운 실패)은 호출부가 정하게 둔다. - 확장 저장 경로: storage_path('app/modules/…') 손조립이 30곳에 흩어져 있어 테스트 격리 분기를 넣으려면 사본마다 복제해야 했고, 한 곳만 빠뜨려도 그 확장의 테스트가 운영 설정 파일을 덮어쓴다. 디스크 root 를 단일 출처로 읽는 ExtensionStoragePath 로 전환하고 테스트 분기는 config/filesystems.php 한 줄에서 끝낸다. 함께 고친 것 - 테스트가 운영 라우트 캐시로 부팅해 확장 allowlist 가 라우트 축에서 통째로 무력화되던 문제. 삭제가 아니라 경로를 돌린다 — 라우트 캐시는 확장 작업 전까지 재생성되지 않아, 삭제하면 운영 사이트가 그때까지 라우트 파일 스캔 경로로 떨어진다. - PHPUnit 프로세스가 확장 vendor 의 제3자 composer 패키지를 오토로드하지 않아 그 패키지를 쓰는 코드 경로가 통째로 테스트 불가였던 문제. 확장 자신의 오토로더를 그대로 쓰면 활성 디렉토리가 _bundled 를 이기고 base path 유추까지 깨지므로, 생성된 맵에서 제3자 항목만 골라 별도 로더로 등록한다. - 게시 폴더가 setgid 를 갖지 않아, 명령줄과 웹이 번갈아 만든 하위 폴더를 다른 쪽이 쓰지 못하던 문제. - 관리자 템플릿이 HTML 정화 라이브러리를 직접 지정하지 않아 전이 의존으로 딸려온 구버전이 쓰이던 문제. 동반 산출물 - 규정 표(·AGENTS.md) 6행 + storage-driver/service-repository/testing-guide 문서 - audit 룰 2종 + coverage 6항목. 저장소가 이미 전량 전환돼 전수 실행이 공허 통과하므로 판정식은 픽스처 36건이 잠근다 - INSTALL.md 에 설치 후 파일 권한 절 추가 (vendor 쓰기 권한 불요를 명시)
This commit is contained in:
1 parent
fc27a6edf6
commit
85e266d361
88 files changed
+1913
-332
No files matched your search
@@ -12,6 +12,7 @@
|
||||
- 글 상세를 공유할 때의 미리보기 이미지(og:image)에도 같은 기준이 적용됩니다.
|
||||
|
||||
### Changed
|
||||
- 코어 최소 요구 버전을 7.0.10 으로 상향
|
||||
|
||||
- 알림 설정의 채널 서브탭이 확장 채널의 통합 탭 선언을 지원합니다. 묶인 채널 중 하나라도 켜져 있으면 통합 탭이 노출됩니다.
|
||||
- 게시판 알림 템플릿 편집 창이 확장 채널 전용 편집 영역을 제공합니다. 채널을 제공하는 확장이 그 채널의 템플릿 편집기와 저장 버튼을 같은 창 안에 넣을 수 있으며, 이때 코어의 제목/본문 입력과 미리보기·저장은 숨겨지고 수신자 규칙은 그대로 편집할 수 있습니다.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ko": "게시판 관리를 위한 모듈",
|
||||
"en": "Module for board management"
|
||||
},
|
||||
"g7_version": ">=7.0.9",
|
||||
"g7_version": ">=7.0.10",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Board\Services;
|
||||
use App\Contracts\Extension\ModuleSettingsInterface;
|
||||
use App\Contracts\Repositories\NotificationDefinitionRepositoryInterface;
|
||||
use App\Services\NotificationDefinitionService;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use App\Traits\NormalizesSettingsData;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -453,18 +454,15 @@ class BoardSettingsService implements ModuleSettingsInterface
|
||||
/**
|
||||
* 설정 저장 경로 반환
|
||||
*
|
||||
* testing 환경에서는 운영 설정(storage/app/modules/.../settings)을 보호하기 위해
|
||||
* 격리된 임시 경로를 사용합니다. 설정 저장을 수행하는 테스트가 운영 basic_defaults.json
|
||||
* 등을 덮어쓰거나 지우는 것을 차단합니다(운영 설정 영구 보존).
|
||||
* 경로는 `modules` 디스크 root(`config/filesystems.php`)를 단일 출처로 삼는다. 그 root 가
|
||||
* 테스트 환경에서 운영 데이터와 격리된 경로를 가리키므로, 운영 설정(storage/app/modules/
|
||||
* .../settings)을 덮어쓰지 않기 위한 분기를 이 서비스가 따로 들고 있지 않는다 — 분기를
|
||||
* 확장마다 복사하면 한 곳만 빠뜨려도 그 확장의 테스트가 조용히 운영 파일을 건드린다.
|
||||
*
|
||||
* @return string 설정 파일 저장 디렉토리 경로
|
||||
*/
|
||||
private function getStoragePath(): string
|
||||
{
|
||||
if (app()->runningUnitTests()) {
|
||||
return storage_path('framework/testing/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
}
|
||||
|
||||
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings');
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ namespace Modules\Sirsoft\Board\Tests\Feature\Admin;
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
@@ -42,7 +43,7 @@ class BoardSettingsControllerTest extends ModuleTestCase
|
||||
// 일반 사용자 생성 (권한 없음)
|
||||
$this->normalUser = $this->createUser();
|
||||
|
||||
$this->settingsStoragePath = storage_path('app/modules/sirsoft-board/settings');
|
||||
$this->settingsStoragePath = ExtensionStoragePath::module('sirsoft-board', 'settings');
|
||||
|
||||
// 테스트 전 저장소 정리
|
||||
if (File::isDirectory($this->settingsStoragePath)) {
|
||||
|
||||
@@ -236,6 +236,8 @@ class BoardSetSettingPipelineTest extends ModuleTestCase
|
||||
*/
|
||||
public function test_storage_path_is_isolated_during_tests(): void
|
||||
{
|
||||
// audit:allow extension-storage-path-hand-assembled 운영 경로를 **의도적으로** 가리킨다 —
|
||||
// 이 단언의 대상은 "테스트가 운영 파일을 건드리지 않았는가" 이므로 해석기를 쓰면 검사가 성립하지 않는다.
|
||||
$productionPath = storage_path('app/modules/sirsoft-board/settings/basic_defaults.json');
|
||||
// 운영 파일의 존재 여부·내용을 그대로 스냅샷 (환경마다 상태가 다르므로 변화 없음만 단언)
|
||||
$before = File::exists($productionPath) ? File::get($productionPath) : null;
|
||||
|
||||
@@ -4,6 +4,16 @@
|
||||
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
|
||||
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
|
||||
|
||||
## [1.2.1] - 2026-08-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 상세설명을 편집기(HTML)로 작성한 상품을 등록하거나 수정할 때 저장이 실패하던 문제를 수정했습니다. 상품 설명의 보안 정화에 쓰는 구성요소가 모듈 설치 폴더 안에 자기 캐시 파일을 만들려 했기 때문에, 보안상 모듈 폴더에 쓰기를 막아 둔 서버에서는 저장이 항상 오류로 끝났고 다시 시도해도 같은 결과였습니다. 이제 이 캐시는 `storage` 폴더 아래에 만들어지며, 그 위치마저 쓸 수 없는 경우에는 캐시 없이 정화만 수행해 저장이 실패하지 않습니다(설명은 종전과 똑같이 정화됩니다). (#125 @lyg-kaban 님께서 제보해주셨습니다.)
|
||||
|
||||
### Changed
|
||||
|
||||
- 코어 최소 요구 버전을 7.0.10 으로 상향
|
||||
|
||||
## [1.2.0] - 2026-08-24
|
||||
|
||||
### Added
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "modules/sirsoft-ecommerce",
|
||||
"description": "Ecommerce module for Gnuboard7",
|
||||
"type": "library",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"license": "MIT",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
"ko": "이커머스",
|
||||
"en": "Ecommerce"
|
||||
},
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"license": "MIT",
|
||||
"description": {
|
||||
"ko": "그누보드7 이커머스 모듈 - 상품, 주문, 결제 관리",
|
||||
"en": "Gnuboard7 Ecommerce Module - Product, Order, Payment Management"
|
||||
},
|
||||
"g7_version": ">=7.0.9",
|
||||
"g7_version": ">=7.0.10",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@g7/sirsoft-ecommerce",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@g7/sirsoft-ecommerce",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"devDependencies": {
|
||||
"jsdom": "^27.4.0",
|
||||
"typescript": "^5.3.3",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@g7/sirsoft-ecommerce",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"description": "그누보드7 이커머스 모듈 프론트엔드 에셋",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleSettingsInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use App\Traits\NormalizesSettingsData;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -610,19 +611,16 @@ class EcommerceSettingsService implements ModuleSettingsInterface
|
||||
/**
|
||||
* 설정 저장 경로 반환
|
||||
*
|
||||
* testing 환경에서는 운영 설정(storage/app/modules/.../settings)을 보호하기 위해
|
||||
* 격리된 임시 경로를 사용합니다. 설정 저장 API를 호출하는 Feature 테스트가
|
||||
* 운영 mileage.json 등을 덮어쓰는 것을 차단합니다(운영 설정 영구 보존).
|
||||
* 경로는 `modules` 디스크 root(`config/filesystems.php`)를 단일 출처로 삼는다. 그 root 가
|
||||
* 테스트 환경에서 운영 데이터와 격리된 경로를 가리키므로, 운영 설정(storage/app/modules/
|
||||
* .../settings)을 덮어쓰지 않기 위한 분기를 이 서비스가 따로 들고 있지 않는다 — 분기를
|
||||
* 확장마다 복사하면 한 곳만 빠뜨려도 그 확장의 테스트가 조용히 운영 파일을 건드린다.
|
||||
*
|
||||
* @return string 설정 파일 저장 디렉토리 경로
|
||||
*/
|
||||
private function getStoragePath(): string
|
||||
{
|
||||
if (app()->runningUnitTests()) {
|
||||
return storage_path('framework/testing/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
}
|
||||
|
||||
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Search\SearchPagePolicy;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use App\Support\Query\BoundedCount;
|
||||
use App\Support\Query\BoundedPage;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
@@ -11,6 +13,7 @@ use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Pagination\CursorPaginator;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\OptionHasOrderHistoryException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ProductHasOrderHistoryException;
|
||||
@@ -54,6 +57,25 @@ class ProductService
|
||||
*/
|
||||
protected ?\HTMLPurifier $purifier = null;
|
||||
|
||||
/**
|
||||
* 이 모듈의 식별자
|
||||
*/
|
||||
private const MODULE_IDENTIFIER = 'sirsoft-ecommerce';
|
||||
|
||||
/**
|
||||
* HTMLPurifier 정의 캐시 디렉토리 권한
|
||||
*
|
||||
* 0775 인 이유: CLI(스케줄러/큐)와 웹(php-fpm)이 같은 캐시를 공유해야 한다. 그룹 쓰기가
|
||||
* 없으면 먼저 만든 프로세스가 상대를 잠근다. `Cache.SerializerPermissions` 로 HTMLPurifier 가
|
||||
* 만드는 하위 디렉토리에도 전파되며, `.ser` 파일에는 `$chmod & 0666` 이 적용되어 0664 가 된다.
|
||||
*/
|
||||
private const PURIFIER_CACHE_DIR_MODE = 0775;
|
||||
|
||||
/**
|
||||
* 정의 캐시 비활성 통지를 프로세스당 1회만 남기기 위한 플래그
|
||||
*/
|
||||
private static bool $purifierCacheWarned = false;
|
||||
|
||||
/**
|
||||
* 시스템 기본통화 코드 조회
|
||||
*
|
||||
@@ -1330,12 +1352,7 @@ class ProductService
|
||||
}
|
||||
|
||||
if ($this->purifier === null) {
|
||||
$config = \HTMLPurifier_Config::createDefault();
|
||||
$config->set('HTML.Allowed', 'p,br,strong,em,b,i,u,s,ul,ol,li,a[href|target],img[src|alt|width|height],h1,h2,h3,h4,h5,h6,table,tr,td,th,thead,tbody,tfoot,caption,colgroup,col,blockquote,pre,code,div,span[style],hr');
|
||||
$config->set('CSS.AllowedProperties', 'color,background-color,font-size,font-weight,text-align,text-decoration,margin,padding,border,width,height');
|
||||
$config->set('Attr.AllowedFrameTargets', ['_blank']);
|
||||
$config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true]);
|
||||
$this->purifier = new \HTMLPurifier($config);
|
||||
$this->purifier = $this->createPurifier();
|
||||
}
|
||||
|
||||
foreach ($data['description'] as $locale => $content) {
|
||||
@@ -1347,6 +1364,113 @@ class ProductService
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTMLPurifier 인스턴스를 생성합니다.
|
||||
*
|
||||
* 정의 캐시 경로를 `storage/` 아래로 강제합니다. 지정하지 않으면 HTMLPurifier 는 자기 설치
|
||||
* 폴더(`{module}/vendor/ezyang/htmlpurifier/library/.../DefinitionCache/Serializer/`)에 캐시를
|
||||
* 쓰는데, 배포본의 vendor 를 읽기 전용으로 두는 서버에서는 그 쓰기가 `E_USER_WARNING` 을 내고
|
||||
* Laravel 이 이를 `ErrorException` 으로 승격시켜 상품 등록/수정이 매번 500 이 됩니다 (공개 #125).
|
||||
* 캐시는 설정 해시당 1회만 기록되므로 쓰기 불가 환경에서는 캐시가 영영 생기지 않아 모든 요청이
|
||||
* 실패합니다.
|
||||
*
|
||||
* 캐시 디렉토리를 확보하지 못하면 정의 캐시만 끄고(`Cache.DefinitionImpl = null`) 정화는 그대로
|
||||
* 수행합니다 — 캐시는 성능 장치이고 정화는 보안 장치라, 캐시 실패가 보안 장치를 건너뛰게
|
||||
* 만들어서는 안 됩니다.
|
||||
*
|
||||
* @return \HTMLPurifier 설정이 적용된 인스턴스
|
||||
*/
|
||||
protected function createPurifier(): \HTMLPurifier
|
||||
{
|
||||
$cachePath = $this->resolvePurifierCachePath($failure);
|
||||
|
||||
if ($cachePath === null && ! self::$purifierCacheWarned) {
|
||||
self::$purifierCacheWarned = true;
|
||||
|
||||
// `error` 로 남기는 이유: G7 출하 기본값(config/settings/defaults.json)의 `log_level` 이
|
||||
// `error` 라, `warning` 으로 남기면 기본 설치 상태에서는 이 통지가 로그 파일에 아예
|
||||
// 기록되지 않는다. 저장은 성공하므로 사용자 피해는 없지만, 캐시를 못 쓰는 상태가
|
||||
// 흔적 없이 영구히 유지되어 운영자가 조치할 근거를 얻지 못한다.
|
||||
Log::error('HTMLPurifier 정의 캐시 디렉토리를 사용할 수 없어 캐시 없이 동작합니다', [
|
||||
'module' => self::MODULE_IDENTIFIER,
|
||||
'expected_path' => $this->purifierCacheDirectory(),
|
||||
// 사유마다 고쳐야 할 대상이 다르다 — 상위 디렉토리 권한 / 그 자리를 차지한 파일 /
|
||||
// 대상 자신의 권한. 사유 없이 경로만 남기면 운영자가 어디를 볼지 알 수 없다.
|
||||
'reason' => $failure['reason'] ?? 'unknown',
|
||||
'blocking_path' => $failure['path'] ?? $this->purifierCacheDirectory(),
|
||||
'impact' => '상품 설명(HTML) 정화가 요청마다 정의를 다시 계산합니다. 해당 디렉토리의 쓰기 권한을 확인하세요.',
|
||||
]);
|
||||
}
|
||||
|
||||
return new \HTMLPurifier($this->buildPurifierConfig($cachePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* HTMLPurifier 설정을 조립합니다.
|
||||
*
|
||||
* @param string|null $cachePath 정의 캐시 디렉토리 절대 경로 (null 이면 캐시 비활성)
|
||||
* @return \HTMLPurifier_Config 조립된 설정
|
||||
*/
|
||||
protected function buildPurifierConfig(?string $cachePath): \HTMLPurifier_Config
|
||||
{
|
||||
$config = \HTMLPurifier_Config::createDefault();
|
||||
$config->set('HTML.Allowed', 'p,br,strong,em,b,i,u,s,ul,ol,li,a[href|target],img[src|alt|width|height],h1,h2,h3,h4,h5,h6,table,tr,td,th,thead,tbody,tfoot,caption,colgroup,col,blockquote,pre,code,div,span[style],hr');
|
||||
$config->set('CSS.AllowedProperties', 'color,background-color,font-size,font-weight,text-align,text-decoration,margin,padding,border,width,height');
|
||||
$config->set('Attr.AllowedFrameTargets', ['_blank']);
|
||||
$config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true]);
|
||||
|
||||
if ($cachePath === null) {
|
||||
$config->set('Cache.DefinitionImpl', null);
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
$config->set('Cache.SerializerPath', $cachePath);
|
||||
// HTMLPurifier 가 `{경로}/HTML` 하위 디렉토리와 `.ser` 파일을 만들 때 쓰는 권한.
|
||||
// 기본값 0755 는 CLI 가 먼저 만들면 웹 계정이 못 쓴다.
|
||||
$config->set('Cache.SerializerPermissions', self::PURIFIER_CACHE_DIR_MODE);
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의 캐시 디렉토리를 확보하고 절대 경로를 반환합니다.
|
||||
*
|
||||
* 디렉토리가 이미 있는데 쓰기 불가라면 요청 경로에서 권한을 고치려 들지 않고 null 을
|
||||
* 돌려줍니다 — 호출측이 캐시를 끄고 정화는 그대로 수행합니다.
|
||||
*
|
||||
* 확보 자체(경고를 내지 않는 생성 · umask 무력화 · POSIX setgid · 소유권 상속 · 쓰기 판정)는
|
||||
* 코어 공통 프리미티브가 맡습니다. 그 프리미티브는 예외도 PHP 경고도 내지 않으므로, 이 수정이
|
||||
* 막으려던 500 이 확보 실패 지점에서 다시 나는 일이 없습니다.
|
||||
*
|
||||
* @param array{reason: string, path: string}|null $failure out — 확보 실패 사유와 그 대상 경로
|
||||
* @return string|null 사용 가능한 절대 경로. 확보 실패 시 null
|
||||
*/
|
||||
protected function resolvePurifierCachePath(?array &$failure = null): ?string
|
||||
{
|
||||
$dir = $this->purifierCacheDirectory();
|
||||
|
||||
return FilePermissionHelper::ensureWritableDirectory($dir, self::PURIFIER_CACHE_DIR_MODE, $failure)
|
||||
? $dir
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의 캐시 디렉토리의 절대 경로 (존재 여부와 무관한 순수 계산).
|
||||
*
|
||||
* 경로는 코어 해석기가 `modules` 디스크 root 를 단일 출처로 삼아 조립합니다.
|
||||
* `getStorageBasePath('cache')` 를 경유하지 않는 이유는 그 반환값이 `Storage::disk()->path()`
|
||||
* 위임이라, 확장이 카테고리 디스크를 비로컬(S3 등)로 오버라이드하면 파일시스템 경로가 아니게
|
||||
* 되기 때문입니다 — HTMLPurifier 는 `file_put_contents` 로 쓰므로 반드시 로컬 절대 경로여야
|
||||
* 합니다.
|
||||
*
|
||||
* @return string 절대 경로
|
||||
*/
|
||||
protected function purifierCacheDirectory(): string
|
||||
{
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'cache/htmlpurifier');
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO 동기화 플래그를 적용합니다 (서버 SSoT).
|
||||
*
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Concerns;
|
||||
|
||||
/**
|
||||
* HTMLPurifier 정의 캐시 위치 검사 헬퍼 (공개 #125 회귀)
|
||||
*
|
||||
* 정의 캐시가 모듈 설치 폴더(vendor) 대신 `storage/` 아래에 기록되는지를 확인하는
|
||||
* 테스트들이 공유합니다.
|
||||
*/
|
||||
trait InspectsHtmlPurifierCache
|
||||
{
|
||||
/**
|
||||
* 테스트 환경에서 정의 캐시가 기록되어야 하는 디렉토리 절대 경로.
|
||||
*
|
||||
* `ProductService::purifierCacheDirectory()` 의 테스트 분기와 동일해야 합니다.
|
||||
*
|
||||
* @return string 절대 경로
|
||||
*/
|
||||
protected function purifierStorageBase(): string
|
||||
{
|
||||
return storage_path('framework/testing/modules/sirsoft-ecommerce/cache/htmlpurifier');
|
||||
}
|
||||
|
||||
/**
|
||||
* HTMLPurifier 가 자기 설치 폴더를 캐시 기본값으로 쓸 때의 경로.
|
||||
*
|
||||
* `HTMLPurifier_DefinitionCache_Serializer::generateBaseDirectoryPath()` 의 폴백과 동일식입니다.
|
||||
*
|
||||
* @return string|null 절대 경로. HTMLPurifier 미로드 시 null
|
||||
*/
|
||||
protected function vendorSerializerBase(): ?string
|
||||
{
|
||||
return defined('HTMLPURIFIER_PREFIX')
|
||||
? HTMLPURIFIER_PREFIX.'/HTMLPurifier/DefinitionCache/Serializer'
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리 하위 `.ser` 파일의 "경로 => mtime:size" 스냅샷을 만듭니다.
|
||||
*
|
||||
* @param string|null $base 검사할 디렉토리 절대 경로 (null 이거나 미존재면 빈 배열)
|
||||
* @return array<string, string> 경로를 키로 정렬된 스냅샷
|
||||
*/
|
||||
protected function serSnapshot(?string $base): array
|
||||
{
|
||||
if ($base === null || ! is_dir($base)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$snapshot = [];
|
||||
$it = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($base, \FilesystemIterator::SKIP_DOTS)
|
||||
);
|
||||
|
||||
foreach ($it as $file) {
|
||||
if ($file->isFile() && str_ends_with($file->getFilename(), '.ser')) {
|
||||
$snapshot[$file->getPathname()] = $file->getMTime().':'.$file->getSize();
|
||||
}
|
||||
}
|
||||
|
||||
ksort($snapshot);
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\Admin;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Sequence;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\Concerns\InspectsHtmlPurifierCache;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* HTML 상세설명 상품 등록의 정의 캐시 경로 회귀 테스트 (공개 #125)
|
||||
*
|
||||
* 실제 등록 엔드포인트를 태워, 정의 캐시가 모듈 설치 폴더(vendor)가 아니라 `storage/` 아래에
|
||||
* 기록되는지와 두 번째 저장이 기존 캐시를 재사용하는지를 확인합니다.
|
||||
*/
|
||||
class ProductStoreHtmlDescriptionCacheTest extends ModuleTestCase
|
||||
{
|
||||
use InspectsHtmlPurifierCache;
|
||||
|
||||
private $user;
|
||||
|
||||
private Category $category;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->assertTrue(
|
||||
class_exists(\HTMLPurifier::class),
|
||||
'HTMLPurifier 가 로드되지 않았습니다. 모듈 vendor 가 설치되어 있고 '
|
||||
.'tests/bootstrap.php 의 확장 vendor 오토로드 등록이 동작하는지 확인하세요.'
|
||||
);
|
||||
|
||||
$defaultConfig = SequenceType::PRODUCT->getDefaultConfig();
|
||||
Sequence::firstOrCreate(
|
||||
['type' => SequenceType::PRODUCT->value],
|
||||
[
|
||||
'algorithm' => $defaultConfig['algorithm']->value,
|
||||
'prefix' => $defaultConfig['prefix'],
|
||||
'current_value' => 0,
|
||||
'increment' => 1,
|
||||
'min_value' => 1,
|
||||
'max_value' => $defaultConfig['max_value'],
|
||||
'cycle' => false,
|
||||
'pad_length' => $defaultConfig['pad_length'],
|
||||
'max_history_count' => $defaultConfig['max_history_count'],
|
||||
]
|
||||
);
|
||||
|
||||
$this->user = $this->createAdminUser([
|
||||
'sirsoft-ecommerce.products.read',
|
||||
'sirsoft-ecommerce.products.create',
|
||||
'sirsoft-ecommerce.products.update',
|
||||
]);
|
||||
|
||||
$this->category = new Category([
|
||||
'name' => ['ko' => '테스트 카테고리', 'en' => 'Test Category'],
|
||||
'slug' => 'issue125-category',
|
||||
'is_active' => true,
|
||||
'depth' => 0,
|
||||
]);
|
||||
$this->category->path = 'temp';
|
||||
$this->category->save();
|
||||
$this->category->generatePath();
|
||||
$this->category->save();
|
||||
|
||||
File::deleteDirectory($this->purifierStorageBase());
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->purifierStorageBase());
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML 상세설명 상품 등록 payload.
|
||||
*
|
||||
* @param string $productCode 상품코드
|
||||
* @return array 등록 요청 body
|
||||
*/
|
||||
private function htmlProductData(string $productCode): array
|
||||
{
|
||||
return [
|
||||
'name' => ['ko' => 'ISSUE125 상품', 'en' => 'ISSUE125 Product'],
|
||||
'product_code' => $productCode,
|
||||
'category_ids' => [$this->category->id],
|
||||
'list_price' => 10000,
|
||||
'selling_price' => 9000,
|
||||
'stock_quantity' => 10,
|
||||
'sales_status' => 'on_sale',
|
||||
'display_status' => 'visible',
|
||||
'tax_status' => 'taxable',
|
||||
'description_mode' => 'html',
|
||||
'description' => ['ko' => '<p>설명</p><script>alert(1)</script>'],
|
||||
'options' => [
|
||||
[
|
||||
'option_code' => $productCode.'-O1',
|
||||
'option_name' => ['ko' => '기본옵션', 'en' => 'Default Option'],
|
||||
'option_values' => [
|
||||
['key' => ['ko' => '색상'], 'value' => ['ko' => '빨강']],
|
||||
],
|
||||
'list_price' => 10000,
|
||||
'selling_price' => 9000,
|
||||
'stock_quantity' => 10,
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML 상세설명 상품을 등록하면 정의 캐시가 storage 아래에 기록됩니다.
|
||||
*
|
||||
* 거짓 green 경고: 개발 머신 vendor 에는 이미 같은 이름의 `.ser` 가 있어 "vendor 스냅샷
|
||||
* 불변" 단언은 수정 전에도 통과할 수 있다. 결함을 증명하는 것은 storage 스냅샷 단언이다.
|
||||
*
|
||||
* @scenario description_mode=html, cache_dir=writable
|
||||
*
|
||||
* @effects definition_cache_written_under_storage, vendor_install_directory_never_written
|
||||
*/
|
||||
public function test_store_with_html_description_writes_cache_under_storage(): void
|
||||
{
|
||||
$vendorBefore = $this->serSnapshot($this->vendorSerializerBase());
|
||||
|
||||
$response = $this->actingAs($this->user)
|
||||
->postJson('/api/modules/sirsoft-ecommerce/admin/products', $this->htmlProductData('ISSUE125-001'));
|
||||
|
||||
$response->assertCreated();
|
||||
|
||||
$this->assertNotEmpty(
|
||||
$this->serSnapshot($this->purifierStorageBase()),
|
||||
'storage 아래에 정의 캐시가 기록되지 않았습니다.'
|
||||
);
|
||||
$this->assertSame(
|
||||
$vendorBefore,
|
||||
$this->serSnapshot($this->vendorSerializerBase()),
|
||||
'HTMLPurifier 설치 폴더에 정의 캐시가 기록되었습니다.'
|
||||
);
|
||||
|
||||
$description = $response->json('data.description');
|
||||
$this->assertStringNotContainsString('<script', is_array($description) ? ($description['ko'] ?? '') : (string) $description);
|
||||
}
|
||||
|
||||
/**
|
||||
* 두 번째 저장은 이미 기록된 정의 캐시를 재사용합니다 (재기록하지 않음).
|
||||
*
|
||||
* @scenario description_mode=html, cache_dir=already_populated
|
||||
*
|
||||
* @effects second_save_reuses_cached_definition
|
||||
*/
|
||||
public function test_second_store_reuses_existing_definition_cache(): void
|
||||
{
|
||||
$this->actingAs($this->user)
|
||||
->postJson('/api/modules/sirsoft-ecommerce/admin/products', $this->htmlProductData('ISSUE125-002'))
|
||||
->assertCreated();
|
||||
|
||||
$snapshot = $this->serSnapshot($this->purifierStorageBase());
|
||||
$this->assertNotEmpty($snapshot);
|
||||
|
||||
// mtime 해상도가 1초라 같은 초 안의 재기록이 감지되지 않는다 — 과거로 밀어 baseline 확보.
|
||||
foreach (array_keys($snapshot) as $path) {
|
||||
touch($path, time() - 3600);
|
||||
}
|
||||
$baseline = $this->serSnapshot($this->purifierStorageBase());
|
||||
|
||||
$this->actingAs($this->user)
|
||||
->postJson('/api/modules/sirsoft-ecommerce/admin/products', $this->htmlProductData('ISSUE125-003'))
|
||||
->assertCreated();
|
||||
|
||||
$this->assertSame(
|
||||
$baseline,
|
||||
$this->serSnapshot($this->purifierStorageBase()),
|
||||
'두 번째 저장이 정의 캐시를 다시 기록했습니다 (재사용되지 않음).'
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
@@ -117,6 +117,8 @@ class EcommerceSettingsOrderSettingsTest extends ModuleTestCase
|
||||
*/
|
||||
public function test_saving_settings_does_not_touch_production_path(): void
|
||||
{
|
||||
// audit:allow extension-storage-path-hand-assembled 운영 경로를 **의도적으로** 가리킨다 —
|
||||
// 이 단언의 대상은 "테스트가 운영 파일을 건드리지 않았는가" 이므로 해석기를 쓰면 검사가 성립하지 않는다.
|
||||
$productionFile = storage_path('app/modules/sirsoft-ecommerce/settings/order_settings.json');
|
||||
$existedBefore = File::exists($productionFile);
|
||||
$contentBefore = $existedBefore ? File::get($productionFile) : null;
|
||||
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\Concerns\InspectsHtmlPurifierCache;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use Psr\Log\AbstractLogger;
|
||||
|
||||
/**
|
||||
* HTMLPurifier 정의 캐시 경로 회귀 테스트 (공개 #125)
|
||||
*
|
||||
* `sanitizeDescription()` 이 정의 캐시 경로를 지정하지 않으면 HTMLPurifier 는 자기 설치 폴더
|
||||
* (`{module}/vendor/ezyang/htmlpurifier/library/.../DefinitionCache/Serializer/`)에 캐시를 쓴다.
|
||||
* 배포본의 vendor 를 읽기 전용으로 두는 서버에서는 그 쓰기가 경고를 내고 Laravel 이 이를
|
||||
* `ErrorException` 으로 승격시켜 상품 등록/수정이 매번 500 이 된다.
|
||||
*/
|
||||
class ProductDescriptionPurifierCacheTest extends ModuleTestCase
|
||||
{
|
||||
use InspectsHtmlPurifierCache;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 하네스 결손(모듈 vendor 미오토로드)을 조용한 skip 으로 감추지 않는다 —
|
||||
// 로드되지 않으면 이 테스트가 검증하려는 코드 경로 자체가 실행되지 않는다.
|
||||
$this->assertTrue(
|
||||
class_exists(\HTMLPurifier::class),
|
||||
'HTMLPurifier 가 로드되지 않았습니다. 모듈 vendor 가 설치되어 있고 '
|
||||
.'tests/bootstrap.php 의 확장 vendor 오토로드 등록이 동작하는지 확인하세요.'
|
||||
);
|
||||
|
||||
// 검증 대상이 이 테스트와 같은 트리(_bundled)의 사본인지 확인한다.
|
||||
// 모듈 vendor 의 composer 오토로더는 자기 PSR-4 를 **활성** 디렉토리로 매핑하고 자신을
|
||||
// prepend 로 등록하므로, 그것을 그대로 로드하면 테스트가 활성 사본을 검증하게 되어
|
||||
// `_bundled` 의 수정이 반영되지 않은 채로도 통과하거나 실패한다 (조용한 오판).
|
||||
$this->assertStringStartsWith(
|
||||
dirname(__DIR__, 3).DIRECTORY_SEPARATOR,
|
||||
(new \ReflectionClass(ProductService::class))->getFileName(),
|
||||
'ProductService 가 이 테스트와 다른 트리에서 로드되었습니다 — 모듈 vendor 오토로더가 '
|
||||
.'자기 PSR-4 를 등록해 활성 디렉토리 사본을 검증하고 있습니다.'
|
||||
);
|
||||
|
||||
$this->purgePurifierCacheBase();
|
||||
$this->resetPurifierCacheNoticeFlag();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->purgePurifierCacheBase();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 캐시 디렉토리를 정리합니다 (파일이 자리를 차지한 경우 포함).
|
||||
*/
|
||||
private function purgePurifierCacheBase(): void
|
||||
{
|
||||
$base = $this->purifierStorageBase();
|
||||
|
||||
foreach ([$base, dirname($base)] as $path) {
|
||||
if (is_file($path)) {
|
||||
@unlink($path);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log 파사드를 기록용 로거로 교체하고 그 기록기를 돌려줍니다.
|
||||
*
|
||||
* `Log::spy()` 는 쓰지 않는다 — `LogManager` 가 `__call` 로 임의 메서드를 받아 넘기므로
|
||||
* Mockery 스파이가 `shouldHaveReceived('error')` 를 `warning` 호출에도 통과시킨다(무효 단언).
|
||||
*
|
||||
* @return object `calls` 배열(level/message)을 보유한 기록기
|
||||
*/
|
||||
private function swapLogRecorder(): object
|
||||
{
|
||||
$recorder = new class extends AbstractLogger
|
||||
{
|
||||
/** @var array<int, array{level: string, message: string}> */
|
||||
public array $calls = [];
|
||||
|
||||
public function log($level, string|\Stringable $message, array $context = []): void
|
||||
{
|
||||
$this->calls[] = ['level' => (string) $level, 'message' => (string) $message];
|
||||
}
|
||||
};
|
||||
|
||||
Log::swap($recorder);
|
||||
|
||||
return $recorder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 비활성 통지의 "프로세스당 1회" 플래그를 되돌립니다.
|
||||
*
|
||||
* 정적 플래그라 같은 프로세스의 앞선 테스트가 이미 세워 두면 통지가 발화하지 않아,
|
||||
* 통지 단언이 테스트 순서에 따라 조용히 통과/실패한다.
|
||||
*/
|
||||
private function resetPurifierCacheNoticeFlag(): void
|
||||
{
|
||||
$property = new \ReflectionProperty(ProductService::class, 'purifierCacheWarned');
|
||||
$property->setAccessible(true);
|
||||
$property->setValue(null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* `sanitizeDescription()` 을 호출하고 사용된 서비스 인스턴스를 돌려줍니다.
|
||||
*
|
||||
* @param array $data 상품 데이터
|
||||
* @return array{0: ProductService, 1: array} 서비스 인스턴스와 정화 결과
|
||||
*/
|
||||
private function sanitize(array $data): array
|
||||
{
|
||||
// 생성자 의존성이 7개라 수동 new 가 성립하지 않는다.
|
||||
$service = app(ProductService::class);
|
||||
|
||||
$method = new \ReflectionMethod($service, 'sanitizeDescription');
|
||||
$method->setAccessible(true);
|
||||
|
||||
return [$service, $method->invoke($service, $data)];
|
||||
}
|
||||
|
||||
/**
|
||||
* 서비스가 보유한 HTMLPurifier 인스턴스를 꺼냅니다.
|
||||
*
|
||||
* @param ProductService $service 대상 서비스
|
||||
* @return \HTMLPurifier|null 인스턴스 (미생성이면 null)
|
||||
*/
|
||||
private function purifierOf(ProductService $service): ?\HTMLPurifier
|
||||
{
|
||||
$property = new \ReflectionProperty($service, 'purifier');
|
||||
$property->setAccessible(true);
|
||||
|
||||
return $property->getValue($service);
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML 모드 정화 시 정의 캐시가 vendor 가 아니라 storage 아래에 기록됩니다.
|
||||
*
|
||||
* 거짓 green 경고: 개발 머신 vendor 에는 이미 `.ser` 가 있고 설정 해시가 같아 파일명이
|
||||
* 동일하므로 "vendor 스냅샷 불변" 단언은 수정 전에도 통과할 수 있다. 결함을 증명하는 것은
|
||||
* storage 쪽 단언(`Cache.SerializerPath` / `generateFilePath` / `assertFileExists`)이다.
|
||||
*
|
||||
* @scenario description_mode=html, cache_dir=writable
|
||||
*
|
||||
* @effects definition_cache_written_under_storage, vendor_install_directory_never_written
|
||||
*/
|
||||
public function test_definition_cache_is_written_under_storage_not_vendor(): void
|
||||
{
|
||||
$storageBase = $this->purifierStorageBase();
|
||||
$vendorBefore = $this->serSnapshot($this->vendorSerializerBase());
|
||||
|
||||
[$service, $result] = $this->sanitize([
|
||||
'description_mode' => 'html',
|
||||
'description' => ['ko' => '<p>본문</p><script>alert(1)</script>'],
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<p>본문</p>', $result['description']['ko']);
|
||||
$this->assertStringNotContainsString('<script', $result['description']['ko']);
|
||||
|
||||
$purifier = $this->purifierOf($service);
|
||||
$this->assertNotNull($purifier);
|
||||
|
||||
$config = $purifier->config;
|
||||
$this->assertSame($storageBase, $config->get('Cache.SerializerPath'));
|
||||
|
||||
$cacheFile = (new \HTMLPurifier_DefinitionCache_Serializer('HTML'))->generateFilePath($config);
|
||||
$this->assertStringStartsWith($storageBase, $cacheFile);
|
||||
$this->assertFileExists($cacheFile);
|
||||
|
||||
$this->assertSame(
|
||||
$vendorBefore,
|
||||
$this->serSnapshot($this->vendorSerializerBase()),
|
||||
'HTMLPurifier 설치 폴더에 정의 캐시가 기록되었습니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* text 모드는 HTMLPurifier 를 인스턴스화하지 않습니다.
|
||||
*
|
||||
* @scenario description_mode=text, cache_dir=writable
|
||||
*
|
||||
* @effects text_mode_skips_purifier_entirely
|
||||
*/
|
||||
public function test_text_mode_never_touches_purifier(): void
|
||||
{
|
||||
[$service, $result] = $this->sanitize([
|
||||
'description_mode' => 'text',
|
||||
'description' => ['ko' => '<p>본문</p><script>alert(1)</script>'],
|
||||
]);
|
||||
|
||||
$this->assertSame('<p>본문</p><script>alert(1)</script>', $result['description']['ko']);
|
||||
$this->assertNull($this->purifierOf($service));
|
||||
$this->assertDirectoryDoesNotExist($this->purifierStorageBase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 디렉토리를 확보하지 못하면 캐시만 끄고 정화는 그대로 수행합니다.
|
||||
*
|
||||
* 목적지에 같은 이름의 **파일**을 놓아 재현한다 — ACL/chmod 없이 Windows·POSIX 양쪽에서
|
||||
* 결정적이다.
|
||||
*
|
||||
* 거짓 green 경고: vendor 스냅샷 불변 단언은 수정 전에도 통과할 수 있다(위 참조).
|
||||
* 이 테스트의 판정은 `Cache.DefinitionImpl === null` 이다.
|
||||
*
|
||||
* 통지 수준을 함께 잠근다 — 이 폴백은 저장을 성공시키므로 운영자에게 도달하는 흔적이
|
||||
* 그 통지 하나뿐인데, G7 출하 기본 로그 수준(`config/settings/defaults.json` 의 `log_level`)이
|
||||
* `error` 라 `warning` 으로 남기면 기본 설치 상태에서 파일에 기록되지 않는다.
|
||||
*
|
||||
* @scenario description_mode=html, cache_dir=occupied_by_file
|
||||
*
|
||||
* @effects purify_still_strips_script_when_cache_disabled, vendor_install_directory_never_written, cache_disabled_notice_reaches_default_log_level
|
||||
*/
|
||||
public function test_falls_back_to_disabled_definition_cache_when_directory_unusable(): void
|
||||
{
|
||||
$base = $this->purifierStorageBase();
|
||||
File::ensureDirectoryExists(dirname($base));
|
||||
file_put_contents($base, 'occupied');
|
||||
|
||||
$vendorBefore = $this->serSnapshot($this->vendorSerializerBase());
|
||||
|
||||
$recorder = $this->swapLogRecorder();
|
||||
|
||||
[$service, $result] = $this->sanitize([
|
||||
'description_mode' => 'html',
|
||||
'description' => ['ko' => '<p>본문</p><script>alert(1)</script>'],
|
||||
]);
|
||||
|
||||
$notices = array_values(array_filter(
|
||||
$recorder->calls,
|
||||
fn (array $call): bool => str_contains($call['message'], 'HTMLPurifier 정의 캐시 디렉토리를 사용할 수 없어')
|
||||
));
|
||||
|
||||
$this->assertCount(1, $notices, '캐시 비활성 통지가 프로세스당 1회 발화해야 합니다.');
|
||||
$this->assertSame(
|
||||
'error',
|
||||
$notices[0]['level'],
|
||||
'캐시 비활성 통지는 error 수준이어야 합니다 — 출하 기본 로그 수준이 error 라 '
|
||||
.'warning 으로 남기면 기본 설치 상태에서 로그 파일에 기록되지 않고, 이 폴백은 저장을 '
|
||||
.'성공시키므로 운영자에게 도달하는 흔적이 이 통지 하나뿐입니다.'
|
||||
);
|
||||
|
||||
$this->assertStringContainsString('<p>본문</p>', $result['description']['ko']);
|
||||
$this->assertStringNotContainsString('<script', $result['description']['ko']);
|
||||
|
||||
$purifier = $this->purifierOf($service);
|
||||
$this->assertNotNull($purifier);
|
||||
$this->assertNull($purifier->config->get('Cache.DefinitionImpl'));
|
||||
|
||||
$this->assertSame(
|
||||
$vendorBefore,
|
||||
$this->serSnapshot($this->vendorSerializerBase()),
|
||||
'HTMLPurifier 설치 폴더에 정의 캐시가 기록되었습니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 디렉토리 생성 실패가 예외로 승격되지 않습니다.
|
||||
*
|
||||
* `File::ensureDirectoryExists()` 는 `mkdir()` 을 억제 없이 호출하므로, 생성이 실패하면
|
||||
* `E_WARNING` 이 나오고 Laravel `HandleExceptions` 가 이를 `ErrorException` 으로 승격시켜
|
||||
* 요청이 500 이 된다 — 이 이슈가 막으려던 실패가 다른 줄에서 그대로 재현되는 형태다.
|
||||
* 부모 자리에 파일을 놓아 재현한다(ACL/chmod 없이 Windows·POSIX 양쪽에서 결정적).
|
||||
*
|
||||
* @scenario description_mode=html, cache_dir=parent_unusable
|
||||
*
|
||||
* @effects cache_dir_creation_failure_does_not_escalate, purify_still_strips_script_when_cache_disabled
|
||||
*/
|
||||
public function test_directory_creation_failure_does_not_escalate_to_exception(): void
|
||||
{
|
||||
$base = $this->purifierStorageBase();
|
||||
$parent = dirname($base);
|
||||
|
||||
File::deleteDirectory($parent);
|
||||
File::ensureDirectoryExists(dirname($parent));
|
||||
file_put_contents($parent, 'occupied');
|
||||
|
||||
$this->assertFalse(is_dir($base));
|
||||
$this->assertFalse(file_exists($base), '부모가 파일이면 자식 경로는 존재하지 않아야 한다 (전제 확인).');
|
||||
|
||||
[$service, $result] = $this->sanitize([
|
||||
'description_mode' => 'html',
|
||||
'description' => ['ko' => '<p>본문</p><script>alert(1)</script>'],
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<p>본문</p>', $result['description']['ko']);
|
||||
$this->assertStringNotContainsString('<script', $result['description']['ko']);
|
||||
$this->assertNull($this->purifierOf($service)->config->get('Cache.DefinitionImpl'));
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
feature: HTMLPurifier 정의 캐시 경로 재지정 (공개 #125)
|
||||
|
||||
description: |
|
||||
상품 상세설명을 편집기(HTML)로 작성해 저장하면 정화 구성요소(HTMLPurifier)가 정의 캐시를
|
||||
자기 설치 폴더(`{module}/vendor/ezyang/htmlpurifier/library/.../DefinitionCache/Serializer/`)에
|
||||
기록했다. 배포본의 vendor 를 읽기 전용으로 두는 표준 서버에서는 그 쓰기가 예외가 아니라
|
||||
PHP 경고로 나오고 Laravel 이 이를 ErrorException 으로 승격시켜 상품 등록/수정이 500 으로
|
||||
끝났다. 캐시는 설정 해시당 1회만 기록되므로 쓰기 불가 환경에서는 캐시가 영영 생기지 않아
|
||||
매 요청이 같은 실패를 반복했다 (공개 이슈 #125, @lyg-kaban 제보).
|
||||
|
||||
정정은 세 갈래다 — ① 정의 캐시 경로를 `storage/app/modules/{identifier}/cache/htmlpurifier`
|
||||
로 명시 지정하고, ② 그 디렉토리를 우리가 먼저 만든다(HTMLPurifier 는 base 디렉토리가 없으면
|
||||
경고만 내고 만들지 않는다), ③ 그 경로마저 확보하지 못하면 정의 캐시만 끄고 정화는 그대로
|
||||
수행한다. 캐시는 성능 장치이고 정화는 보안 장치라, 캐시 실패가 보안 장치를 건너뛰게
|
||||
만들어서는 안 된다.
|
||||
|
||||
③ 의 폴백은 저장을 성공시키므로 운영자에게 도달하는 흔적이 로그 통지 하나뿐이다. 그 통지는
|
||||
`error` 수준으로 남긴다 — G7 출하 기본 로그 수준(`config/settings/defaults.json` 의
|
||||
`log_level`)이 `error` 라, `warning` 으로 남기면 기본 설치 상태에서 파일에 기록되지 않아
|
||||
캐시를 못 쓰는 상태가 흔적 없이 영구히 유지된다.
|
||||
|
||||
axes:
|
||||
description_mode: [text, html]
|
||||
cache_dir: [writable, occupied_by_file, parent_unusable, already_populated]
|
||||
|
||||
exclusions:
|
||||
- { description_mode: text, cache_dir: occupied_by_file, reason: "text 모드는 HTMLPurifier 를 인스턴스화하지 않아 캐시 상태와 직교" }
|
||||
- { description_mode: text, cache_dir: parent_unusable, reason: "동일 — text 모드는 purifier 경로에 진입하지 않는다" }
|
||||
- { description_mode: text, cache_dir: already_populated, reason: "동일 — text 모드는 purifier 경로에 진입하지 않는다" }
|
||||
|
||||
effects:
|
||||
- definition_cache_written_under_storage
|
||||
- vendor_install_directory_never_written
|
||||
- text_mode_skips_purifier_entirely
|
||||
- purify_still_strips_script_when_cache_disabled
|
||||
- cache_dir_creation_failure_does_not_escalate
|
||||
- cache_disabled_notice_reaches_default_log_level
|
||||
- second_save_reuses_cached_definition
|
||||
|
||||
test_files:
|
||||
- modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/ProductDescriptionPurifierCacheTest.php
|
||||
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Admin/ProductStoreHtmlDescriptionCacheTest.php
|
||||
|
||||
validation:
|
||||
note: |
|
||||
거짓 green 경고: 개발 머신의 vendor 에는 이미 `.ser` 가 있고 설정 해시가 같아 파일명이
|
||||
동일하므로, "vendor 설치 폴더가 쓰이지 않았다" 는 단언만으로는 수정 전에도 통과한다.
|
||||
결함을 실제로 증명하는 것은 storage 쪽 단언이다 — `Cache.SerializerPath` 값,
|
||||
`generateFilePath()` 가 가리키는 경로의 실재, 그리고 폴백 경로에서의
|
||||
`Cache.DefinitionImpl === null`.
|
||||
|
||||
이 테스트들은 모듈 전용 composer 패키지(`\HTMLPurifier`)를 실제로 로드해야 성립한다.
|
||||
PHPUnit 진입점(`autoload-extensions.php`)은 확장 vendor 를 오토로드하지 않으므로 코어
|
||||
`tests/bootstrap.php` 가 확장 vendor 의 생성된 맵에서 제3자 패키지만 골라 등록하며(확장
|
||||
자신의 PSR-4 는 제외 — 활성 디렉토리 사본을 검증하게 되는 것을 막는다),
|
||||
각 테스트는 로드 실패를 조용한 skip 이 아니라 setUp 단언 실패로 드러낸다.
|
||||
+2
-1
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_0\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -79,6 +80,6 @@ class AbsorbLegacyDueDaysIntoAutoCancelDays implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings/order_settings.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/order_settings.json';
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_0\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -81,10 +82,6 @@ class BackfillShippingPolicyCurrency implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/language_currency.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/language_currency.json';
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_0\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -153,10 +154,6 @@ class NormalizeCurrencyBaseUnit implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/language_currency.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/language_currency.json';
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_0\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -137,10 +138,6 @@ class NormalizeCurrencyLocales implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/language_currency.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/language_currency.json';
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_0\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -60,6 +61,6 @@ class RemoveLegacyDefaultLanguage implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings/language_currency.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/language_currency.json';
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_2\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -130,10 +131,6 @@ class PruneEmptyShippingCountryNameLocales implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/shipping.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/shipping.json';
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_5\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
@@ -122,10 +123,6 @@ class BackfillMileageEarnRounding implements DataMigration
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/mileage.json');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings').'/mileage.json';
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -4,6 +4,7 @@ namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_1_1\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -102,7 +103,7 @@ class SoftDeleteOrphanInquiryReplyPosts implements DataMigration
|
||||
$boardIds = [];
|
||||
|
||||
// ① 설정 파일의 board_slug → boards.id 해석
|
||||
$settingsPath = storage_path('app/modules/sirsoft-ecommerce/settings/inquiry.json');
|
||||
$settingsPath = ExtensionStoragePath::module('sirsoft-ecommerce', 'settings').'/inquiry.json';
|
||||
|
||||
if (File::exists($settingsPath) && Schema::hasTable(self::BOARDS_TABLE)) {
|
||||
$settings = json_decode(File::get($settingsPath), true);
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"schema_version": "1.0",
|
||||
"generated_at": "2026-08-22T12:22:17+00:00",
|
||||
"generated_at": "2026-08-28T01:27:59+00:00",
|
||||
"generator": "g7 vendor-bundle:build",
|
||||
"target": "module:sirsoft-ecommerce",
|
||||
"composer_json_sha256": "0556835aa543c462efe9132123b57234fddb66e482898144e7930f6cbedb1a9d",
|
||||
"composer_json_sha256": "4f224863e21777f5ef474a7fcfb7d5f66132551b4c58220a660bd3acb573dfdb",
|
||||
"composer_lock_sha256": "876ca9c2273a33baff878d25050a567018a946412db053930a7f548c4add595d",
|
||||
"zip_sha256": "3127bf97f4342c91cffc0d729eaa70f2a1f74a4a4015288081a082e665ccb9c0",
|
||||
"zip_size": 435548,
|
||||
"zip_sha256": "5f954f1597fc2a39bb601af441e3af3768e303b835c9047f0ade71cb56aec66c",
|
||||
"zip_size": 435549,
|
||||
"package_count": 1,
|
||||
"php_requirement": "^8.2",
|
||||
"g7_version": "7.0.9",
|
||||
"g7_version": "7.0.10",
|
||||
"packages": [
|
||||
{
|
||||
"name": "ezyang/htmlpurifier",
|
||||
|
||||
Binary file not shown.
@@ -14,6 +14,10 @@
|
||||
|
||||
- 페이지 공유 미리보기의 설명(og:description)이 항상 비어 있던 문제를 수정했습니다. 이제 페이지 SEO 설정의 설명이 사용됩니다.
|
||||
|
||||
### Changed
|
||||
|
||||
- 코어 최소 요구 버전을 7.0.10 으로 상향
|
||||
|
||||
## [1.0.3] - 2026-08-19
|
||||
|
||||
### Security
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ko": "정적 페이지(정보/정책/안내) 관리 모듈",
|
||||
"en": "Static page (info/policy/guide) management module"
|
||||
},
|
||||
"g7_version": ">=7.0.9",
|
||||
"g7_version": ">=7.0.10",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Sirsoft\Page\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleSettingsInterface;
|
||||
use App\Support\ExtensionStoragePath;
|
||||
use App\Traits\NormalizesSettingsData;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -253,17 +254,15 @@ class PageSettingsService implements ModuleSettingsInterface
|
||||
/**
|
||||
* 설정 저장 경로 반환
|
||||
*
|
||||
* testing 환경에서는 운영 설정(storage/app/modules/.../settings)을 보호하기 위해
|
||||
* 별도 경로를 사용합니다 — 테스트가 개발/운영 설정을 덮어쓰지 않게 합니다.
|
||||
* 경로는 `modules` 디스크 root(`config/filesystems.php`)를 단일 출처로 삼는다. 그 root 가
|
||||
* 테스트 환경에서 운영 데이터와 격리된 경로를 가리키므로, 운영 설정(storage/app/modules/
|
||||
* .../settings)을 덮어쓰지 않기 위한 분기를 이 서비스가 따로 들고 있지 않는다 — 분기를
|
||||
* 확장마다 복사하면 한 곳만 빠뜨려도 그 확장의 테스트가 조용히 운영 파일을 건드린다.
|
||||
*
|
||||
* @return string 설정 파일 저장 디렉토리 경로
|
||||
*/
|
||||
private function getStoragePath(): string
|
||||
{
|
||||
if (app()->runningUnitTests()) {
|
||||
return storage_path('framework/testing/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
}
|
||||
|
||||
return storage_path('app/modules/'.self::MODULE_IDENTIFIER.'/settings');
|
||||
return ExtensionStoragePath::module(self::MODULE_IDENTIFIER, 'settings');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user