Files
Gnuboard7/modules/_bundled/sirsoft-board/src/Http/Requests/UploadAttachmentRequest.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

139 lines
5.0 KiB
PHP

<?php
namespace Modules\Sirsoft\Board\Http\Requests;
use App\Extension\HookManager;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ResolvesAllowedExtensions;
use Modules\Sirsoft\Board\Http\Requests\Concerns\ValidatesAttachmentCount;
use Modules\Sirsoft\Board\Models\Board;
/**
* 게시판 첨부파일 업로드 요청 검증
*
* 첨부 개수 상한은 게시글 작성 Request 들과 같이 여기서도 선차단한다 — 최종 불변조건은
* `AttachmentService::assertAttachmentCountWithin()` 이 담당하지만(모든 경로가 지나는
* SSoT), 요청 계층에서 막으면 다른 검증 오류와 같은 422 필드 오류 형태로 돌아가 업로더가
* 응답을 분기하지 않아도 된다. 두 계층은 합산 기준·우선순위가 동일하므로 판정이 갈리지 않는다.
*/
class UploadAttachmentRequest extends FormRequest
{
use ResolvesAllowedExtensions;
use ValidatesAttachmentCount;
/**
* 요청 권한 확인
*
* @return bool 항상 true (권한은 미들웨어에서 검증)
*/
public function authorize(): bool
{
return true;
}
/**
* 검증 규칙
*
* @return array<string, mixed>
*/
public function rules(): array
{
$slug = $this->route('slug');
$board = Board::where('slug', $slug)->first();
// 게시판이 없으면 기본 규칙 반환
if (! $board) {
return [
'file' => ['required', 'file'],
'post_id' => ['nullable', 'integer', 'min:1'],
'collection' => ['sometimes', 'string', 'max:100'],
'temp_key' => ['nullable', 'string', 'max:64'],
];
}
// 게시판 설정을 기반으로 한 검증 규칙
$maxSizeMB = $board->max_file_size ?? 10;
$maxSizeKB = $maxSizeMB * 1024;
// 게시판 값이 비어 있으면(null 또는 []) 모듈 기본값으로 폴백한다.
// 빈 배열을 그대로 쓰면 'mimes:' 빈 규칙이 되어 전 파일이 거부된다.
$defaults = g7_module_settings('sirsoft-board', 'basic_defaults', []);
$allowedExtensions = $this->resolveAllowedExtensions(
$board->allowed_extensions,
$defaults['allowed_extensions'] ?? null
);
$mimes = implode(',', $allowedExtensions);
$rules = [
'file' => ['required', 'file', 'max:'.$maxSizeKB, 'mimes:'.$mimes],
'post_id' => ['nullable', 'integer', 'min:1'],
'collection' => ['sometimes', 'string', 'max:100'],
'temp_key' => ['nullable', 'string', 'max:64'],
];
// 모듈/플러그인이 validation rules를 동적으로 추가할 수 있도록 훅 제공
return HookManager::applyFilters('sirsoft-board.attachment.upload_validation_rules', $rules, $this);
}
/**
* 검증 메시지
*
* @return array<string, string>
*/
public function messages(): array
{
$slug = $this->route('slug');
$board = Board::where('slug', $slug)->first();
$maxSizeMB = $board?->max_file_size ?? 10;
return [
'file.required' => __('sirsoft-board::validation.attachment.file_required'),
'file.file' => __('sirsoft-board::validation.attachment.file_invalid'),
'file.max' => __('sirsoft-board::validation.attachment.file_max', ['max' => $maxSizeMB]),
'file.mimes' => __('sirsoft-board::validation.attachment.file_mimes'),
'post_id.required' => __('sirsoft-board::validation.attachment.post_id_required'),
'post_id.integer' => __('sirsoft-board::validation.attachment.post_id_invalid'),
];
}
/**
* 첨부 개수 상한을 선차단합니다.
*
* @param Validator $validator 검증기
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
// 필드 규칙(용량·확장자)이 이미 걸린 요청에는 개수 판정을 덧붙이지 않는다 —
// 파일 자체가 거부될 요청까지 상한 초과로 보고하면 원인이 뒤바뀐다.
if ($validator->errors()->isNotEmpty()) {
return;
}
$postId = $this->input('post_id');
$this->assertSingleAttachmentSlotAvailable(
Board::where('slug', $this->route('slug'))->first(),
$postId !== null && $postId !== '' ? (int) $postId : null,
$this->input('temp_key')
);
});
}
/**
* 검증 전 데이터 준비
*/
protected function prepareForValidation(): void
{
// query string으로 전달된 temp_key, post_id를 body로 merge
$this->merge([
'collection' => $this->collection ?? 'attachments',
'temp_key' => $this->query('temp_key') ?? $this->temp_key,
'post_id' => $this->query('post_id') ?? $this->post_id,
]);
}
}