fix(core,board,ecommerce,page): 중첩 리소스 스코프·계층 무결성 결함 12건 일괄 수정
중첩 라우트의 상위 리소스 ID 를 조회 스코프에 반영하지 않아 A 의 경로로 B 의 하위 리소스를 읽거나 변경할 수 있었다. 방어 위치를 Repository where 절(SSoT)로 통일하고 컨트롤러 사후 비교에 의존하지 않게 했다. 같은 리소스의 형제 엔드포인트가 서로 다른 강도로 검증하던 부분도 맞췄다. 계층 리소스는 자기 자신·자손을 부모로 지정하는 순환을 검증 계층에서 차단하고, 검증을 우회하는 경로(시더/훅/오염 데이터)를 위해 path 재귀에 방문 ID 가드를 뒀다. 설정값이 정하는 깊이 상한을 Service 가 리터럴로 재클램프하던 부분을 제거해 게시판 설정이 실제로 적용되게 했다. 쓰기 경로는 validated 기준으로 좁혀 FormRequest 미정의 필드가 fillable 로 새지 않게 했다. 기존 오염 데이터는 업그레이드 스텝이 정리한다(삭제 없이 최상위로 이동). 재발 방지로 audit 룰 3종을 추가하고, 규정 문서와 트러블슈팅 사례를 함께 갱신했다. 공개 이슈: gnuboard/g7
This commit is contained in:
1 parent
9dda22f8e4
commit
abb40ad210
74 files changed
+3880
-192
No files matched your search
@@ -5,6 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CategoryOperationException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryRepositoryInterface;
|
||||
@@ -22,8 +24,8 @@ class CategoryService
|
||||
/**
|
||||
* 계층형 카테고리 목록 조회
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @return Collection
|
||||
* @param array $filters 필터 조건
|
||||
* @return Collection 계층 구조가 적용된 카테고리 컬렉션
|
||||
*/
|
||||
public function getHierarchicalCategories(array $filters = []): Collection
|
||||
{
|
||||
@@ -34,9 +36,9 @@ class CategoryService
|
||||
$filters = HookManager::applyFilters('sirsoft-ecommerce.category.filter_list_query', $filters);
|
||||
|
||||
// hierarchical 플래그가 true이면 전체 트리 구조 반환
|
||||
if (!empty($filters['hierarchical'])) {
|
||||
if (! empty($filters['hierarchical'])) {
|
||||
$categories = Category::getTree(null, $filters['is_active'] ?? false);
|
||||
} elseif (!empty($filters['flat'])) {
|
||||
} elseif (! empty($filters['flat'])) {
|
||||
// flat 플래그가 true이면 평면 리스트 반환 (TagInput 등에 사용)
|
||||
$categories = $this->repository->getFlatList($filters, ['images']);
|
||||
} else {
|
||||
@@ -57,7 +59,7 @@ class CategoryService
|
||||
*
|
||||
* 프론트엔드 사용자 페이지에서 카테고리 필터에 사용합니다.
|
||||
*
|
||||
* @return Collection
|
||||
* @return Collection 활성 카테고리로만 구성된 공개 트리
|
||||
*/
|
||||
public function getPublicCategoryTree(): Collection
|
||||
{
|
||||
@@ -75,8 +77,8 @@ class CategoryService
|
||||
/**
|
||||
* slug로 공개 카테고리 조회 (활성 카테고리만)
|
||||
*
|
||||
* @param string $slug 카테고리 slug
|
||||
* @return Category|null
|
||||
* @param string $slug 카테고리 slug
|
||||
* @return Category|null 활성 카테고리 또는 null (비활성·미존재)
|
||||
*/
|
||||
public function getPublicCategoryBySlug(string $slug): ?Category
|
||||
{
|
||||
@@ -104,8 +106,8 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 상세 조회
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category|null
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category|null 카테고리 모델 또는 null (미존재)
|
||||
*/
|
||||
public function getCategory(int $id): ?Category
|
||||
{
|
||||
@@ -132,8 +134,8 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 생성
|
||||
*
|
||||
* @param array $data 카테고리 데이터
|
||||
* @return Category
|
||||
* @param array $data 카테고리 데이터
|
||||
* @return Category 생성된 카테고리 모델
|
||||
*/
|
||||
public function createCategory(array $data): Category
|
||||
{
|
||||
@@ -150,7 +152,7 @@ class CategoryService
|
||||
$data['path'] = $depthAndPath['path'];
|
||||
|
||||
// sort_order가 없으면 자동 계산
|
||||
if (!isset($data['sort_order'])) {
|
||||
if (! isset($data['sort_order'])) {
|
||||
$data['sort_order'] = $this->repository->getNextSortOrder($data['parent_id'] ?? null);
|
||||
}
|
||||
|
||||
@@ -162,7 +164,7 @@ class CategoryService
|
||||
$this->updatePath($category);
|
||||
|
||||
// 이미지 처리 (temp_key 방식)
|
||||
if (!empty($data['temp_key'])) {
|
||||
if (! empty($data['temp_key'])) {
|
||||
$this->imageRepository->linkTempImages($data['temp_key'], $category->id);
|
||||
}
|
||||
|
||||
@@ -178,16 +180,16 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 수정
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @param array $data 수정할 데이터
|
||||
* @return Category
|
||||
* @param int $id 카테고리 ID
|
||||
* @param array $data 수정할 데이터
|
||||
* @return Category 수정된 카테고리 모델
|
||||
*/
|
||||
public function updateCategory(int $id, array $data): Category
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
@@ -201,7 +203,8 @@ class CategoryService
|
||||
|
||||
$category = DB::transaction(function () use ($category, $data) {
|
||||
// parent_id가 변경되었으면 depth/path 재계산
|
||||
if (isset($data['parent_id']) && $data['parent_id'] !== $category->parent_id) {
|
||||
// 루트로 이동(parent_id = null)도 변경이므로 array_key_exists 사용 (isset 은 null 을 미설정으로 취급)
|
||||
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== $category->parent_id) {
|
||||
$depthAndPath = $this->calculateDepthAndPath($data['parent_id']);
|
||||
$data['depth'] = $depthAndPath['depth'];
|
||||
$data['path'] = $depthAndPath['path'];
|
||||
@@ -211,15 +214,15 @@ class CategoryService
|
||||
$categoryData = collect($data)->except(['temp_key'])->toArray();
|
||||
$category = $this->repository->update($category->id, $categoryData);
|
||||
|
||||
// path 업데이트 (parent_id 변경 시)
|
||||
if (isset($data['parent_id'])) {
|
||||
// path 업데이트 (parent_id 변경 시 — 루트 이동 포함)
|
||||
if (array_key_exists('parent_id', $data)) {
|
||||
$this->updatePath($category);
|
||||
// 하위 카테고리들의 path도 재계산
|
||||
$this->updateDescendantsPaths($category);
|
||||
}
|
||||
|
||||
// 이미지 처리
|
||||
if (!empty($data['temp_key'])) {
|
||||
if (! empty($data['temp_key'])) {
|
||||
$this->imageRepository->linkTempImages($data['temp_key'], $category->id);
|
||||
}
|
||||
|
||||
@@ -235,33 +238,34 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 삭제
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @param int $id 카테고리 ID
|
||||
* @return array 삭제 결과 정보
|
||||
* @throws \Exception
|
||||
*
|
||||
* @throws CategoryOperationException 카테고리 미존재 또는 삭제 불가 조건
|
||||
*/
|
||||
public function deleteCategory(int $id): array
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// 하위 카테고리 확인
|
||||
if ($this->repository->hasChildren($id)) {
|
||||
$childrenCount = $category->children()->count();
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_has_children', [
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_has_children', [
|
||||
'category_id' => $id,
|
||||
'count' => $childrenCount,
|
||||
]));
|
||||
]);
|
||||
}
|
||||
|
||||
// 연결된 상품 수 확인 - 상품이 있으면 삭제 차단
|
||||
$productsCount = $this->repository->getProductCount($id);
|
||||
if ($productsCount > 0) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_has_products', [
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_has_products', [
|
||||
'count' => $productsCount,
|
||||
]));
|
||||
]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
@@ -286,7 +290,7 @@ class CategoryService
|
||||
/**
|
||||
* depth와 Materialized Path를 계산합니다.
|
||||
*
|
||||
* @param int|null $parentId 부모 카테고리 ID
|
||||
* @param int|null $parentId 부모 카테고리 ID
|
||||
* @return array ['depth' => int, 'path' => string]
|
||||
*/
|
||||
private function calculateDepthAndPath(?int $parentId): array
|
||||
@@ -297,7 +301,7 @@ class CategoryService
|
||||
|
||||
$parent = $this->repository->findById($parentId);
|
||||
|
||||
if (!$parent) {
|
||||
if (! $parent) {
|
||||
return ['depth' => 0, 'path' => ''];
|
||||
}
|
||||
|
||||
@@ -309,9 +313,6 @@ class CategoryService
|
||||
|
||||
/**
|
||||
* 카테고리의 path를 업데이트합니다 (ID 포함).
|
||||
*
|
||||
* @param Category $category
|
||||
* @return void
|
||||
*/
|
||||
private function updatePath(Category $category): void
|
||||
{
|
||||
@@ -329,39 +330,52 @@ class CategoryService
|
||||
/**
|
||||
* 하위 카테고리들의 path를 재계산합니다 (재귀).
|
||||
*
|
||||
* @param Category $category
|
||||
* @return void
|
||||
* 검증(NotCircularCategoryParent)을 우회한 경로(시더/훅/기존 오염 데이터)에서
|
||||
* 순환 참조가 남아 있어도 무한 재귀 대신 유한 실패로 끝나도록 방문 ID 를 추적한다.
|
||||
*
|
||||
* @param Category $category 기준 카테고리
|
||||
* @param array<int, bool> $visited 방문한 카테고리 ID 집합 (재귀 내부 전달용)
|
||||
*/
|
||||
private function updateDescendantsPaths(Category $category): void
|
||||
private function updateDescendantsPaths(Category $category, array $visited = []): void
|
||||
{
|
||||
$children = $category->children;
|
||||
$visited[$category->id] = true;
|
||||
|
||||
foreach ($category->children as $child) {
|
||||
if (isset($visited[$child->id])) {
|
||||
Log::warning('[sirsoft-ecommerce] 카테고리 순환 참조 감지 — path 재계산 중단', [
|
||||
'category_id' => $category->id,
|
||||
'child_id' => $child->id,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($children as $child) {
|
||||
$this->updatePath($child);
|
||||
$this->updateDescendantsPaths($child); // 재귀 호출
|
||||
$this->updateDescendantsPaths($child, $visited);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리 상태 토글
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category
|
||||
* @throws \Exception
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category 상태가 토글된 카테고리 모델
|
||||
*
|
||||
* @throws CategoryOperationException 카테고리 미존재 또는 삭제 불가 조건
|
||||
*/
|
||||
public function toggleStatus(int $id): Category
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
HookManager::doAction('sirsoft-ecommerce.category.before_toggle_status', $category);
|
||||
|
||||
$category = $this->repository->update($id, [
|
||||
'is_active' => !$category->is_active,
|
||||
'is_active' => ! $category->is_active,
|
||||
]);
|
||||
|
||||
// After 훅
|
||||
@@ -373,8 +387,7 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 순서 변경
|
||||
*
|
||||
* @param array $orders 순서 변경 데이터 [['id' => 1, 'parent_id' => null, 'sort_order' => 0], ...]
|
||||
* @return void
|
||||
* @param array $orders 순서 변경 데이터 [['id' => 1, 'parent_id' => null, 'sort_order' => 0], ...]
|
||||
*/
|
||||
public function reorder(array $orders): void
|
||||
{
|
||||
@@ -384,7 +397,7 @@ class CategoryService
|
||||
DB::transaction(function () use ($orders) {
|
||||
foreach ($orders as $order) {
|
||||
$category = $this->repository->findById($order['id']);
|
||||
if (!$category) {
|
||||
if (! $category) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use Modules\Sirsoft\Ecommerce\Enums\OrderOptionSourceTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\MileageTransactionRepositoryInterface;
|
||||
@@ -295,18 +296,26 @@ class OrderOptionService
|
||||
*
|
||||
* @param array $items [{option_id, quantity}] 변경 대상
|
||||
* @param OrderStatusEnum $newStatus 변경할 상태
|
||||
* @param int $orderId 상위 주문 ID (옵션 소속 검증에 사용)
|
||||
* @param array $metadata 추가 정보
|
||||
* @return array 변경 결과
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 옵션이 상위 주문에 속하지 않는 경우
|
||||
*/
|
||||
public function bulkChangeStatusWithQuantity(
|
||||
array $items,
|
||||
OrderStatusEnum $newStatus,
|
||||
int $orderId,
|
||||
array $metadata = []
|
||||
): array {
|
||||
// 스냅샷 캡처 (ChangeDetector용)
|
||||
$optionIds = collect($items)->pluck('option_id')->filter()->unique()->toArray();
|
||||
$snapshots = $this->orderOptionRepository->getSnapshotsByIds($optionIds);
|
||||
|
||||
// 상위 주문 스코프 2차 방어 — FormRequest 를 우회한 내부/훅 호출도 차단.
|
||||
// 선택 파라미터로 두면 신규 호출처가 빠뜨렸을 때 방어가 조용히 꺼지므로 필수로 받는다.
|
||||
$this->assertOptionsBelongToOrder($optionIds, $orderId);
|
||||
|
||||
// 결제완료(payment_complete) 목표 전이 시 본인인증(IDV) 정책 가드 (A8 / N4).
|
||||
// 관리자 주문상세 "주문상태 변경"(옵션 일괄변경)이 결제완료로 부모 주문을 전이시키는,
|
||||
// 실무에서 가장 흔한 결제승인 경로다. OrderService::update / bulkUpdate 와 동일하게
|
||||
@@ -351,8 +360,8 @@ class OrderOptionService
|
||||
|
||||
// 부모 주문 상태 동기화
|
||||
$orderIds = $this->orderOptionRepository->getOrderIdsByOptionIds($optionIds);
|
||||
foreach ($orderIds as $orderId) {
|
||||
$this->syncParentOrderStatus($orderId);
|
||||
foreach ($orderIds as $parentOrderId) {
|
||||
$this->syncParentOrderStatus($parentOrderId);
|
||||
}
|
||||
|
||||
// after 훅 (스냅샷 전달)
|
||||
@@ -365,6 +374,29 @@ class OrderOptionService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 옵션들이 모두 지정 주문에 속하는지 검증합니다.
|
||||
*
|
||||
* @param array<int, int> $optionIds 검증할 주문 옵션 ID 목록
|
||||
* @param int $orderId 상위 주문 ID
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 하나라도 다른 주문에 속하는 경우
|
||||
*/
|
||||
private function assertOptionsBelongToOrder(array $optionIds, int $orderId): void
|
||||
{
|
||||
if ($optionIds === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$orderIds = $this->orderOptionRepository->getOrderIdsByOptionIds($optionIds);
|
||||
|
||||
foreach ($orderIds as $foundOrderId) {
|
||||
if ((int) $foundOrderId !== $orderId) {
|
||||
throw new ResourceScopeMismatchException('sirsoft-ecommerce::exceptions.order_option_not_in_order');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 옵션 금액 필드를 캡처합니다.
|
||||
*
|
||||
|
||||
@@ -11,6 +11,7 @@ use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductImageCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ProductImageUploadLimitException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
@@ -306,11 +307,19 @@ class ProductImageService
|
||||
* @param int $productId 상품 ID
|
||||
* @param int $imageId 이미지 ID
|
||||
* @return bool 성공 여부
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 이미지가 해당 상품에 속하지 않는 경우
|
||||
*/
|
||||
public function setThumbnail(int $productId, int $imageId): bool
|
||||
{
|
||||
// 기존 대표 이미지 해제
|
||||
$images = $this->repository->getByProductId($productId);
|
||||
|
||||
// 대상 이미지가 이 상품에 속하는지 먼저 확인 (교차 상품 오염 차단)
|
||||
if ($images->firstWhere('id', $imageId) === null) {
|
||||
throw new ResourceScopeMismatchException('sirsoft-ecommerce::exceptions.product_image_not_in_product');
|
||||
}
|
||||
|
||||
// 기존 대표 이미지 해제
|
||||
foreach ($images as $image) {
|
||||
if ($image->is_thumbnail) {
|
||||
$this->repository->update($image->id, ['is_thumbnail' => false]);
|
||||
|
||||
Reference in new issue
Block a user