Files
Gnuboard7/modules/_bundled/sirsoft-page/tests/Feature/PageAttachmentPolicyTest.php
T
HeuJung d17ea28da5 fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정
관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다.
설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자
리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다.

경계값 SSoT 도입:
- config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로
 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
- 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다.

적용되지 않던 정책을 실제로 적용:
- 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을
 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함)
- 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에
 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로
- 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책,
 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세

파생 결함:
- 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는
 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고,
 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다.
- 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자
 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로
 두고, 빈 목록 자체를 캐시하지 않는다.
- 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다.
- 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여).

재발 방지:
- audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프)
- 테스트 실행 범위 강제 훅(check-test-scope)
- 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착)

공개 이슈: gnuboard/g7
2026-07-30 07:52:24 +09:00

181 lines
6.3 KiB
PHP

<?php
namespace Modules\Sirsoft\Page\Tests\Feature;
use Modules\Sirsoft\Page\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Page\Http\Requests\UploadPageAttachmentRequest;
use Modules\Sirsoft\Page\Models\PageAttachment;
use Modules\Sirsoft\Page\Module;
use Modules\Sirsoft\Page\Services\PageAttachmentService;
use Modules\Sirsoft\Page\Tests\ModuleTestCase;
/**
* 페이지 첨부 정책(개수·용량·형식) 강제 테스트 (E3)
*
* 수정 전에는 `config/settings/defaults.json` 의 `attachment.*` 가 SSoT 로 선언만 되고
* 참조가 0건이었습니다. Request 는 `max:10240` + mimes 16종을 하드코딩했고(설정은 MIME 6종),
* 개수 강제는 어디에도 없었습니다.
*
* 주의: 현행 하드코딩 값(10240KB)과 우연히 일치하면 수정 전에도 green 이 되므로,
* 용량 검증은 반드시 기본값과 다른 설정값을 주입해 판정합니다.
*/
class PageAttachmentPolicyTest extends ModuleTestCase
{
/**
* 첨부 설정을 주입합니다.
*
* 모듈 설정은 SettingsServiceProvider 가 `g7_settings.modules.*` config 로 올려 두고
* `g7_module_settings()` 로 조회한다 (board 관례).
*
* @param array $overrides 덮어쓸 설정 값
*/
private function writeAttachmentSettings(array $overrides = []): void
{
config(['g7_settings.modules.sirsoft-page.attachment' => array_merge([
'max_count' => 5,
'max_size_mb' => 10,
'allowed_types' => ['image/jpeg', 'image/png', 'application/pdf'],
], $overrides)]);
}
/**
* 임시 첨부를 N 개 만듭니다.
*
* @param string $tempKey 임시 키
* @param int $count 생성 개수
*/
private function seedTempAttachments(string $tempKey, int $count): void
{
for ($i = 0; $i < $count; $i++) {
PageAttachment::create([
'page_id' => null,
'temp_key' => $tempKey,
'collection' => 'attachments',
'original_filename' => "temp-{$i}.png",
'stored_filename' => "temp-{$i}.png",
'path' => "temp/{$tempKey}/temp-{$i}.png",
'mime_type' => 'image/png',
'size' => 100,
'order' => $i,
]);
}
}
/**
* 설정한 최대 용량이 검증 규칙에 반영되는지 테스트합니다.
*/
public function test_max_size_setting_is_reflected_in_rules(): void
{
// 기본값(10MB)과 다른 값이어야 하드코딩과의 우연한 일치를 피할 수 있다
$this->writeAttachmentSettings(['max_size_mb' => 5]);
$rules = (new UploadPageAttachmentRequest)->rules();
$this->assertContains('max:5120', $rules['file']);
$this->assertNotContains('max:10240', $rules['file']);
}
/**
* 허용 형식이 설정의 MIME 목록으로 강제되는지 테스트합니다.
*/
public function test_allowed_types_use_mimetypes_from_settings(): void
{
$this->writeAttachmentSettings(['allowed_types' => ['image/png', 'application/pdf']]);
$rules = (new UploadPageAttachmentRequest)->rules();
$this->assertContains('mimetypes:image/png,application/pdf', $rules['file']);
// 수정 전: mimes:jpg,jpeg,png,... 16종 하드코딩 (설정과 무관)
foreach ($rules['file'] as $rule) {
$this->assertStringNotContainsString('mimes:jpg', (string) $rule);
}
}
/**
* 허용 형식 목록이 비면 형식을 제한하지 않는지 테스트합니다 (탈출구).
*/
public function test_empty_allowed_types_disables_type_restriction(): void
{
$this->writeAttachmentSettings(['allowed_types' => []]);
$rules = (new UploadPageAttachmentRequest)->rules();
foreach ($rules['file'] as $rule) {
$this->assertStringNotContainsString('mimetypes:', (string) $rule);
}
}
/**
* temp_key 연결이 개수 상한을 초과하면 차단되는지 테스트합니다.
*/
public function test_temp_key_link_over_limit_is_blocked(): void
{
$this->writeAttachmentSettings(['max_count' => 5]);
$tempKey = 'tk_'.str_repeat('a', 20);
$this->seedTempAttachments($tempKey, 8);
$this->expectException(AttachmentLimitExceededException::class);
app(PageAttachmentService::class)->linkTempAttachmentsWithMove($tempKey, 1);
}
/**
* 상한과 같은 개수는 통과하는지 테스트합니다 (경계).
*/
public function test_link_at_limit_passes(): void
{
$this->writeAttachmentSettings(['max_count' => 5]);
$tempKey = 'tk_'.str_repeat('b', 20);
$this->seedTempAttachments($tempKey, 5);
app(PageAttachmentService::class)->assertAttachmentCountWithin(null, 5, 'tk_none');
$this->assertTrue(true);
}
/**
* 기존 첨부와 합산해 판정하는지 테스트합니다.
*/
public function test_existing_plus_new_over_limit_is_blocked(): void
{
$this->writeAttachmentSettings(['max_count' => 5]);
$tempKey = 'tk_'.str_repeat('c', 20);
$this->seedTempAttachments($tempKey, 4);
$this->expectException(AttachmentLimitExceededException::class);
app(PageAttachmentService::class)->assertAttachmentCountWithin(null, 2, $tempKey);
}
/**
* 상한 미설정(0)이면 제한하지 않는지 테스트합니다.
*/
public function test_zero_limit_is_unrestricted(): void
{
$this->writeAttachmentSettings(['max_count' => 0]);
app(PageAttachmentService::class)->assertAttachmentCountWithin(null, 100, null);
$this->assertTrue(true);
}
/**
* 스토리지 디스크가 모듈 설정에 의존하지 않는지 테스트합니다.
*
* 설정 파일 자체가 이 디스크에 저장되므로 여기서 module_setting() 을 호출하면
* 설정 로드 → getStorage() → getStorageDisk() → 설정 로드 무한 재귀가 된다.
* (기존 `config('sirsoft-page.attachment.disk')` 참조도 해당 config 가 없어 항상 폴백이었다.)
*/
public function test_storage_disk_does_not_depend_on_module_settings(): void
{
$this->writeAttachmentSettings();
$module = new Module;
$this->assertSame('modules', $module->getStorageDisk());
}
}