fix(security): KVE-2026-1914/1915/1919 remediation 전건

위임 관리자(부관리자)가 권한·역할·표현식·비밀 콘텐츠 경계를 우회하던
결함군을 계층 대칭성 원칙으로 전건 차단한다. 약한 경로가 정상 응답을
내보내는 것이 유일한 증상이라, 게이트를 생산 지점 한 곳(SSoT)에 두고
같은 데이터를 내보내는 소비 경로 전부가 그 게이트를 경유하도록 맞췄다.

- 등급 상한(rank ceiling): 슈퍼관리자 보호·역할/사용자 역할 배정(추가·제거
 대칭)·일괄 상태변경·순서변경을 상세 경로와 동일 강도로 재적용. 가드는
 DB 쓰기에 선행하여 거부 시 상태 불변.
- 레이아웃 표현식: new Function/with 실행을 AST 화이트리스트 평가기로 교체.
 비-문자열 computed 키 정규화(normalizeKey)·Object facade(리플렉션 static
 제거)·legacy 접근자 차단. 저장측 검증·정적 검사와 3계층 동형.
- secret 게이트: 비밀글의 댓글·첨부·문의 독립 경로 재적용, hash 파일서빙
 소유권·비밀·발행 상태 검사 통일.
- 신뢰 스크립트 호스트: 확장 선언 기반 + same-origin 브라우저 정규화를
 런타임·저장측·정적검사 3층 동형화.
- 회귀 감지: 단위·Feature·E2E·시나리오 매니페스트 전축 + audit 룰 4종 신설.
This commit is contained in:
HeuJung committed 2026-08-17 01:45:09 +09:00
1 parent cd84b63d2b
commit 71abdeaf60
249 files changed
+14354 -1134

No files matched your search

@@ -41,11 +41,73 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
<!-- 실측 제외: http-403 — 응답 필드는 사람이 작성하세요. -->
_목록 응답: `data.data` 가 항목 배열, `data.meta` 가 페이지 정보, `data.abilities` 가 컬렉션 레벨 권한 (`MemoCollection`)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| data | array | `[{...}]` | 메모 항목 배열 (각 항목은 `MemoResource` — 아래 표) |
| meta.current_page | integer | `1` | 현재 페이지 번호 |
| meta.last_page | integer | `3` | 마지막 페이지 번호 |
| meta.per_page | integer | `10` | 페이지당 항목 수 (미지정 시 기본 `10`) |
| meta.total | integer | `27` | 전체 항목 수 |
| abilities.can_create | boolean | `true` | 요청자의 `gnuboard7-hello_module.memos.create` 보유 여부 |
| abilities.can_update | boolean | `true` | 요청자의 `gnuboard7-hello_module.memos.update` 보유 여부 |
| abilities.can_delete | boolean | `true` | 요청자의 `gnuboard7-hello_module.memos.delete` 보유 여부 |
`data.data[]` 항목 (`MemoResource`):
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `1` | 메모 기본키 |
| uuid | string(uuid) | `9f2c1b0e-…` | 외부 노출용 식별자 |
| title | string | `첫 번째 메모` | 제목 |
| content | string | `메모 본문입니다.` | 본문 내용 |
| created_at | string | `2026-08-16 01:30:00` | 생성 일시 (요청자 타임존으로 포맷) |
| updated_at | string | `2026-08-16 01:30:00` | 수정 일시 (요청자 타임존으로 포맷) |
| abilities | object | `{"can_create":true, …}` | 항목 레벨 권한 (컬렉션 `abilities` 와 같은 3종) |
**응답 예시**
<!-- 실측 제외: http-403 — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "메모 목록을 조회했습니다.",
"data": {
"data": [
{
"id": 1,
"uuid": "9f2c1b0e-4d7a-4f10-9c33-1a5b6e8d2f04",
"title": "첫 번째 메모",
"content": "메모 본문입니다.",
"created_at": "2026-08-16 01:30:00",
"updated_at": "2026-08-16 01:30:00",
"abilities": {
"can_create": true,
"can_update": true,
"can_delete": true
}
}
],
"meta": {
"current_page": 1,
"last_page": 3,
"per_page": 10,
"total": 27
},
"abilities": {
"can_create": true,
"can_update": true,
"can_delete": true
}
}
}
```
> 위 문서의 실측이 `403` 으로 관측된 것은 프로브 계정에 `gnuboard7-hello_module.memos.read` 권한이 없었기 때문이다. 권한을 갖춘 요청은 `200` 과 위 페이로드를 받는다.
**에러 응답**
@@ -53,11 +115,16 @@ Authorization: Bearer {YOUR_TOKEN}
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.read`)이 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지 — `page` 최소 1, `per_page` 1~100) |
| 500 | Internal Server Error | 조회 중 예외 발생 (`gnuboard7-hello_module::messages.memo.fetch_failed`, `errors.error` 에 예외 메시지) |
<!-- @generated:end -->
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
**설명**
메모 목록을 페이지 단위로 조회한다. 학습용 샘플 모듈의 표준 목록 엔드포인트로, 코어의 `AdminBaseController` + `BaseApiCollection` 조합을 그대로 따른다.
`per_page` 를 지정하지 않으면 기본값 `10` 이 적용된다. 상·하한(1~100)은 `MemoListRequest` 가 검증하므로 Service 는 검증 없이 값을 그대로 쓴다 — 검증은 FormRequest 책임이라는 규칙의 예시다.
### POST /api/modules/gnuboard7-hello_module/admin/memos
@@ -90,11 +157,45 @@ Content-Type: application/json
**응답 필드** (`data` 내부)
<!-- 실측 제외: http-403 — 응답 필드는 사람이 작성하세요. -->
_단건 응답: `data` 가 생성된 메모 하나 (`MemoResource`)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `28` | 생성된 메모의 기본키 |
| uuid | string(uuid) | `3b7e5a12-…` | 외부 노출용 식별자 (생성 시 자동 부여) |
| title | string | `예시 제목` | 제목 |
| content | string | `예시 내용입니다.` | 본문 내용 |
| created_at | string | `2026-08-16 01:30:00` | 생성 일시 (요청자 타임존으로 포맷) |
| updated_at | string | `2026-08-16 01:30:00` | 수정 일시 (생성 직후에는 `created_at` 과 같다) |
| abilities | object | `{"can_create":true,"can_update":true,"can_delete":true}` | 요청자의 메모 권한 3종 |
**응답 예시**
<!-- 실측 제외: http-403 — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 201
```
```json
{
"success": true,
"message": "메모가 생성되었습니다.",
"data": {
"id": 28,
"uuid": "3b7e5a12-8c04-4d61-9b2f-7e0a1c4d5f88",
"title": "예시 제목",
"content": "예시 내용입니다.",
"created_at": "2026-08-16 01:30:00",
"updated_at": "2026-08-16 01:30:00",
"abilities": {
"can_create": true,
"can_update": true,
"can_delete": true
}
}
}
```
> 성공 상태코드는 `200` 이 아니라 **`201 Created`** 다. 위 문서의 실측이 `403` 으로 관측된 것은 프로브 계정에 `gnuboard7-hello_module.memos.create` 권한이 없었기 때문이다.
**에러 응답**
@@ -102,11 +203,16 @@ Content-Type: application/json
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.create`)이 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지 — `title` 필수·255자 이하, `content` 필수) |
| 500 | Internal Server Error | 생성 중 예외 발생 (`gnuboard7-hello_module::messages.memo.create_failed`, `errors.error` 에 예외 메시지) |
<!-- @generated:end -->
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
**설명**
메모를 생성한다. 검증은 `StoreMemoRequest` 가 전담하고 Service 는 검증된 배열만 받는다 — Service 에 검증 로직을 두지 않는다는 규칙의 예시다.
컨트롤러가 `$request->validated()` 를 넘기므로 FormRequest 에 정의되지 않은 필드는 모델에 도달하지 않는다. `$request->all()` / `except()` 를 쓰면 `$fillable` 을 통해 미정의 필드가 새므로 쓰지 않는다.
### DELETE /api/modules/gnuboard7-hello_module/admin/memos/{id}
@@ -132,11 +238,25 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
_삭제 응답에는 페이로드가 없다. 컨트롤러가 `success(메시지)` 만 호출하므로 `data` 는 `null` 이다._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| (없음) | null | `null` | 삭제 성공 시 `data` 는 항상 `null`. 결과 판정은 `success` 와 상태코드로 한다 |
**응답 예시**
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "메모가 삭제되었습니다.",
"data": null
}
```
**에러 응답**
@@ -144,11 +264,16 @@ Authorization: Bearer {YOUR_TOKEN}
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.delete`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `id` 의 메모가 없는 경우 (`gnuboard7-hello_module::messages.memo.not_found`) |
| 500 | Internal Server Error | 삭제 중 예외 발생 (`gnuboard7-hello_module::messages.memo.delete_failed`, `errors.error` 에 예외 메시지) |
<!-- @generated:end -->
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
**설명**
메모를 삭제한다. 컨트롤러가 먼저 `getMemo($id)` 로 대상을 조회하므로, 존재하지 않는 `id` 는 삭제 시도 전에 `404` 로 걸러진다.
삭제는 DB CASCADE 에 의존하지 않고 Service 가 명시적으로 수행한다 — 훅 발화·파일 정리·로깅을 보장하기 위해서다.
### GET /api/modules/gnuboard7-hello_module/admin/memos/{id}
@@ -174,11 +299,43 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
_단건 응답: `data` 가 메모 하나 (`MemoResource`)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `2` | 기본 키 (내부 식별자) |
| uuid | string(uuid) | `4473e9ee-ecdf-4ad0-afb3-78ada47265af` | 외부 노출용 UUID |
| title | string | `두 번째 메모` | 제목 |
| content | string | `Memo 엔티티의 CRUD 동작을 확인할 수 있는 추가 샘플입니다.` | 본문 내용 |
| created_at | string | `2026-07-31 22:09:15` | 생성 일시 (요청자 타임존으로 포맷) |
| updated_at | string | `2026-07-31 22:09:15` | 수정 일시 (요청자 타임존으로 포맷) |
| abilities | object | `{"can_create":true,"can_update":true,"can_delete":true}` | 요청자의 메모 권한 3종 |
**응답 예시**
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "메모를 조회했습니다.",
"data": {
"id": 2,
"uuid": "4473e9ee-ecdf-4ad0-afb3-78ada47265af",
"title": "두 번째 메모",
"content": "Memo 엔티티의 CRUD 동작을 확인할 수 있는 추가 샘플입니다.",
"created_at": "2026-07-31 22:09:15",
"updated_at": "2026-07-31 22:09:15",
"abilities": {
"can_create": true,
"can_update": true,
"can_delete": true
}
}
}
```
**에러 응답**
@@ -186,11 +343,16 @@ Authorization: Bearer {YOUR_TOKEN}
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.read`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `id` 의 메모가 없는 경우 (`gnuboard7-hello_module::messages.memo.not_found`) |
| 500 | Internal Server Error | 조회 중 예외 발생 (`gnuboard7-hello_module::messages.memo.fetch_failed`, `errors.error` 에 예외 메시지) |
<!-- @generated:end -->
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
**설명**
메모 단건을 조회하는 관리자 엔드포인트다. path 파라미터는 `int` 타입힌트를 받는 **기본키 `id`** 이며, 응답에 함께 실리는 `uuid` 가 아니다.
같은 리소스의 공개 조회는 `GET /api/modules/gnuboard7-hello_module/memos/{id}` 로 별도 제공된다. 관리자 경로는 `permission:gnuboard7-hello_module.memos.read` 를 요구하는 반면 공개 경로는 `optional.sanctum` 이라 비회원도 접근한다.
### PUT /api/modules/gnuboard7-hello_module/admin/memos/{id}
@@ -224,11 +386,43 @@ Content-Type: application/json
**응답 필드** (`data` 내부)
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
_단건 응답: `data` 가 수정된 메모 하나 (`MemoResource`)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `2` | 기본 키 (수정으로 바뀌지 않는다) |
| uuid | string(uuid) | `4473e9ee-ecdf-4ad0-afb3-78ada47265af` | 외부 노출용 UUID (수정으로 바뀌지 않는다) |
| title | string | `예시 제목` | 수정된 제목 |
| content | string | `예시 내용입니다.` | 수정된 본문 내용 |
| created_at | string | `2026-07-31 22:09:15` | 생성 일시 (불변) |
| updated_at | string | `2026-08-16 01:30:00` | 수정 일시 (이번 요청 시각으로 갱신) |
| abilities | object | `{"can_create":true,"can_update":true,"can_delete":true}` | 요청자의 메모 권한 3종 |
**응답 예시**
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "메모가 수정되었습니다.",
"data": {
"id": 2,
"uuid": "4473e9ee-ecdf-4ad0-afb3-78ada47265af",
"title": "예시 제목",
"content": "예시 내용입니다.",
"created_at": "2026-07-31 22:09:15",
"updated_at": "2026-08-16 01:30:00",
"abilities": {
"can_create": true,
"can_update": true,
"can_delete": true
}
}
}
```
**에러 응답**
@@ -236,12 +430,17 @@ Content-Type: application/json
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.update`)이 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `id` 의 메모가 없는 경우 (`gnuboard7-hello_module::messages.memo.not_found`) |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지 — `title` 필수·255자 이하, `content` 필수) |
| 500 | Internal Server Error | 수정 중 예외 발생 (`gnuboard7-hello_module::messages.memo.update_failed`, `errors.error` 에 예외 메시지) |
<!-- @generated:end -->
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
**설명**
메모를 수정한다. `PUT` 이므로 `title` 과 `content` 를 **모두** 보내야 한다 (`UpdateMemoRequest` 가 둘 다 필수로 검증). 일부 필드만 보내면 `422` 다.
컨트롤러는 `getMemo($id)` 로 대상을 먼저 조회하므로 존재하지 않는 `id` 는 수정 시도 전에 `404` 로 걸러지고, Service 에는 `$request->validated()` 결과만 전달되어 FormRequest 미정의 필드가 모델에 도달하지 않는다.
### GET /api/modules/gnuboard7-hello_module/memos
@@ -6,6 +6,13 @@
## [1.0.4] - 2026-08-12
### Security
- 비밀글의 내용이 열람 권한 없이 새어 나가던 경로를 모두 막았습니다. 게시글 상세 화면은 비밀글 내용을 가렸지만, 상품 문의 목록·비밀글의 댓글 목록·비밀글의 첨부파일(다운로드/미리보기)은 게시글의 비밀 여부를 확인하지 않아 주소만 알면 원문·첨부를 볼 수 있었습니다. 이제 이 경로 전부에서 작성자 본인 또는 게시판 관리 권한(비밀글 열람)을 가진 요청에만 내용을 제공하고, 그 외에는 내용·제목·답변·첨부를 가립니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-1914)
- 회원 프로필의 작성글 목록과 "내가 댓글 단 글" 활동 목록에서 다른 사람의 비밀글·블라인드 글 **본문**이 로그인 없이도 나가던 문제를 수정했습니다. 두 목록은 본문 앞부분을 함께 싣는데 그것을 가리는 설정이 실제로는 한 번도 켜지지 않았습니다. 이제 본인이 볼 때만 본문이 보이고, 다른 사람이 볼 때는 비워집니다. 글의 제목과 목록에서의 표시(비밀글·블라인드 배지)는 게시판 목록과 동일하게 그대로 유지됩니다. (KVE-2026-1914)
- 첨부파일 삭제·순서 변경에 담당 범위 제한을 적용했습니다. 회원 화면은 작성자 본인만 삭제하도록 막고 있었지만 관리 화면에는 같은 확인이 없었고, 순서 변경은 양쪽 모두 확인이 없었습니다. 순서는 목록 전체에 대한 하나의 값이라 범위 밖 대상이 하나라도 섞이면 요청 전체를 거부합니다. (KVE-2026-1919)
- 게시판을 찾을 수 없을 때 비밀글 보호가 통과되던 문제를 수정했습니다. 첨부파일 서빙과 댓글 목록은 부모 글을 찾지 못하면 검사를 건너뛰고 진행해, 게이트가 있어야 할 자리가 비어 있었습니다. 이제 부모 글을 확인할 수 없으면 차단합니다.
### Changed
- 글 저장·수정 시 비밀글 여부 값을 문자열(`"true"`/`"false"`)로 보내는 클라이언트도 수용하도록 해석을 관대화했습니다. 해석할 수 없는 값은 종전과 동일하게 거부됩니다.
@@ -21,6 +28,7 @@
- 신고 반려 누적 제한 안내 문구를 실제 동작에 맞게 정정했습니다. "설정 건수를 초과하면 차단"으로 적혀 있었지만 실제로는 설정 건수에 도달하는 순간부터 차단됩니다 — 5건으로 설정하면 5번째 반려부터 신고가 막힙니다.
- 관리자가 게시판 설정을 저장해도 백그라운드 작업에는 이전 설정이 계속 적용되던 문제를 수정했습니다. (#109 @Tuwasduliebst 님께서 제보해주셨습니다.)
- 신고 현황 목록에서 항목을 선택한 뒤 검색하거나 페이지를 넘기면, 화면에서 사라진 항목이 선택된 채로 남아 일괄 처리 대상에 포함되던 문제를 수정했습니다. 이제 일괄 처리 대상은 언제나 화면에 보이면서 체크된 항목뿐입니다.
- 댓글 목록을 불러올 때 댓글마다 원글을 반복 조회하던 비효율을 제거해 응답을 더 빠르게 했습니다. 댓글이 많은 글일수록 개선 폭이 큽니다.
## [1.0.3] - 2026-08-10
@@ -16,6 +16,16 @@
---
## 비밀글 서버측 게이팅 (KVE-2026-1914)
비밀글(`is_secret`)의 원문은 작성자 본인 또는 게시판 관리 권한(`posts.read-secret`/`manager`)을 가진 요청에만 제공됩니다. 판정은 `SecretContentGate`(SSoT)가 담당하며 게시글 상세 외 다음 경로에도 동일하게 적용됩니다.
- **댓글 목록**(`GET .../posts/{postId}/comments`): 부모 게시글이 비밀글이고 열람 권한이 없으면 빈 목록(`200`)을 반환합니다.
- **첨부 서빙**(`GET .../attachment/{hash}`, `.../attachment/{hash}/preview`): 부모 게시글이 비밀글이고 열람 권한이 없으면 `403`. 첨부 요청은 상세와 분리된 요청이라 비밀번호 검증(`password_verified`)은 적용되지 않으며 작성자/관리 권한만 인정합니다.
- **상세/목록 응답**: 비열람자에게 `content`·`title`·`reply`·`attachments`가 마스킹됩니다.
---
## 목록·검색의 총 건수와 답변·댓글 상한
게시판 목록에 `search` 를 얹으면 내부 검색이 수행됩니다. 매칭이 아주 많을 수 있으므로 총
@@ -118,7 +118,7 @@ class AttachmentController extends AdminBaseController
}
// 삭제 (Service에서 처리)
$result = $this->attachmentService->delete($slug, $id);
$result = $this->attachmentService->delete($slug, $id, 'admin');
if (! $result) {
return $this->error('sirsoft-board::messages.attachment.delete_failed', 500);
@@ -149,7 +149,7 @@ class AttachmentController extends AdminBaseController
// FileUploader가 [{id, order}] 형태로 전송 → [ID => order] 매핑으로 변환
$orders = collect($validated['order'])->pluck('order', 'id')->all();
$result = $this->attachmentService->reorder($slug, $orders);
$result = $this->attachmentService->reorder($slug, $orders, 'admin');
if (! $result) {
return $this->error('sirsoft-board::messages.attachment.reorder_failed', 500);
@@ -14,6 +14,8 @@ use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\UpdateCommentRequest;
use Modules\Sirsoft\Board\Http\Requests\VerifyCommentPasswordRequest;
use Modules\Sirsoft\Board\Http\Resources\CommentResource;
use Modules\Sirsoft\Board\Http\Resources\PostResource;
use Modules\Sirsoft\Board\Repositories\Contracts\PostRepositoryInterface;
use Modules\Sirsoft\Board\Services\BoardService;
use Modules\Sirsoft\Board\Services\CommentService;
@@ -32,7 +34,8 @@ class CommentController extends PublicBaseController
*/
public function __construct(
private CommentService $commentService,
private BoardService $boardService
private BoardService $boardService,
private PostRepositoryInterface $postRepository
) {
parent::__construct();
}
@@ -57,6 +60,32 @@ class CommentController extends PublicBaseController
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
}
// 비밀글 댓글 게이팅(KVE-2026-1914): 부모 게시글이 비밀글이면 열람 권한이 없는
// 요청에는 댓글 목록을 노출하지 않는다(게시글 상세와 동일 정책, SecretContentGate SSoT).
$post = $this->postRepository->find($slug, $postId);
// 부모 글을 못 읽으면 막는다(fail-closed). `find` 는 슬러그로 게시판을 먼저 찾는데
// 그 게시판이 없으면 null 을 돌려주므로, 통과시키면 비밀 게이트가 있어야 할 자리에서
// 무게이트로 댓글 목록이 나간다.
if (! $post) {
return $this->error('sirsoft-board::messages.posts.not_found', 404);
}
if ($post->is_secret && ! PostResource::canViewSecretForPost($post)) {
return $this->success(
'sirsoft-board::messages.comments.index_success',
CommentResource::collection([])
);
}
// 이미 조회한 부모 post 를 CommentResource 로 전달한다(KVE-2026-1914 이중 방어 A-4b).
// Resource 는 이 인스턴스를 재사용해 (a) 2차 비밀 게이트를 댓글당 lazy-load 없이
// 재확인하고 (b) toArray 의 slug 도출도 재사용한다 — 목록의 댓글당 board_posts
// 조회(N+1)를 제거한다. 컨트롤러가 SSoT 로 부모 post 를 쥐고 있으므로 추가 쿼리 0.
if ($post) {
request()->attributes->set('sirsoft_board_parent_post', $post);
}
$comments = $this->commentService->getCommentsByPostId($slug, $postId);
return $this->success(
@@ -9,6 +9,7 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Enums\TriggerType;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Repositories\Contracts\ReportRepositoryInterface;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
use Modules\Sirsoft\Board\Traits\FormatsBoardDate;
@@ -31,7 +32,11 @@ class CommentResource extends BaseApiResource
*/
public function toArray(Request $request): array
{
$slug = $this->post?->board?->slug ?? $request->route('slug');
// 컨트롤러가 넘긴 부모 post(요청 속성)를 재사용해 slug 를 도출한다 — 목록에서 댓글당
// `$this->post` lazy-load(N+1)를 피한다(KVE-2026-1914 A-4b). 미주입 경로(상세/생성/
// admin)는 종전대로 이미 로드된 관계 또는 라우트 slug 로 폴백한다.
$parentPost = $this->resolveParentPost($request);
$slug = $parentPost?->board?->slug ?? $request->route('slug');
return [
'id' => $this->id,
@@ -170,8 +175,9 @@ class CommentResource extends BaseApiResource
}
// fallback: 개별 쿼리 (목록 등 사전 로드 미적용 경로)
// 부모 post 는 컨트롤러가 넘긴 인스턴스를 재사용해 댓글당 lazy-load 를 피한다.
$user = $request->user();
$boardId = $this->post?->board?->id ?? null;
$boardId = $this->resolveParentPost($request)?->board?->id ?? null;
if (! $user || ! $boardId) {
return false;
@@ -206,7 +212,7 @@ class CommentResource extends BaseApiResource
*/
protected function resolveAbilities(Request $request): array
{
$slug = $this->post?->board?->slug ?? $request->route('slug');
$slug = $this->resolveParentPost($request)?->board?->slug ?? $request->route('slug');
if (! $slug) {
return [];
}
@@ -251,6 +257,29 @@ class CommentResource extends BaseApiResource
// 콘텐츠 필터링 메서드
// =========================================================================
/**
* 부모 게시글(Post)을 조회 없이 해석합니다.
*
* 우선순위:
* 1. 컨트롤러가 요청 속성으로 넘긴 인스턴스(`sirsoft_board_parent_post`) — 목록 경로에서
* 댓글당 lazy-load(N+1)를 피하는 SSoT. 모든 댓글이 같은 인스턴스를 공유한다.
* 2. 이미 로드된 `post` 관계(상세/생성/admin 등 미주입 경로 하위호환).
*
* 둘 다 없으면 null — 추가 쿼리를 유발하지 않는다(2차 게이트는 1차 방어가 담당).
*
* @param Request $request HTTP 요청
* @return Post|null 부모 게시글
*/
private function resolveParentPost(Request $request): ?Post
{
$injected = $request->attributes->get('sirsoft_board_parent_post');
if ($injected instanceof Post) {
return $injected;
}
return $this->resource->relationLoaded('post') ? $this->post : null;
}
/**
* 권한에 따라 필터링된 댓글 내용을 반환합니다.
*
@@ -260,6 +289,14 @@ class CommentResource extends BaseApiResource
*/
private function getFilteredContent(Request $request, ?string $slug): ?string
{
// 부모 게시글이 비밀글이면 열람 권한 없는 요청에는 댓글 원문을 숨긴다
// (KVE-2026-1914 이중 방어 — 1차 차단은 CommentController::index).
// 컨트롤러가 넘긴 부모 post(요청 속성)를 재사용해 댓글당 lazy-load 없이 재확인한다.
$parentPost = $this->resolveParentPost($request);
if ($parentPost && $parentPost->is_secret && ! PostResource::canViewSecretForPost($parentPost, $request)) {
return null;
}
// 게시글 삭제로 함께 숨겨진(cascade) 댓글은 사용자가 직접 지운 것이 아니므로
// 마스킹하지 않고 원문을 그대로 노출한다 (글을 볼 수 있는 사람이면 누구나).
$isCascadeDeleted = $this->deleted_at !== null
@@ -10,8 +10,10 @@ use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Enums\ReportReasonType;
use Modules\Sirsoft\Board\Enums\TriggerType;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Repositories\Contracts\ReportRepositoryInterface;
use Modules\Sirsoft\Board\Support\BoardPermissionCacheKeys;
use Modules\Sirsoft\Board\Support\SecretContentGate;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
use Modules\Sirsoft\Board\Traits\FormatsBoardDate;
@@ -686,30 +688,24 @@ class PostResource extends BaseApiResource
*/
private function canViewSecretContent(Request $request, ?string $slug = null): bool
{
// 1. 작성자 본인 (회원 게시글)
$user = Auth::user();
if ($user && $this->user_id && $this->user_id === $user->id) {
return true;
}
// 판정 규칙은 SecretContentGate(SSoT)에 있다 — 리스너·댓글 경로와 규칙을 공유해
// 드리프트를 방지한다.
return self::canViewSecretForPost($this->resource, $request);
}
// 2. 비밀번호 검증 완료
if ($this->password_verified === true) {
return true;
}
// 3-4. 게시판별 권한 체크
$slug = $slug ?? $this->getSlug($request);
if (! $slug) {
return false;
}
if ($this->isAdminRequest($request)) {
return $this->checkBoardPermission($slug, 'admin.posts.read-secret')
|| $this->checkBoardPermission($slug, 'admin.manage');
}
return $this->checkBoardPermission($slug, 'posts.read-secret', PermissionType::User)
|| $this->checkBoardPermission($slug, 'manager', PermissionType::User);
/**
* 주어진 게시글의 비밀 원문 열람 권한을 판정합니다 (SSoT 진입점).
*
* PostResource 외 경로(이커머스 문의 연동 훅, 댓글 목록/리소스, 첨부 서빙)가
* 동일 규칙으로 서버측 마스킹을 수행하도록 공유합니다(KVE-2026-1914).
*
* @param Post $post 대상 게시글
* @param Request|null $request HTTP 요청 (미지정 시 현재 요청)
* @return bool 열람 가능 여부
*/
public static function canViewSecretForPost(Post $post, ?Request $request = null): bool
{
return app(SecretContentGate::class)->canView($post, $request);
}
// =========================================================================
@@ -6,6 +6,7 @@ use App\Contracts\Extension\HookListenerInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Board\Http\Resources\PostResource;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
use Modules\Sirsoft\Board\Repositories\Contracts\PostRepositoryInterface;
@@ -90,7 +91,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
/**
* 기본 훅 핸들러 (HookListenerInterface 필수 메서드)
*
* @param mixed ...$args 훅 인자
* @param mixed ...$args 훅 인자
* @return void
*/
public function handle(...$args): void
@@ -116,9 +117,11 @@ class EcommerceInquiryHookListener implements HookListenerInterface
$data['user_id'] = null;
}
// ip_address: board_posts.ip_address NOT NULL 제약 충족
// ip_address: board_posts.ip_address NOT NULL 제약 충족.
// 클라이언트 IP 는 요청 경계(호출 서비스 ProductInquiryService)가 payload 로
// 주입한다 — Listener 는 request() 를 직접 참조하지 않는다(입력 우회 방지).
if (empty($data['ip_address'])) {
$data['ip_address'] = request()->ip() ?? '0.0.0.0';
$data['ip_address'] = '0.0.0.0';
}
// parent_id 있으면 답변글 → 부모 Post 제목으로 Re: 원글제목 설정
@@ -151,13 +154,20 @@ class EcommerceInquiryHookListener implements HookListenerInterface
}
/**
* ID 목록으로 Post 데이터 배열 반환
* ID 목록으로 Post 데이터 배열 반환 (`sirsoft-ecommerce.inquiry.get_by_ids` 필터 훅)
*
* 이커머스 모듈이 문의 목록을 구성할 때 게시글 데이터를 일괄 조회합니다.
*
* 반환 payload 계약(KVE-2026-1914): 각 항목은 비밀글 열람 권위 플래그
* `can_view_secret`(bool)을 반드시 포함해야 한다. 소비자(`ProductInquiryService`)는
* 이 플래그로 title/content/reply/attachments 마스킹을 최종 확정하며, **플래그가
* 없으면 fail-closed 로 전부 마스킹**한다. 3자 확장이 이 훅을 대체 구현할 때
* `can_view_secret` 를 누락하면 비밀 아닌 문의까지 조용히 마스킹되는 기능 회귀가
* 발생하므로, 대체 리스너도 요청자 신원으로 이 플래그를 채워야 한다.
*
* @param array $carry 이전 필터 결과 (초기값: [])
* @param array $context 조회 컨텍스트 ['ids' => int[], 'slug' => string]
* @return array Post 데이터 배열
* @return array Post 데이터 배열 (각 항목에 `can_view_secret` bool 필수)
*/
public function getByIds(array $carry, array $context): array
{
@@ -171,6 +181,12 @@ class EcommerceInquiryHookListener implements HookListenerInterface
$posts = $this->postRepository->findByIdsWithRelations($ids);
return $posts->map(function (Post $post) {
// 비밀글 서버측 게이팅(KVE-2026-1914): 열람 권한이 없으면 원문을 마스킹한다.
// 규칙은 PostResource 와 동일한 SecretContentGate(SSoT)를 공유한다.
// 리스트 컨텍스트라 password_verified 는 적용되지 않는다(작성자/관리 권한만).
$isSecret = (bool) $post->is_secret;
$canViewSecret = ! $isSecret || PostResource::canViewSecretForPost($post);
return [
'id' => $post->id,
'board_id' => $post->board_id,
@@ -178,26 +194,34 @@ class EcommerceInquiryHookListener implements HookListenerInterface
'parent_id' => $post->parent_id,
'user_id' => $post->user_id,
'author_name' => $post->author_name,
'title' => $post->title,
'content' => $post->content,
'title' => $canViewSecret
? $post->title
: __('sirsoft-board::messages.post.secret_post_title'),
'content' => $canViewSecret ? $post->content : null,
'category' => $post->category,
'is_secret' => (bool) $post->is_secret,
'is_secret' => $isSecret,
// 서버가 요청자 신원으로 내린 열람 판정(SSoT). 소비 서비스가 이 값으로
// 마스킹을 재확인(이중 방어)할 수 있도록 함께 실어 보낸다. 소비측은 자기
// 권한을 재계산하지 말고 이 값만 신뢰해야 게이트 강도가 갈리지 않는다.
'can_view_secret' => $canViewSecret,
'status' => $post->status?->value,
'view_count' => $post->view_count,
'created_at' => $post->created_at?->toIso8601String(),
'updated_at' => $post->updated_at?->toIso8601String(),
// 첨부파일 목록
'attachments' => $post->attachments->map(fn ($a) => [
'id' => $a->id,
'original_filename' => $a->original_filename,
'size' => $a->size,
'size_formatted' => $a->size_formatted,
'is_image' => $a->is_image,
'preview_url' => $a->preview_url,
'download_url' => $a->download_url,
])->values()->all(),
// 답변 게시글 (parent_id가 있는 자식 글)
'reply' => $this->getReplyForPost($post),
// 첨부파일 목록 (비밀글 비열람자는 빈 배열)
'attachments' => $canViewSecret
? $post->attachments->map(fn ($a) => [
'id' => $a->id,
'original_filename' => $a->original_filename,
'size' => $a->size,
'size_formatted' => $a->size_formatted,
'is_image' => $a->is_image,
'preview_url' => $a->preview_url,
'download_url' => $a->download_url,
])->values()->all()
: [],
// 답변 게시글 (parent_id가 있는 자식 글, 비밀글 비열람자는 null)
'reply' => $canViewSecret ? $this->getReplyForPost($post) : null,
];
})->all();
} catch (\Exception $e) {
@@ -229,18 +253,18 @@ class EcommerceInquiryHookListener implements HookListenerInterface
}
return [
'secret_mode' => $board->secret_mode?->value ?? 'disabled',
'categories' => $board->categories ?? [],
'use_file_upload' => (bool) $board->use_file_upload,
'max_file_count' => $board->max_file_count ?? 5,
'max_file_size' => $board->max_file_size ?? 10,
'allowed_extensions' => $board->allowed_extensions ?? [],
'min_title_length' => $board->min_title_length ?? 2,
'max_title_length' => $board->max_title_length ?? 200,
'min_content_length' => $board->min_content_length ?? 10,
'max_content_length' => $board->max_content_length ?? 10000,
'attachment_upload_url' => '/api/modules/sirsoft-board/boards/' . $board->slug . '/attachments',
'attachment_delete_url' => '/api/modules/sirsoft-board/boards/' . $board->slug . '/attachments/:id',
'secret_mode' => $board->secret_mode?->value ?? 'disabled',
'categories' => $board->categories ?? [],
'use_file_upload' => (bool) $board->use_file_upload,
'max_file_count' => $board->max_file_count ?? 5,
'max_file_size' => $board->max_file_size ?? 10,
'allowed_extensions' => $board->allowed_extensions ?? [],
'min_title_length' => $board->min_title_length ?? 2,
'max_title_length' => $board->max_title_length ?? 200,
'min_content_length' => $board->min_content_length ?? 10,
'max_content_length' => $board->max_content_length ?? 10000,
'attachment_upload_url' => '/api/modules/sirsoft-board/boards/'.$board->slug.'/attachments',
'attachment_delete_url' => '/api/modules/sirsoft-board/boards/'.$board->slug.'/attachments/:id',
];
} catch (\Exception $e) {
Log::error('EcommerceInquiryHookListener: 게시판 설정 조회 실패', [
@@ -270,7 +294,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
$post = $this->postRepository->findWithBoard($postId);
if (! $post || ! $post->board) {
throw new ModelNotFoundException("Post {$postId} 또는 소속 Board를 찾을 수 없습니다.");
throw new ModelNotFoundException("Post {$postId} or its board could not be found.");
}
$attachmentIds = $data['attachment_ids'] ?? [];
@@ -278,7 +302,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (ModelNotFoundException $e) {
Log::warning('EcommerceInquiryHookListener: Post 수정 실패 - 게시글 또는 게시판 없음', [
'post_id' => $postId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -287,7 +311,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (\Exception $e) {
Log::error('EcommerceInquiryHookListener: Post 수정 실패', [
'post_id' => $postId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -315,7 +339,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
$post = $this->postRepository->findWithBoard($postId);
if (! $post || ! $post->board) {
throw new ModelNotFoundException("Post {$postId} 또는 소속 Board를 찾을 수 없습니다.");
throw new ModelNotFoundException("Post {$postId} or its board could not be found.");
}
// 이커머스 경로: 알림 발송 SKIP (createPost와 동일한 skip_notification 패턴)
@@ -323,7 +347,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (ModelNotFoundException $e) {
Log::warning('EcommerceInquiryHookListener: Post 삭제 실패 - 게시글 또는 게시판 없음', [
'post_id' => $postId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -332,7 +356,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (\Exception $e) {
Log::error('EcommerceInquiryHookListener: Post 삭제 실패', [
'post_id' => $postId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -367,7 +391,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
}
if (! $reply->board) {
throw new ModelNotFoundException("Reply Post {$reply->id} 소속 Board를 찾을 수 없습니다.");
throw new ModelNotFoundException("Reply Post {$reply->id}'s board could not be found.");
}
$this->postService->updatePost($reply->board->slug, $reply->id, $data);
@@ -376,7 +400,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (ModelNotFoundException $e) {
Log::warning('EcommerceInquiryHookListener: Reply Post 수정 실패 - 게시글 또는 게시판 없음', [
'parent_post_id' => $parentPostId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -385,7 +409,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (\Exception $e) {
Log::error('EcommerceInquiryHookListener: Reply Post 수정 실패', [
'parent_post_id' => $parentPostId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -419,7 +443,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
}
if (! $reply->board) {
throw new ModelNotFoundException("Reply Post {$reply->id} 소속 Board를 찾을 수 없습니다.");
throw new ModelNotFoundException("Reply Post {$reply->id}'s board could not be found.");
}
// 이커머스 경로: 알림 발송 SKIP (createPost와 동일한 skip_notification 패턴)
@@ -429,7 +453,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (ModelNotFoundException $e) {
Log::warning('EcommerceInquiryHookListener: Reply Post 삭제 실패 - 게시글 또는 게시판 없음', [
'parent_post_id' => $parentPostId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -438,7 +462,7 @@ class EcommerceInquiryHookListener implements HookListenerInterface
} catch (\Exception $e) {
Log::error('EcommerceInquiryHookListener: Reply Post 삭제 실패', [
'parent_post_id' => $parentPostId,
'error' => $e->getMessage(),
'error' => $e->getMessage(),
]);
throw new \RuntimeException(
@@ -77,6 +77,27 @@ class AttachmentRepository implements AttachmentRepositoryInterface
return $post->deleted_at !== null || $post->status === PostStatus::Deleted;
}
/**
* 첨부파일이 속한 게시글을 게시판 스코프로 조회합니다(비밀 게이팅용).
*
* @param string $slug 게시판 슬러그
* @param int $postId 게시글 ID
* @return Post|null 게시글 모델 또는 null
*/
public function findPostForGate(string $slug, int $postId): ?Post
{
$board = Board::where('slug', $slug)->first();
if (! $board) {
return null;
}
return Post::withTrashed()
->where('board_id', $board->id)
->where('id', $postId)
->first(['id', 'board_id', 'user_id', 'is_secret', 'status', 'deleted_at']);
}
/**
* 여러 ID로 첨부파일 조회 (order 정렬)
*
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Modules\Sirsoft\Board\Models\Attachment;
use Modules\Sirsoft\Board\Models\Post;
/**
* 게시판 첨부파일 Repository 인터페이스
@@ -39,6 +40,18 @@ interface AttachmentRepositoryInterface
*/
public function isPostDeleted(string $slug, int $postId): bool;
/**
* 첨부파일이 속한 게시글을 게시판 스코프로 조회합니다(비밀 게이팅용).
*
* 비밀글 첨부 서빙 시 부모 게시글의 소유자/비밀 여부를 판정하기 위해 사용합니다.
* 게시판을 찾을 수 없거나 게시글이 없으면 null 을 반환합니다.
*
* @param string $slug 게시판 슬러그
* @param int $postId 게시글 ID
* @return Post|null 게시글 모델 또는 null
*/
public function findPostForGate(string $slug, int $postId): ?Post;
/**
* 여러 ID로 첨부파일 조회 (order 정렬)
*
@@ -1064,7 +1064,7 @@ class PostRepository implements PostRepositoryInterface
* 사용자가 작성한 게시글, 댓글을 단 게시글을 통합하여 반환합니다.
*
* @param int $userId 사용자 ID
* @param array $filters 필터 조건 (board_slug, search, activity_type, sort, is_public)
* @param array $filters 필터 조건 (board_slug, search, activity_type, sort, viewer_id, exclude_board_slugs)
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 게시글 활동 목록
*/
@@ -1074,7 +1074,15 @@ class PostRepository implements PostRepositoryInterface
$search = $filters['search'] ?? null;
$activityType = $filters['activity_type'] ?? 'authored';
$sort = $filters['sort'] ?? 'latest'; // latest, oldest, views
$isPublic = $filters['is_public'] ?? false; // 공개 프로필용 필터 (비밀글 제외, 공개 게시글만)
// 열람자 관점. 이 값이 대상 사용자와 다르면(비로그인 포함) **타인 관점**이므로
// 비밀글·미발행글을 내보내지 않는다.
//
// 종전에는 `is_public` 옵트인 플래그로 이 판정을 했는데, 그 키를 설정하는 코드가
// 저장소 어디에도 없어서 필터가 한 번도 적용되지 않았다(사문). 옵트인은 호출부가
// 빠뜨리면 조용히 열리는 방향이라, 열람자 신원으로 판정하는 fail-closed 로 뒤집는다 —
// viewer_id 가 없으면 자동으로 가장 좁은 가시성이 된다.
$viewerId = $filters['viewer_id'] ?? null;
$isOwnView = $viewerId !== null && $viewerId === $userId;
$excludeBoardSlugs = $filters['exclude_board_slugs'] ?? [];
// board_slug 필터용 board_id 조회
@@ -1099,12 +1107,15 @@ class PostRepository implements PostRepositoryInterface
$cachedTotal = $filters['cached_total'] ?? null;
if ($activityType === 'commented' && ! $isPublic) {
return $this->getUserCommentedActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $orderColumn, $orderDirection, $perPage, $cachedTotal);
// 분기 선택은 activity_type 만 본다. 가시성은 각 분기 안에서 처리한다 —
// 여기서 열람자까지 보고 분기를 바꾸면 `commented` 요청이 조용히 `authored` 결과를
// 돌려주게 되어 저장소 계약이 깨진다.
if ($activityType === 'commented') {
return $this->getUserCommentedActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $orderColumn, $orderDirection, $perPage, $cachedTotal, $viewerId);
}
// authored (기본값, 공개 프로필 포함)
return $this->getUserAuthoredActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $isPublic, $orderColumn, $orderDirection, $perPage, $cachedTotal);
return $this->getUserAuthoredActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $isOwnView, $orderColumn, $orderDirection, $perPage, $cachedTotal);
}
/**
@@ -1113,7 +1124,7 @@ class PostRepository implements PostRepositoryInterface
* @param int $userId 사용자 ID
* @param int|null $boardIdFilter 게시판 ID 필터
* @param string|null $search 검색 키워드
* @param bool $isPublic 공개 프로필 여부 (비밀글 제외)
* @param bool $isOwnView 열람자가 대상 본인인지 여부 (아니면 비밀글·미발행글 제외)
* @param string $orderColumn 정렬 컬럼
* @param string $orderDirection 정렬 방향
* @param int $perPage 페이지당 항목 수
@@ -1123,7 +1134,7 @@ class PostRepository implements PostRepositoryInterface
?int $boardIdFilter,
array $excludeBoardIds,
?string $search,
bool $isPublic,
bool $isOwnView,
string $orderColumn,
string $orderDirection,
int $perPage,
@@ -1145,11 +1156,6 @@ class PostRepository implements PostRepositoryInterface
$query->whereNotIn('board_posts.board_id', $allExcludeIds);
}
if ($isPublic) {
$query->where('board_posts.status', PostStatus::Published->value)
->where('board_posts.is_secret', false);
}
if ($search) {
$keyword = $this->escapeLikeKeyword($search);
$query->where(function ($q) use ($keyword) {
@@ -1180,7 +1186,15 @@ class PostRepository implements PostRepositoryInterface
);
// paginate 후 10건에만 PHP 가공 적용 (N+1 아님)
$paginator->through(function ($post) {
$paginator->through(function ($post) use ($isOwnView) {
// 이 목록은 본문 일부(content_plain)를 함께 싣는다. 타인이 볼 때 비밀글·블라인드
// 글의 본문이 그대로 나가던 것이 결함이었다 — 행과 제목은 게시판 목록에서 이미
// 같은 수준으로 보이므로(PostResource 의 목록 규칙: 제목은 노출, 본문만 차단)
// 여기서도 **행은 남기고 본문만** 비운다. 행을 지우면 프로필의 비밀글/블라인드
// 배지가 사문이 되어 필요 이상으로 기능이 깎인다.
$hideContent = ! $isOwnView
&& ((bool) $post->is_secret || $post->status === PostStatus::Blinded);
return [
'id' => $post->id,
'board_slug' => $post->board?->slug,
@@ -1194,9 +1208,11 @@ class PostRepository implements PostRepositoryInterface
'comment_count' => (int) ($post->comments_count ?? 0),
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat($post->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
'content_plain' => ($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? ''),
'content_plain' => $hideContent
? ''
: (($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? '')),
];
});
@@ -1222,7 +1238,8 @@ class PostRepository implements PostRepositoryInterface
string $orderColumn,
string $orderDirection,
int $perPage,
?int $cachedTotal = null
?int $cachedTotal = null,
?int $viewerId = null
): LengthAwarePaginator {
// 테이블명은 모델에서 얻는다 — 문자열로 박으면 테이블명이 바뀔 때 조용히 깨진다
$postsTable = (new Post)->getTable();
@@ -1308,7 +1325,15 @@ class PostRepository implements PostRepositoryInterface
);
// paginate 후 10건에만 PHP 가공 적용
$paginator->through(function ($post) {
$paginator->through(function ($post) use ($viewerId) {
// 이 목록은 "내가 댓글 단 글" 이라 **타인이 쓴 비밀글**이 섞인다. 행은 내 활동
// 기록이므로 남기되 본문은 내보내지 않는다 — 목록 미리보기를 빈 문자열로 만드는
// PostResource::getMaskedContentPreviewForList 와 같은 규칙이다.
// (블라인드 글도 동일: 상세·목록 어느 경로에서도 본문이 나가지 않는다.)
// 열람자 미상($viewerId === null)이면 비밀글은 전부 가린다(fail-closed).
$hideContent = ((bool) $post->is_secret && (int) $post->user_id !== $viewerId)
|| $post->status === PostStatus::Blinded;
return [
'id' => $post->id,
'board_slug' => $post->board?->slug,
@@ -1322,9 +1347,11 @@ class PostRepository implements PostRepositoryInterface
'comment_count' => (int) ($post->comments_count ?? 0),
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat($post->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
'content_plain' => ($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? ''),
'content_plain' => $hideContent
? ''
: (($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? '')),
];
});
@@ -16,6 +16,7 @@ use Modules\Sirsoft\Board\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Board\Models\Attachment;
use Modules\Sirsoft\Board\Repositories\Contracts\AttachmentRepositoryInterface;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
use Modules\Sirsoft\Board\Support\SecretContentGate;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -345,6 +346,45 @@ class AttachmentService
}
}
/**
* 비밀글 첨부파일 접근 권한을 검증합니다(KVE-2026-1914).
*
* 첨부가 속한 게시글이 비밀글이면 SecretContentGate(SSoT) 판정을 통과한
* 요청(작성자 본인 또는 게시판 manager/posts.read-secret)에만 서빙합니다.
* 첨부 서빙은 상세 요청과 분리된 별도 요청이라 password_verified 는 세팅되지
* 않으므로, 비회원이 비밀번호로 검증한 경우는 이 경로에서 인정되지 않습니다
* (안전 측 실패 — 해시/ID 만으로 비밀글 첨부를 가져가는 것을 차단).
*
* @param string $slug 게시판 슬러그
* @param Attachment $attachment 첨부파일 모델
*
* @throws AccessDeniedHttpException 비밀글 첨부에 권한 없이 접근한 경우
*/
private function assertSecretPostAttachmentAccess(string $slug, Attachment $attachment): void
{
if (! $attachment->post_id) {
return;
}
$post = $this->repository->findPostForGate($slug, $attachment->post_id);
// 부모 글을 못 읽으면 막는다(fail-closed). 첨부에 post_id 가 있는데 그 글을 못 찾는
// 것은 정상 상태가 아니다 — 슬러그가 다른 게시판이거나 글이 사라진 경우이며, 통과시키면
// 게이트가 있어야 할 자리에서 무게이트가 된다. 조회는 withTrashed 라 소프트 삭제로는
// null 이 되지 않는다.
if (! $post) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
if (! $post->is_secret) {
return;
}
if (! app(SecretContentGate::class)->canView($post)) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
}
/**
* ID로 첨부파일 조회
*
@@ -380,9 +420,10 @@ class AttachmentService
*
* @param string $slug 게시판 슬러그
* @param int $id 첨부파일 ID
* @param string $context 호출 컨텍스트 (admin | user) — 스코프 권한 식별자 결정에 쓰인다
* @return bool 삭제 성공 여부
*/
public function delete(string $slug, int $id): bool
public function delete(string $slug, int $id, string $context = 'user'): bool
{
$attachment = $this->repository->findById($slug, $id);
@@ -390,6 +431,8 @@ class AttachmentService
return false;
}
$this->assertAttachmentWithinScope($slug, $attachment, $context);
// 삭제 후 재정렬을 위해 정보 저장
$postId = $attachment->post_id;
$collection = $attachment->collection;
@@ -425,10 +468,13 @@ class AttachmentService
*
* @param string $slug 게시판 슬러그
* @param array<int, int> $orders 첨부파일 ID => order 매핑
* @param string $context 호출 컨텍스트 (admin | user) — 스코프 권한 식별자 결정에 쓰인다
* @return bool 성공 여부
*/
public function reorder(string $slug, array $orders): bool
public function reorder(string $slug, array $orders, string $context = 'user'): bool
{
$this->assertReorderWithinScope($slug, $orders, $context);
// Before 훅
HookManager::doAction('sirsoft-board.attachment.before_reorder', $slug, $orders);
@@ -440,6 +486,63 @@ class AttachmentService
return $result;
}
/**
* 첨부가 액터의 스코프 안에 있는지 검사합니다.
*
* 첨부 관리 라우트는 `{id}`(정수)로 선언돼 라우트 모델 바인딩이 일어나지 않고, 순서
* 변경은 아예 정적 경로다. 두 경우 모두 PermissionMiddleware 가 모델을 resolve 하지
* 못해 스코프 검사를 건너뛰므로(목록 엔드포인트로 간주) 서비스가 재적용한다.
* 사용자 경로는 컨트롤러가 `canDelete`(작성자 본인)로 막고 있었으나 관리자 경로는
* 그 대응물이 없어 비어 있었다 — 두 경로 모두 여기서 같은 판정을 받는다.
*
* @param string $slug 게시판 슬러그
* @param Attachment $attachment 대상 첨부
*
* @throws AccessDeniedHttpException 스코프 밖 첨부인 경우
*/
private function assertAttachmentWithinScope(string $slug, Attachment $attachment, string $context): void
{
// 컨텍스트는 호출부가 명시한다 — PostService 가 쓰는 방식과 같다. 요청에서
// 컨트롤러 네임스페이스를 스니핑하는 사설 복제본이 이미 4곳에 있는데 5번째를
// 만들지 않는다.
$scopePermission = $context === 'admin'
? "sirsoft-board.{$slug}.admin.attachments.upload"
: "sirsoft-board.{$slug}.attachments.upload";
if (! PermissionHelper::checkScopeAccess($attachment, $scopePermission)) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
}
/**
* 순서 변경 대상 첨부 전체가 액터의 스코프 안에 있는지 검사합니다.
*
* 순서는 집합 전체에 대한 하나의 배열이라 일부만 반영하면 나머지와 어긋난다 —
* 걸러내지 않고 전량 거부한다(코어 첨부/메뉴 순서 변경과 같은 의미론).
*
* @param string $slug 게시판 슬러그
* @param array<int, array{id: int, order: int}> $orders 순서 데이터
*
* @throws AccessDeniedHttpException 스코프 밖 첨부가 하나라도 포함된 경우
*/
private function assertReorderWithinScope(string $slug, array $orders, string $context): void
{
$ids = array_values(array_unique(array_filter(
array_map(static fn ($item): int => (int) ($item['id'] ?? 0), $orders)
)));
foreach ($ids as $id) {
$attachment = $this->repository->findById($slug, $id);
// 이 게시판 소속이 아닌 id 는 통과시키지 않는다.
if (! $attachment) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertAttachmentWithinScope($slug, $attachment, $context);
}
}
/**
* 삭제 후 남은 파일들의 순서를 재정렬합니다.
*
@@ -517,6 +620,9 @@ class AttachmentService
// 삭제된 게시글의 첨부파일은 관리 권한자만 접근
$this->assertDeletedPostAttachmentAccess($slug, $attachment);
// 비밀글 첨부파일은 열람 권한자만 접근
$this->assertSecretPostAttachmentAccess($slug, $attachment);
// 다운로드 활동이력 기록 훅
// 권한/삭제글 가드 통과 후 발화 → 차단된 시도는 기록하지 않음.
// $context('user'|'admin')는 로그 부가정보용 (log_type 은 요청 경로로 자동 결정).
@@ -580,6 +686,9 @@ class AttachmentService
// 삭제된 게시글의 첨부파일은 관리 권한자만 접근
$this->assertDeletedPostAttachmentAccess($slug, $attachment);
// 비밀글 첨부파일은 열람 권한자만 접근
$this->assertSecretPostAttachmentAccess($slug, $attachment);
return $this->storage->response(
'attachments',
$attachment->path,
@@ -612,6 +721,9 @@ class AttachmentService
// 삭제된 게시글의 첨부파일은 관리 권한자만 접근
$this->assertDeletedPostAttachmentAccess($slug, $attachment);
// 비밀글 첨부파일은 열람 권한자만 접근
$this->assertSecretPostAttachmentAccess($slug, $attachment);
// 파일 존재 확인
if (! $this->storage->exists('attachments', $attachment->path)) {
Log::error('게시판 첨부파일 스토리지에 없음', [
@@ -882,9 +882,12 @@ class PostService
$filters['user_id'] = $requestParams['user_id'] ?? null;
$filters['created_at_from'] = $requestParams['created_at_from'] ?? null;
$filters['created_at_to'] = $requestParams['created_at_to'] ?? null;
} else {
$filters['exclude_blinded'] = true;
}
// 사용자 컨텍스트에는 추가 필터가 없다. 예전에는 여기서 `exclude_blinded` 를 세웠지만
// 저장소가 그 키를 읽지 않아 한 번도 적용되지 않았고, 뒤늦게 배선하면 블라인드 글이
// 사용자 목록에서 통째로 사라진다 — 이 모듈은 블라인드 글을 **행은 남기고 본문만
// 가리는** 방식으로 다루며(PostResource::getMaskedContentPreviewForList) 레이아웃도
// 블라인드 배지를 그린다. 죽은 키를 살리는 대신 제거해 표시만 오해를 주던 상태를 없앤다.
// 페이지당 항목 수 계산
$requestedPerPage = isset($requestParams['per_page']) ? (int) $requestParams['per_page'] : null;
@@ -1070,6 +1073,10 @@ class PostService
}
}
// 본인 활동 화면(`/me/board-activities`)이므로 열람자 = 대상 본인이다.
// 저장소는 이 값이 없으면 타인 관점으로 보고 비밀글·미발행글을 걸러낸다(fail-closed).
$filters['viewer_id'] = $userId;
$result = $this->postRepository->getUserActivities($userId, $filters, $perPage);
// 캐시 미적중 시 paginate 결과의 total을 캐시에 저장
@@ -1105,9 +1112,12 @@ class PostService
/**
* 사용자의 공개 게시글 목록을 조회합니다 (공개 프로필용).
*
* 기존 getUserActivities()를 재사용합니다.
* 타인 프로필에서 해당 사용자의 모든 게시글을 표시합니다 (비밀글/블라인드 포함).
* UI에서 배지로 비밀글/블라인드 상태를 구분합니다.
* 기존 getUserActivities()를 재사용합니다. 이 목록은 본문 일부(content_plain)를 함께
* 싣기 때문에, 열람자가 본인이 아니면 비밀글·블라인드 글의 **본문만** 비운다. 행과
* 제목은 남는다 — 게시판 목록에서 이미 같은 수준으로 보이고(PostResource 의 목록 규칙:
* 제목은 노출, 본문만 차단) 프로필 UI 가 그 배지를 그리므로, 행을 지우면 결함 차단에
* 필요한 범위를 넘어 기능이 깎인다.
* 판정은 저장소가 `viewer_id` 로 수행한다(fail-closed — 값이 없으면 타인 관점).
*
* @param int $userId 사용자 ID
* @param array $filters 필터 옵션 (board_slug, sort 등)
@@ -1116,10 +1126,9 @@ class PostService
*/
public function getUserPublicPosts(int $userId, array $filters = [], int $perPage = 20): LengthAwarePaginator
{
// 기존 getUserActivities 재사용
// 타인 프로필에서 해당 사용자의 모든 게시글 표시 (비밀글/블라인드 포함, 배지로 구분)
return $this->postRepository->getUserActivities($userId, array_merge($filters, [
'activity_type' => 'authored', // 작성글만
'viewer_id' => Auth::id(), // 비로그인은 null → 타인 관점
]), $perPage);
}
@@ -0,0 +1,101 @@
<?php
namespace Modules\Sirsoft\Board\Support;
use App\Enums\PermissionType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
/**
* 비밀글 원문 열람 권한 판정 SSoT
*
* 비밀글 게이팅이 PostResource 한 곳에만 있던 탓에 이커머스 연동 훅·댓글 목록 등
* 다른 경로가 서버측 마스킹 없이 원문을 반환하던 결함(KVE-2026-1914)을 막기 위해,
* 열람 판정 규칙을 한 지점으로 모읍니다. PostResource·리스너·댓글 경로가 모두
* 이 게이트를 호출해 규칙 드리프트를 방지합니다.
*
* 열람 가능 조건 (우선순위 순):
* 1. 작성자 본인 (회원 게시글)
* 2. 비밀번호 검증 완료 (`password_verified` 플래그 — 상세 컨텍스트에서만 설정, 리스트 미적용)
* 3. 게시판별 비밀글 읽기 권한 (posts.read-secret)
* 4. 게시판 관리자 권한 (Admin: admin.manage / User: manager)
*/
class SecretContentGate
{
use ChecksBoardPermission;
/**
* 주어진 게시글의 비밀 원문을 현재 요청자가 열람할 수 있는지 판정합니다.
*
* 게시판 슬러그를 해석할 수 없으면(라우트 슬러그 부재 + board 미로딩) 안전하게
* false(마스킹)로 실패합니다.
*
* @param Post $post 대상 게시글
* @param Request|null $request HTTP 요청 (미지정 시 현재 요청)
* @return bool 열람 가능 여부
*/
public function canView(Post $post, ?Request $request = null): bool
{
$request = $request ?? request();
// 1. 작성자 본인 (회원 게시글)
$user = Auth::user();
if ($user && $post->user_id && $post->user_id === $user->id) {
return true;
}
// 2. 비밀번호 검증 완료 (상세 컨텍스트에서만 세팅됨)
if (($post->password_verified ?? false) === true) {
return true;
}
// 3-4. 게시판별 권한 체크
$slug = $this->resolveSlug($post, $request);
if (! $slug) {
return false;
}
if ($this->isAdminRequest($request)) {
return $this->checkBoardPermission($slug, 'admin.posts.read-secret')
|| $this->checkBoardPermission($slug, 'admin.manage');
}
return $this->checkBoardPermission($slug, 'posts.read-secret', PermissionType::User)
|| $this->checkBoardPermission($slug, 'manager', PermissionType::User);
}
/**
* 게시판 슬러그를 해석합니다.
*
* 라우트 슬러그를 우선 사용하고, 없으면 로드된 board 관계에서 가져옵니다.
* board 가 미로딩이면 lazy loading N+1 을 피하기 위해 null 을 반환합니다
* (호출부가 fail-closed 마스킹).
*
* @param Post $post 대상 게시글
* @param Request $request HTTP 요청
* @return string|null 게시판 슬러그
*/
private function resolveSlug(Post $post, Request $request): ?string
{
return $request->route('slug') ?? ($post->relationLoaded('board') ? $post->board?->slug : null);
}
/**
* Admin 요청 여부를 확인합니다.
*
* @param Request $request HTTP 요청
* @return bool Admin 요청 여부
*/
private function isAdminRequest(Request $request): bool
{
$controller = $request->route()?->getController();
if (! $controller) {
return false;
}
return str_contains(get_class($controller), '\\Admin\\');
}
}
@@ -44,6 +44,7 @@ return [
'secret_password_incorrect' => 'Secret post password is incorrect.',
// Secret post filtering messages
'secret_post_content' => 'This is a secret post. Please enter the password to view the content.',
'secret_post_title' => 'Secret post',
'deleted_post_title' => 'Deleted post',
'deleted_post_content' => 'This post has been deleted.',
'blinded_post_content' => 'This post has been blinded by administrator.',
@@ -44,6 +44,7 @@ return [
'secret_password_incorrect' => '비밀글 비밀번호가 일치하지 않습니다.',
// 비밀글 필터링 메시지
'secret_post_content' => '비밀글입니다. 내용을 보려면 비밀번호를 입력해 주세요.',
'secret_post_title' => '비밀글',
'deleted_post_title' => '삭제된 게시글',
'deleted_post_content' => '삭제된 게시글입니다.',
'blinded_post_content' => '관리자에 의해 블라인드 처리된 게시글입니다.',
@@ -504,8 +504,8 @@ Route::post('boards/{slug}/comments/{commentId}/verify-password', [UserCommentCo
| 로그인한 회원의 게시글 활동(작성, 댓글, 신고)을 조회하는 API입니다.
| - 회원만 접근 가능하므로 auth:sanctum 미들웨어 필요
|
| 최종 URL 예시: /api/me/board-activities
| 최종 Name 예시: api.me.board-activities.index
| 최종 URL 예시: /api/modules/sirsoft-board/me/board-activities
| 최종 Name 예시: api.modules.sirsoft-board.me.board-activities.index
|
*/
Route::get('/me/board-activities', [UserActivityController::class, 'index'])
@@ -0,0 +1,309 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature\User;
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 비밀글 첨부파일 접근 차단 테스트 (KVE-2026-1914 A-3)
*
* 첨부는 본문 게이팅(getFilteredContent)과 별개 경로라, 본문이 비밀 마스킹되어도
* 첨부 다운로드/미리보기는 게시글 비밀 상태를 검사하지 않아 해시/ID 만으로 원문
* 파일이 노출되던 결함을 검증합니다.
*
* 정책: 비밀글 첨부는 작성자 본인 또는 게시판 manager/posts.read-secret 보유자만 접근.
*
* 실제 공격자 프로필은 대개 미인증(게스트)이다. preview 라우트는 permission
* 미들웨어 없이 optional.sanctum 만 걸려(공개 썸네일 정책) 컨트롤러/서비스의 비밀
* 게이트만이 게스트를 막는다 — 그래서 게스트 축을 명시 고정한다. download 라우트는
* permission 미들웨어가 게스트를 401 로 선차단한다.
*
* 시나리오 축(viewer)·효과는 매니페스트 tests/scenarios/board-secret-content-gate.yaml 참조.
* 각 test 메서드의 `@scenario viewer=…` 마커가 축 조합을 커버한다(메서드당 단일 값).
*
* 효과 목록을 클래스 레벨에 몰아 적지 않는다 — 커버리지 룰은 마커 레벨을 구분하지 않으므로,
* 클래스 레벨 목록이 있으면 그 메서드를 지워도 효과가 "언급됨" 으로 집계돼 삭제가 무증상
* green 이 된다. 마커는 메서드에만 둔다.
*/
class SecretPostAttachmentAccessTest extends BoardTestCase
{
private User $regularUser;
private User $ownerUser;
private User $managerUser;
protected function getTestBoardSlug(): string
{
return 'secret-attach';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '비밀 첨부 테스트 게시판', 'en' => 'Secret Attachment Test Board'],
'is_active' => true,
'use_comment' => true,
'secret_mode' => 'enabled',
'blocked_keywords' => [],
];
}
protected function setUp(): void
{
parent::setUp();
$slug = $this->board->slug;
// 일반 사용자 (posts.read + attachments.download, 비밀 열람 권한 없음)
$this->regularUser = User::factory()->create();
$this->ownerUser = User::factory()->create();
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
foreach (['posts.read', 'attachments.download'] as $key) {
$perm = Permission::firstOrCreate(
['identifier' => "sirsoft-board.{$slug}.{$key}"],
['name' => ['ko' => $key, 'en' => $key], 'type' => 'user']
);
$userRole->permissions()->syncWithoutDetaching([$perm->id]);
}
$this->regularUser->roles()->attach($userRole->id);
$this->ownerUser->roles()->attach($userRole->id);
}
// manager 권한 사용자
$this->managerUser = User::factory()->create();
$managerRole = Role::firstOrCreate(
['identifier' => "{$slug}-manager"],
['name' => ['ko' => '게시판 매니저', 'en' => 'Board Manager']]
);
foreach (['posts.read', 'attachments.download', 'manager'] as $key) {
$perm = Permission::firstOrCreate(
['identifier' => "sirsoft-board.{$slug}.{$key}"],
['name' => ['ko' => $key, 'en' => $key], 'type' => 'user']
);
$managerRole->permissions()->syncWithoutDetaching([$perm->id]);
}
$this->managerUser->roles()->attach($managerRole->id);
}
private function createAttachment(int $postId, string $hash, bool $image = false): int
{
$ext = $image ? 'jpg' : 'pdf';
$mime = $image ? 'image/jpeg' : 'application/pdf';
return DB::table('board_attachments')->insertGetId([
'board_id' => $this->board->id,
'post_id' => $postId,
'original_filename' => "doc.{$ext}",
'stored_filename' => "{$hash}.{$ext}",
'hash' => $hash,
'mime_type' => $mime,
'size' => 1024,
'path' => "attachments/doc.{$ext}",
'collection' => 'attachments',
'created_at' => now(),
'updated_at' => now(),
]);
}
private function downloadUrl(string $hash): string
{
return "/api/modules/sirsoft-board/boards/{$this->board->slug}/attachment/{$hash}";
}
private function previewUrl(string $hash): string
{
return "/api/modules/sirsoft-board/boards/{$this->board->slug}/attachment/{$hash}/preview";
}
private function secretPost(): int
{
return $this->createTestPost([
'title' => '비밀글 첨부',
'status' => 'published',
'is_secret' => true,
'user_id' => $this->ownerUser->id,
'author_name' => 'owner',
]);
}
// ==========================================
// 비밀글 첨부 차단
// ==========================================
/**
* @scenario viewer=regular
*
* @effects regular_user_cannot_download_secret_post_attachment
*/
public function test_regular_user_cannot_download_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secdlregAAAA');
$response = $this->actingAs($this->regularUser, 'sanctum')
->get($this->downloadUrl('secdlregAAAA'));
// attachments.download 권한은 있으나 비밀 게이트로 차단(403)
$response->assertStatus(403);
}
/**
* @scenario viewer=regular
*
* @effects regular_user_cannot_preview_secret_post_attachment
*/
public function test_regular_user_cannot_preview_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secprevregAA', image: true);
$response = $this->actingAs($this->regularUser, 'sanctum')
->get($this->previewUrl('secprevregAA'));
$response->assertStatus(403);
}
// ==========================================
// 미인증(게스트) 차단 — 실제 공격자 프로필
// ==========================================
/**
* 미인증(게스트)은 비밀글 첨부 미리보기를 볼 수 없다 (403).
*
* preview 라우트는 permission 미들웨어가 없어(optional.sanctum 만) 컨트롤러/서비스의
* 비밀 게이트만이 게스트를 막는다 — 해시만 쥔 미인증 공격자가 실제로 차단되는지 고정한다.
*
* @scenario viewer=guest
*
* @effects guest_cannot_preview_secret_post_attachment
*/
public function test_guest_cannot_preview_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secprevgstAA', image: true);
// actingAs 없음 = 미인증 게스트
$response = $this->get($this->previewUrl('secprevgstAA'));
$response->assertStatus(403);
}
/**
* 미인증(게스트)은 비밀글 첨부 다운로드를 할 수 없다 (401).
*
* download 라우트는 attachments.download permission 미들웨어가 걸려 있어 게스트를
* 컨트롤러 도달 전에 401(guest_permission_denied)로 선차단한다.
*
* @scenario viewer=guest
*
* @effects guest_cannot_download_secret_post_attachment
*/
public function test_guest_cannot_download_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secdlgstAAAA');
$response = $this->get($this->downloadUrl('secdlgstAAAA'));
$response->assertStatus(401);
}
/**
* 미인증(게스트)도 정상글(비밀 아님) 첨부 미리보기는 차단되지 않는다 (게이트 과차단 회귀 방지).
*
* 공개 썸네일 정책상 preview 는 공개다 — 비밀 게이트가 정상글 게스트 미리보기까지
* 막으면 안 된다. 실제 파일이 없어 404 여도 403(비밀 차단)은 아니어야 한다.
*
* @scenario viewer=guest
*
* @effects guest_can_preview_normal_post_attachment
*/
public function test_guest_can_preview_normal_post_attachment(): void
{
$postId = $this->createTestPost([
'title' => '정상글 첨부(게스트 미리보기)',
'status' => 'published',
'is_secret' => false,
]);
$this->createAttachment($postId, 'normgstAAAAA', image: true);
$response = $this->get($this->previewUrl('normgstAAAAA'));
$this->assertNotSame(403, $response->getStatusCode(), '정상글 첨부 미리보기는 게스트에게 비밀 차단되면 안 됩니다');
$this->assertLessThan(500, $response->getStatusCode(), '게이트 통과 시 서버 오류가 아니어야 합니다');
}
// ==========================================
// 작성자/manager 는 접근 가능 (회귀 방지)
// ==========================================
/**
* @scenario viewer=owner
*
* @effects owner_can_access_secret_post_attachment
*/
public function test_owner_can_access_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secdlownerAA');
$response = $this->actingAs($this->ownerUser, 'sanctum')
->get($this->downloadUrl('secdlownerAA'));
// 작성자 본인은 비밀 게이트 통과 (실제 파일 없어 404 여도 403 은 아님)
$this->assertNotSame(403, $response->getStatusCode(), '작성자 본인은 비밀글 첨부에 접근 가능해야 합니다');
$this->assertLessThan(500, $response->getStatusCode(), '게이트 통과 시 서버 오류가 아니어야 합니다');
}
/**
* @scenario viewer=manager
*
* @effects manager_can_access_secret_post_attachment
*/
public function test_manager_can_access_secret_post_attachment(): void
{
$postId = $this->secretPost();
$this->createAttachment($postId, 'secdlmgrAAAA');
$response = $this->actingAs($this->managerUser, 'sanctum')
->get($this->downloadUrl('secdlmgrAAAA'));
$this->assertNotSame(403, $response->getStatusCode(), 'manager 는 비밀글 첨부에 접근 가능해야 합니다');
$this->assertLessThan(500, $response->getStatusCode(), '게이트 통과 시 서버 오류가 아니어야 합니다');
}
// ==========================================
// 정상글 첨부는 그대로 (회귀 방지)
// ==========================================
/**
* @scenario viewer=regular
*
* @effects normal_post_attachment_still_public
*/
public function test_normal_post_attachment_still_public(): void
{
$postId = $this->createTestPost([
'title' => '정상글 첨부',
'status' => 'published',
'is_secret' => false,
]);
$this->createAttachment($postId, 'normsecAAAAA');
$response = $this->actingAs($this->regularUser, 'sanctum')
->get($this->downloadUrl('normsecAAAAA'));
$this->assertNotSame(403, $response->getStatusCode(), '정상글 첨부는 권한 차단되면 안 됩니다');
$this->assertLessThan(500, $response->getStatusCode(), '게이트 통과 시 서버 오류가 아니어야 합니다');
}
}
@@ -0,0 +1,314 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature\User;
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Http\Resources\CommentResource;
use Modules\Sirsoft\Board\Models\Comment;
use Modules\Sirsoft\Board\Models\Post;
use Modules\Sirsoft\Board\Services\CommentService;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 비밀글 댓글 목록 게이팅 테스트 (KVE-2026-1914 A-4)
*
* 댓글 목록은 부모 게시글 비밀 상태를 검사하지 않아, 비밀글의 댓글이 비열람자에게
* 그대로 노출되던 결함을 검증합니다.
*
* 정책: 부모 게시글이 비밀글이면 열람 권한(작성자/manager/posts.read-secret) 없는
* 요청에는 댓글 목록을 노출하지 않는다(빈 목록).
*
* 실제 공격자 프로필은 미인증(게스트)이다. 사용자 댓글 목록 라우트는 comments.read
* permission 미들웨어가 걸려 있어 그 권한이 없는 게스트를 401 로 선차단한다(부모가
* 비밀글이든 아니든). 게스트가 permission 을 갖는 공개 게시판이라도 비밀 게이트가 빈
* 목록을 돌려주는 것은 regular(비밀 권한 없는 회원) 경로와 동일하다.
*
* 시나리오 축(viewer)·효과는 매니페스트 tests/scenarios/board-secret-content-gate.yaml 참조.
* 각 test 메서드의 `@scenario viewer=…` 마커가 축 조합을 커버한다(메서드당 단일 값).
*
* 효과 목록을 클래스 레벨에 몰아 적지 않는다 — 커버리지 룰은 마커 레벨을 구분하지 않으므로,
* 클래스 레벨 목록이 있으면 그 메서드를 지워도 효과가 "언급됨" 으로 집계돼 삭제가 무증상
* green 이 된다. 마커는 메서드에만 둔다.
*/
class SecretPostCommentAccessTest extends BoardTestCase
{
private User $regularUser;
private User $ownerUser;
private User $managerUser;
protected function getTestBoardSlug(): string
{
return 'secret-comment';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '비밀 댓글 테스트 게시판', 'en' => 'Secret Comment Test Board'],
'is_active' => true,
'use_comment' => true,
'secret_mode' => 'enabled',
'blocked_keywords' => [],
];
}
protected function setUp(): void
{
parent::setUp();
$slug = $this->board->slug;
$this->regularUser = User::factory()->create();
$this->ownerUser = User::factory()->create();
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
foreach (['posts.read', 'comments.read'] as $key) {
$perm = Permission::firstOrCreate(
['identifier' => "sirsoft-board.{$slug}.{$key}"],
['name' => ['ko' => $key, 'en' => $key], 'type' => 'user']
);
$userRole->permissions()->syncWithoutDetaching([$perm->id]);
}
$this->regularUser->roles()->attach($userRole->id);
$this->ownerUser->roles()->attach($userRole->id);
}
$this->managerUser = User::factory()->create();
$managerRole = Role::firstOrCreate(
['identifier' => "{$slug}-manager"],
['name' => ['ko' => '게시판 매니저', 'en' => 'Board Manager']]
);
foreach (['posts.read', 'comments.read', 'manager'] as $key) {
$perm = Permission::firstOrCreate(
['identifier' => "sirsoft-board.{$slug}.{$key}"],
['name' => ['ko' => $key, 'en' => $key], 'type' => 'user']
);
$managerRole->permissions()->syncWithoutDetaching([$perm->id]);
}
$this->managerUser->roles()->attach($managerRole->id);
}
private function commentsUrl(int $postId): string
{
return "/api/modules/sirsoft-board/boards/{$this->board->slug}/posts/{$postId}/comments";
}
private function secretPostWithComment(): int
{
$postId = $this->createTestPost([
'title' => '비밀글',
'status' => 'published',
'is_secret' => true,
'user_id' => $this->ownerUser->id,
'author_name' => 'owner',
]);
$this->createTestComment($postId, [
'content' => '비밀 댓글 내용',
'user_id' => $this->ownerUser->id,
'author_name' => 'owner',
]);
return $postId;
}
/**
* @scenario viewer=regular
*
* @effects regular_user_gets_empty_comment_list_on_secret_post
*/
public function test_regular_user_gets_empty_comment_list_on_secret_post(): void
{
$postId = $this->secretPostWithComment();
$response = $this->actingAs($this->regularUser, 'sanctum')
->getJson($this->commentsUrl($postId));
$response->assertStatus(200);
$this->assertCount(0, $response->json('data'), '비열람자에게는 비밀글 댓글이 노출되면 안 됩니다');
}
/**
* @scenario viewer=owner
*
* @effects owner_sees_secret_post_comments
*/
public function test_owner_sees_secret_post_comments(): void
{
$postId = $this->secretPostWithComment();
$response = $this->actingAs($this->ownerUser, 'sanctum')
->getJson($this->commentsUrl($postId));
$response->assertStatus(200);
$this->assertGreaterThanOrEqual(1, count($response->json('data')), '작성자 본인은 비밀글 댓글을 볼 수 있어야 합니다');
}
/**
* @scenario viewer=manager
*
* @effects manager_sees_secret_post_comments
*/
public function test_manager_sees_secret_post_comments(): void
{
$postId = $this->secretPostWithComment();
$response = $this->actingAs($this->managerUser, 'sanctum')
->getJson($this->commentsUrl($postId));
$response->assertStatus(200);
$this->assertGreaterThanOrEqual(1, count($response->json('data')), 'manager 는 비밀글 댓글을 볼 수 있어야 합니다');
}
/**
* 미인증(게스트)은 비밀글 댓글 목록에 접근할 수 없다 (401).
*
* 사용자 댓글 목록 라우트는 comments.read permission 미들웨어가 걸려 있어, 그 권한이
* 없는 게스트는 컨트롤러(비밀 게이트) 도달 전에 401 로 차단된다 — 해시/ID 로 비밀글
* 댓글을 훑는 미인증 공격자를 막는다.
*
* @scenario viewer=guest
*
* @effects guest_blocked_from_secret_post_comments
*/
public function test_guest_blocked_from_secret_post_comments(): void
{
$postId = $this->secretPostWithComment();
// actingAs 없음 = 미인증 게스트
$response = $this->getJson($this->commentsUrl($postId));
$response->assertStatus(401);
}
/**
* @scenario viewer=regular
*
* @effects normal_post_comments_still_visible
*/
public function test_normal_post_comments_still_visible(): void
{
$postId = $this->createTestPost([
'title' => '정상글',
'status' => 'published',
'is_secret' => false,
]);
$this->createTestComment($postId, ['content' => '정상 댓글']);
$response = $this->actingAs($this->regularUser, 'sanctum')
->getJson($this->commentsUrl($postId));
$response->assertStatus(200);
$this->assertGreaterThanOrEqual(1, count($response->json('data')), '정상글 댓글은 노출되어야 합니다');
}
/**
* 2차 방어(이중 방어): 컨트롤러가 넘긴 부모 post 를 CommentResource 가 요청 속성으로 받아
* 비밀글 댓글 원문을 마스킹한다 — 1차 방어(index 빈 컬렉션)가 회귀해 비뷰어가 목록에
* 도달하더라도 Resource 층에서 원문이 새지 않음을 고정한다(KVE-2026-1914 A-4b).
*
* 이 테스트는 수정 전(2차 방어가 relationLoaded('post') 만 검사, 목록에서 post 미로드라 항상
* no-op) 에는 content 가 노출되어 실패한다.
*
* @scenario viewer=guest
*
* @effects second_defense_masks_secret_comment_content
*/
public function test_second_defense_masks_secret_comment_content_via_request_attribute(): void
{
$postId = $this->secretPostWithComment();
$post = Post::find($postId);
$comment = Comment::where('post_id', $postId)->first();
$this->assertNotNull($comment, '비밀글에 댓글이 존재해야 합니다');
// 게스트(비뷰어) 요청 + 컨트롤러 index 가 넘기는 부모 post 속성
$request = Request::create($this->commentsUrl($postId), 'GET');
$request->attributes->set('sirsoft_board_parent_post', $post);
app()->instance('request', $request);
$arr = (new CommentResource($comment))->toArray($request);
$this->assertArrayHasKey('content', $arr);
$this->assertNull($arr['content'], '부모가 비밀글인 댓글은 2차 방어로 원문이 마스킹되어야 합니다');
}
/**
* 성능 실측: 댓글 목록 Resource 해석 시 부모 post 를 댓글당 lazy-load 하지 않아야 한다.
* CommentResource::toArray 34행 `$this->post?->board?->slug` 가 content 계산 전 post 를
* lazy-load 하면 댓글 N건에 post 쿼리 N건(N+1)이 발생한다 — 컨트롤러가 부모 post 를
* 요청 속성으로 전달하면 0건이어야 한다.
*
* @scenario viewer=regular
*
* @effects comment_list_no_per_comment_post_query
*/
public function test_comment_list_does_not_lazy_load_post_per_comment(): void
{
$postId = $this->createTestPost([
'title' => '정상글(쿼리 실측)',
'status' => 'published',
'is_secret' => false,
]);
for ($i = 0; $i < 5; $i++) {
$this->createTestComment($postId, ['content' => "댓글 {$i}"]);
}
$post = Post::find($postId);
$comments = app(CommentService::class)
->getCommentsByPostId($this->board->slug, $postId, 'user');
// 컨트롤러 index 가 넘기는 부모 post 속성
$request = Request::create($this->commentsUrl($postId), 'GET');
$request->attributes->set('sirsoft_board_parent_post', $post);
app()->instance('request', $request);
DB::enableQueryLog();
CommentResource::collection($comments)->toArray($request);
$queries = DB::getQueryLog();
DB::disableQueryLog();
$postQueries = array_filter($queries, fn ($q) => str_contains($q['query'], 'board_posts'));
fwrite(STDERR, "\n[PERF] board_posts 쿼리 ".count($postQueries).'건 / 댓글 '.$comments->count()."건\n");
// 컨트롤러가 부모 post 를 요청 속성으로 넘기므로 Resource 해석은 board_posts 를 한 번도
// 조회하지 않아야 한다(정확히 0건). ≤1 로 두면 단일 post 재조회 회귀를 놓친다.
$this->assertSame(
0,
count($postQueries),
'댓글 목록 Resource 해석에서 부모 post 를 조회하면 안 됩니다(N+1). 컨트롤러가 넘긴 post 재사용 → 0건'
);
}
/**
* 2차 방어가 부모 post 컨텍스트 없이는(상세/생성 경로 하위호환) relationLoaded('post') 로
* 폴백함을 고정 — 정상 뷰어(작성자)는 마스킹되지 않는다.
*
* @scenario viewer=owner
*
* @effects owner_second_defense_not_masked
*/
public function test_second_defense_does_not_mask_for_owner(): void
{
$postId = $this->secretPostWithComment();
$post = Post::find($postId);
$comment = Comment::where('post_id', $postId)->first();
$this->actingAs($this->ownerUser, 'sanctum');
$request = Request::create($this->commentsUrl($postId), 'GET');
$request->setUserResolver(fn () => $this->ownerUser);
$request->attributes->set('sirsoft_board_parent_post', $post);
app()->instance('request', $request);
$arr = (new CommentResource($comment))->toArray($request);
$this->assertNotNull($arr['content'], '작성자 본인에게는 비밀글 댓글 원문이 노출되어야 합니다');
}
}
@@ -0,0 +1,282 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Feature\User;
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* 사용자 활동/공개 프로필 목록의 비밀글 본문 노출 차단 (KVE-2026-1914 형제)
*
* 이 두 목록은 본문 일부(`content_plain`, 1000자)를 함께 싣는데 Resource 를 거치지 않고
* 저장소 배열을 그대로 응답에 싣는다. 공개 프로필 라우트는 `optional.sanctum` 이라
* **미인증**으로 도달하므로, 타인의 비밀글·블라인드 글 본문이 그대로 나갔다.
*
* 결함의 형태는 **사문화된 옵트인 플래그**였다 — 저장소가 `is_public` 을 읽어 필터를 걸도록
* 돼 있었지만 그 키를 설정하는 코드가 어디에도 없어(전수 grep write 0건) 한 번도 적용되지
* 않았다. 판정을 열람자 신원(`viewer_id`) 기반 fail-closed 로 뒤집었다.
*
* 가리는 것은 **본문뿐**이다. 행과 제목은 게시판 목록에서 이미 같은 수준으로 노출되며
* (`PostResource` 의 목록 규칙: 제목은 노출, 본문만 차단) 프로필 UI 도 비밀글/블라인드
* 배지를 그린다 — 행을 지우면 결함 차단에 필요한 범위를 넘어 기능이 깎인다.
*
* 시나리오 축·효과는 매니페스트 tests/scenarios/board-activity-secret-masking.yaml 참조.
* 각 test 메서드의 `@scenario viewer=…, activity_type=…` 마커가 축 조합을, `@effects …` 가
* 효과를 커버한다(메서드당 단일 조합).
*
* 축 요약(마커 아님 — 평문): viewer 는 guest·other_user·owner, activity_type 은
* authored·commented 다. 클래스 레벨에 `@effects` 를 몰아 적으면 그 메서드가 하나도 없어도
* 매니페스트 효과가 "언급됨" 으로 집계되어 커버리지를 부풀린다 — 마커는 메서드에만 둔다.
*/
class UserActivitySecretExposureTest extends BoardTestCase
{
private User $author;
private User $stranger;
protected function getTestBoardSlug(): string
{
return 'activity-secret';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '활동 노출 테스트 게시판', 'en' => 'Activity Exposure Test Board'],
'is_active' => true,
'use_comment' => true,
'secret_mode' => 'enabled',
'blocked_keywords' => [],
];
}
protected function setUp(): void
{
parent::setUp();
$slug = $this->board->slug;
$this->author = User::factory()->create();
$this->stranger = User::factory()->create();
$userRole = Role::where('identifier', 'user')->first();
if ($userRole) {
foreach (['posts.read', 'comments.read', 'comments.create'] as $key) {
$perm = Permission::firstOrCreate(
['identifier' => "sirsoft-board.{$slug}.{$key}"],
['name' => ['ko' => $key, 'en' => $key], 'type' => 'user']
);
$userRole->permissions()->syncWithoutDetaching([$perm->id]);
}
$this->author->roles()->attach($userRole->id);
$this->stranger->roles()->attach($userRole->id);
}
}
private function profileUrl(User $user): string
{
return "/api/modules/sirsoft-board/users/{$user->uuid}/posts";
}
/**
* 마이페이지 활동 목록(내가 댓글 단 글) URL.
*
* 라우트 이름으로 뽑는다 — 모듈 라우트는 `api/modules/{id}` 프리픽스가 그룹에서 붙으므로
* 경로를 손으로 적으면 프리픽스를 빠뜨려 404 가 되고, 그 404 는 마스킹 단언에 도달하기
* 전에 났다는 사실이 드러나지 않으면 "차단됐다" 로 오독되기 쉽다.
*/
private function commentedActivityUrl(): string
{
return route('api.modules.sirsoft-board.me.board-activities.index', [
'activity_type' => 'commented',
], false);
}
private function createAuthorPost(array $overrides = []): int
{
return $this->createTestPost(array_merge([
'title' => '작성자 글',
'content' => '대외비 본문입니다',
'status' => 'published',
'is_secret' => false,
'user_id' => $this->author->id,
'author_name' => 'author',
], $overrides));
}
/**
* 미인증 요청에 타인 비밀글의 **본문**이 나가지 않는다 (행·제목은 유지).
*
* 이 라우트는 optional.sanctum 이라 로그인 없이 도달한다 — 결함의 실제 공격 프로필이다.
*
* @scenario viewer=guest, activity_type=authored
*
* @effects public_profile_masks_secret_post_content_for_others, activity_rows_and_titles_remain_visible
*/
public function test_guest_sees_secret_post_row_without_content(): void
{
$this->createAuthorPost(['title' => '공개글', 'is_secret' => false]);
$this->createAuthorPost(['title' => '비밀글', 'is_secret' => true, 'content' => '비밀 본문']);
$response = $this->getJson($this->profileUrl($this->author));
$response->assertStatus(200);
$rows = $response->json('data.data') ?? [];
$titles = array_column($rows, 'title');
// 행·제목은 게시판 목록에서 이미 같은 수준으로 보인다 — 가리는 것은 본문뿐이다.
$this->assertContains('공개글', $titles);
$this->assertContains('비밀글', $titles, '비밀글도 목록에는 나와야 합니다(배지로 구분)');
$this->assertStringNotContainsString('비밀 본문', $response->getContent(), '비밀글 본문이 응답에 실리면 안 됩니다');
}
/**
* 미인증 요청에 블라인드 글의 **본문**도 나가지 않는다 (행은 유지).
*
* 블라인드 본문은 이 모듈의 다른 목록에서도 비워진다
* (PostResource::getMaskedContentPreviewForList) — 같은 규칙이다.
*
* @scenario viewer=guest, activity_type=authored
*
* @effects public_profile_masks_blinded_post_content_for_others, activity_rows_and_titles_remain_visible
*/
public function test_guest_sees_blinded_post_row_without_content(): void
{
$this->createAuthorPost(['title' => '공개글']);
$this->createAuthorPost(['title' => '블라인드글', 'status' => 'blinded', 'content' => '가려진 본문']);
$response = $this->getJson($this->profileUrl($this->author));
$titles = array_column($response->json('data.data') ?? [], 'title');
$this->assertContains('블라인드글', $titles, '블라인드 글도 목록에는 나와야 합니다');
$this->assertStringNotContainsString('가려진 본문', $response->getContent());
}
/**
* 로그인한 타인에게도 동일하게 본문만 가려진다 (인증 여부와 무관한 판정).
*
* @scenario viewer=other_user, activity_type=authored
*
* @effects public_profile_masks_secret_post_content_for_others
*/
public function test_other_authenticated_user_sees_secret_post_row_without_content(): void
{
$this->createAuthorPost(['title' => '비밀글', 'is_secret' => true, 'content' => '비밀 본문']);
$response = $this->actingAs($this->stranger, 'sanctum')
->getJson($this->profileUrl($this->author));
$titles = array_column($response->json('data.data') ?? [], 'title');
$this->assertContains('비밀글', $titles);
$this->assertStringNotContainsString('비밀 본문', $response->getContent(), '로그인한 타인에게도 본문은 나가면 안 됩니다');
}
/**
* (과차단 회귀) 본인이 자기 프로필을 보면 자기 비밀글의 본문까지 그대로 보인다.
*
* fail-closed 로 뒤집으면서 본인 시야까지 좁히면 기능 축소다.
*
* @scenario viewer=owner, activity_type=authored
*
* @effects public_profile_shows_own_secret_content_to_owner
*/
public function test_owner_still_sees_own_secret_post_content(): void
{
$this->createAuthorPost(['title' => '비밀글', 'is_secret' => true, 'content' => '비밀 본문']);
$response = $this->actingAs($this->author, 'sanctum')
->getJson($this->profileUrl($this->author));
$rows = $response->json('data.data') ?? [];
$titles = array_column($rows, 'title');
$this->assertContains('비밀글', $titles, '본인에게는 자기 비밀글이 보여야 합니다');
$this->assertStringContainsString('비밀 본문', $response->getContent(), '본인에게는 본문도 보여야 합니다');
}
/**
* "내가 댓글 단 글" 목록에는 **타인이 쓴** 비밀글이 섞인다 — 그 본문은 나가지 않는다.
*
* authored 축과 다른 코드 경로다. authored 는 목록 주인이 곧 글쓴이라 열람자 일치만
* 보면 되지만(`$isOwnView`), commented 는 글마다 작성자가 달라 **글 단위**로 판정한다
* (`$post->user_id !== $viewerId`). authored 만 검증하면 이 분기가 무보호로 남는다.
*
* @scenario viewer=other_user, activity_type=commented
*
* @effects commented_activity_masks_others_secret_content, activity_rows_and_titles_remain_visible
*/
public function test_commented_activity_masks_others_secret_post_content(): void
{
$postId = $this->createAuthorPost([
'title' => '남의 비밀글',
'is_secret' => true,
'content' => '남의 비밀 본문',
]);
// 열람자(stranger)가 그 글에 댓글을 달아 자기 활동 목록에 올린다.
$this->createTestComment($postId, [
'user_id' => $this->stranger->id,
'author_name' => 'stranger',
'content' => '댓글 답니다',
]);
$response = $this->actingAs($this->stranger, 'sanctum')
->getJson($this->commentedActivityUrl());
$response->assertStatus(200);
$titles = array_column($response->json('data.data') ?? [], 'title');
// 행은 내 활동 기록이므로 남는다 — 가리는 것은 남의 본문뿐이다.
$this->assertContains('남의 비밀글', $titles, '내가 댓글 단 글은 활동 목록에 남아야 합니다');
$this->assertStringNotContainsString(
'남의 비밀 본문',
$response->getContent(),
'타인이 쓴 비밀글의 본문이 댓글 활동 목록으로 새면 안 됩니다'
);
}
/**
* (과차단 회귀) 자기 비밀글에 자기가 댓글을 달았으면 본문이 그대로 보인다.
*
* 글 단위 판정을 "비밀글이면 무조건 마스킹" 으로 조이면 자기 글까지 가려져 기능이 깎인다.
*
* @scenario viewer=owner, activity_type=commented
*
* @effects commented_activity_shows_own_secret_content_to_owner
*/
public function test_commented_activity_shows_own_secret_post_content_to_owner(): void
{
$postId = $this->createAuthorPost([
'title' => '내 비밀글',
'is_secret' => true,
'content' => '내 비밀 본문',
]);
$this->createTestComment($postId, [
'user_id' => $this->author->id,
'author_name' => 'author',
'content' => '자문자답',
]);
$response = $this->actingAs($this->author, 'sanctum')
->getJson($this->commentedActivityUrl());
$response->assertStatus(200);
$titles = array_column($response->json('data.data') ?? [], 'title');
$this->assertContains('내 비밀글', $titles);
$this->assertStringContainsString(
'내 비밀 본문',
$response->getContent(),
'본인이 쓴 비밀글이면 댓글 활동 목록에서도 본문이 보여야 합니다'
);
}
}
@@ -98,11 +98,14 @@ class UserPublicPostsApiTest extends BoardTestCase
}
/**
* 비밀글도 사용자 프로필 게시글 목록에 포함된다 (is_secret 배지로 구분).
* 타인 프로필에서도 비밀글은 목록에 나오되 본문은 나가지 않는다.
*
* getUserPublicPosts는 모든 게시글을 표시하며 비밀글/블라인드는 배지로 구분합니다.
* 이 목록은 본문 일부(content_plain)를 함께 싣는데 라우트가 optional.sanctum 이라
* **미인증 요청에 타인의 비밀글 본문이 그대로 나갔다**(KVE-2026-1914 형제).
* 행·제목은 게시판 목록에서 이미 같은 수준으로 보이므로(PostResource 의 목록 규칙)
* 행은 남기고 본문만 비운다 — UI 의 비밀글 배지도 그대로 동작한다.
*/
public function test_secret_posts_are_included_with_badge(): void
public function test_secret_posts_are_listed_without_content_for_other_viewers(): void
{
// Given: 공개글과 비밀글을 작성
$this->createPost($this->board->slug, [
@@ -122,19 +125,27 @@ class UserPublicPostsApiTest extends BoardTestCase
// When: 사용자 게시글을 조회하면
$response = $this->getJson("/api/modules/sirsoft-board/users/{$this->targetUser->uuid}/posts");
// Then: 모든 게시글이 반환되며 is_secret 배지로 구분
// Then: 두 건 모두 나오되 비밀글의 본문만 비어 있다
$response->assertOk();
$data = $response->json('data.data');
$this->assertCount(2, $data);
$secret = collect($data)->firstWhere('is_secret', true);
$public = collect($data)->firstWhere('is_secret', false);
$this->assertNotNull($secret, '비밀글도 목록에는 나와야 합니다(배지로 구분)');
$this->assertSame('', $secret['content_plain'], '비밀글 본문은 나가면 안 됩니다');
$this->assertNotSame('', $public['content_plain'], '공개글 본문은 그대로여야 합니다');
}
/**
* 블라인드 처리된 게시글도 사용자 프로필 게시글 목록에 포함된다 (status 배지로 구분).
* 타인 프로필에서도 블라인드 게시글은 목록에 나오되 본문은 나가지 않는다.
*
* getUserPublicPosts는 모든 게시글을 표시하며 비밀글/블라인드는 배지로 구분합니다.
* 블라인드 글의 본문은 이 모듈의 다른 목록에서도 비워진다
* (PostResource::getMaskedContentPreviewForList) — 같은 규칙을 적용한다.
*/
public function test_blinded_posts_are_included_with_badge(): void
public function test_blinded_posts_are_listed_without_content_for_other_viewers(): void
{
// Given: 공개된 게시글과 블라인드 처리된 게시글
$this->createPost($this->board->slug, [
@@ -152,11 +163,15 @@ class UserPublicPostsApiTest extends BoardTestCase
// When: 사용자 게시글을 조회하면
$response = $this->getJson("/api/modules/sirsoft-board/users/{$this->targetUser->uuid}/posts");
// Then: 모든 게시글이 반환되며 status 배지로 구분
// Then: 두 건 모두 나오되 블라인드 글의 본문만 비어 있다
$response->assertOk();
$data = $response->json('data.data');
$this->assertCount(2, $data);
$blinded = collect($data)->firstWhere('status', 'blinded');
$this->assertNotNull($blinded, '블라인드 글도 목록에는 나와야 합니다(배지로 구분)');
$this->assertSame('', $blinded['content_plain'], '블라인드 글 본문은 나가면 안 됩니다');
}
/**
@@ -13,11 +13,7 @@
*
* @scenario board-reports-search
* @axes field=all field=post_title field=board_name field=author_name field=reporter_name
* @effects search_keyword_propagated_to_url_query,
* search_field_propagated_to_url_query,
* search_input_value_retained_after_navigation,
* reset_clears_search_keyword,
* mobile_search_propagates_to_url_query
* 효과 요약(마커 아님 — 평문): search_keyword_propagated_to_url_query, search_field_propagated_to_url_query, search_input_value_retained_after_navigation, reset_clears_search_keyword, mobile_search_propagates_to_url_query.
*
* 활성화 절차: PlaywrightIssueToken 발급이 가능한 환경에서 test.describe.skip → test.describe.
*/
@@ -104,6 +100,35 @@ test.describe.skip('게시판 신고현황 — 검색 기능 동작 (#413-72)',
expect(url.searchParams.get('filters[0][value]')).toBeFalsy();
});
// @scenario field=reporter_name
// @effects search_field_propagated_to_url_query, search_keyword_propagated_to_url_query, search_input_value_retained_after_navigation
test('검색 필드(신고자명) 선택 + 검색어가 URL query 에 전달되고 재진입 시 복원된다', async ({
page,
settingsToken,
}) => {
await authenticatePage(page, settingsToken);
await page.goto(REPORTS_URL);
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
// 검색 필드 select → reporter_name (게시글 작성자가 아니라 신고한 사람 기준)
await page.locator('#search_field_select select, #search_field_select').first()
.selectOption('reporter_name');
await page.locator('#search_input input, #search_input').first().fill('김신고');
await page.locator('#search_button').click();
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const url = new URL(page.url());
expect(url.searchParams.get('filters[0][field]')).toBe('reporter_name');
expect(url.searchParams.get('filters[0][value]')).toBe('김신고');
// author_name 과 값 공간이 겹치므로, 선택한 필드가 그대로 유지되는지까지 확인한다
// (필드가 조용히 all/author_name 으로 되돌아가면 다른 행이 걸려 결과가 맞는 것처럼 보인다)
const fieldSelect = page.locator('#search_field_select select, #search_field_select').first();
await expect(fieldSelect).toHaveValue('reporter_name', { timeout: 5_000 });
const searchInput = page.locator('#search_input input, #search_input').first();
await expect(searchInput).toHaveValue('김신고', { timeout: 5_000 });
});
// @scenario field=post_title
// @effects mobile_search_propagates_to_url_query
test('모바일 뷰포트에서 검색어가 URL query 에 전달된다', async ({ page, settingsToken }) => {
@@ -4,6 +4,8 @@ namespace Modules\Sirsoft\Board\Tests\Unit\Listeners;
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Models\User;
use Illuminate\Http\Request;
use Modules\Sirsoft\Board\Listeners\EcommerceInquiryHookListener;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
@@ -146,6 +148,60 @@ class EcommerceInquiryHookListenerTest extends BoardTestCase
$this->assertStringContainsString('원본 문의 제목', $post->title);
}
/**
* createAndReturn: 저장되는 ip_address 는 호출 서비스가 payload 로 넘긴 값이어야 한다.
* 요청 경계인 ProductInquiryService 가 IP 를 주입하고 Listener 는 그것을 그대로 쓴다.
*
* 입력 경계는 viewer 축과 교차하지 않는 별개 관심사라 매니페스트 sub_flow
* (`listener_ip_boundary`)로 두고 여기서는 효과만 마킹한다 — 매니페스트 axes 에 없는
* 축을 @scenario 에 적으면 어떤 cross product 조합도 커버하지 못하는 죽은 마커가 된다.
*
* @effects listener_uses_service_provided_ip_not_request
*/
public function test_create_and_return_persists_ip_from_payload(): void
{
$result = $this->listener->createAndReturn(null, $this->board->slug, [
'title' => '문의',
'content' => '내용',
'ip_address' => '198.51.100.7',
]);
$post = Post::find($result['post_id']);
$this->assertSame('198.51.100.7', $post->ip_address, 'Listener 는 payload 의 ip_address 를 그대로 저장해야 합니다');
}
/**
* createAndReturn: payload 에 ip_address 가 없으면 '0.0.0.0' 폴백을 쓰고 request()->ip() 로
* 되돌아가지 않는다(입력 우회 방지 경계 — 정정2 회귀 가드).
*
* request IP 를 **비-0.0.0.0** 으로 세팅한 상태에서 폴백값(0.0.0.0)이 나와야 한다. Listener 가
* request()->ip() 를 재도입하면 이 테스트가 request IP('203.0.113.99')를 잡아 fail 한다.
* (테스트 기본 request IP 0.0.0.0 으로는 재도입해도 폴백과 같아 silent green — 그래서 비-0 IP 사용)
*
* 축이 아닌 sub_flow (`listener_ip_boundary`) 소속이라 효과만 마킹한다.
*
* @effects listener_does_not_reach_into_request_for_ip
*/
public function test_create_and_return_does_not_fall_back_to_request_ip(): void
{
$request = Request::create('/'.$this->board->slug, 'POST', server: ['REMOTE_ADDR' => '203.0.113.99']);
$this->app->instance('request', $request);
$this->assertSame('203.0.113.99', $request->ip(), '테스트 전제: request IP 가 비-0.0.0.0 이어야 재도입을 잡는다');
$result = $this->listener->createAndReturn(null, $this->board->slug, [
'title' => '문의',
'content' => '내용',
// ip_address 의도적 누락
]);
$post = Post::find($result['post_id']);
$this->assertSame(
'0.0.0.0',
$post->ip_address,
'ip_address 미제공 시 폴백(0.0.0.0)이어야 하며 request()->ip() 로 되돌아가면 안 됩니다'
);
}
/**
* createAndReturn: 존재하지 않는 slug → 예외 발생하지 않고 null 반환
*/
@@ -214,6 +270,68 @@ class EcommerceInquiryHookListenerTest extends BoardTestCase
$this->assertSame($postId, $result[0]['id']);
}
/**
* getByIds: 비밀글은 비열람자에게 content/title/reply/attachments 가 마스킹된다 (KVE-2026-1914 A-1)
*
* @scenario layer=hook, viewer=non_viewer
*
* @effects hook_masks_secret_post_for_non_viewer, hook_emits_authoritative_can_view_secret_flag
*/
public function test_get_by_ids_masks_secret_post_for_non_viewer(): void
{
$owner = User::factory()->create();
$postId = $this->createTestPost([
'title' => '비밀 문의 제목',
'content' => '비밀 문의 내용',
'is_secret' => true,
'user_id' => $owner->id,
'author_name' => 'owner',
]);
// 비인증(비열람자) 컨텍스트
$result = $this->listener->getByIds([], ['ids' => [$postId], 'slug' => $this->board->slug]);
$this->assertCount(1, $result);
$item = $result[0];
$this->assertNull($item['content'], '비밀글 content 는 비열람자에게 null 이어야 합니다');
$this->assertNotSame('비밀 문의 제목', $item['title'], '비밀글 title 은 플레이스홀더로 대체되어야 합니다');
$this->assertNull($item['reply'], '비밀글 reply 는 비열람자에게 null 이어야 합니다');
$this->assertSame([], $item['attachments'], '비밀글 attachments 는 비열람자에게 빈 배열이어야 합니다');
$this->assertTrue($item['is_secret']);
// 소비 서비스의 이중 방어(A-2)를 위해 서버 열람 판정을 함께 실어 보낸다
$this->assertFalse($item['can_view_secret'], '비열람자에게 can_view_secret 은 false 여야 합니다');
}
/**
* getByIds: 작성자 본인에게는 비밀글 원문이 그대로 노출된다 (회귀 방지)
*
* @scenario layer=hook, viewer=owner
*
* @effects hook_exposes_secret_post_to_owner
*/
public function test_get_by_ids_shows_secret_post_to_owner(): void
{
$owner = User::factory()->create();
$postId = $this->createTestPost([
'title' => '내 비밀 문의',
'content' => '내 비밀 내용',
'is_secret' => true,
'user_id' => $owner->id,
'author_name' => 'owner',
]);
$this->actingAs($owner, 'sanctum');
$result = $this->listener->getByIds([], ['ids' => [$postId], 'slug' => $this->board->slug]);
$this->assertSame('내 비밀 내용', $result[0]['content']);
$this->assertSame('내 비밀 문의', $result[0]['title']);
$this->assertTrue($result[0]['can_view_secret'], '작성자 본인에게 can_view_secret 은 true 여야 합니다');
}
// 게시판 manager 의 비밀글 원문 열람은 HTTP 컨텍스트(라우트 slug)가 필요한
// PermissionMiddleware 경로라, SecretPostAttachmentAccessTest·SecretPostCommentAccessTest
// 에서 실제 요청으로 검증한다(여기서는 소유자/비열람자 마스킹만 단위 검증).
// ==========================================
// getBoardSettings
// ==========================================
@@ -6,6 +6,12 @@
## [1.1.1] - 2026-08-12
### Security
- 비밀 상품 문의의 내용이 작성자·관리자가 아닌 사람에게도 노출되던 문제를 막았습니다. 문의 목록은 게시글의 비밀 여부를 서버에서 확인해, 열람 권한이 없는 요청에는 내용·제목·답변·첨부를 가립니다. (목록의 '비밀글 숨김' 옵션과 무관하게 서버가 요청자 신원으로 노출 여부를 결정합니다.) (KISA 측에서 제보해주셨습니다 — KVE-2026-1914)
- 관리자가 숨긴 리뷰의 이미지가 주소만 알면 계속 조회되던 문제를 수정했습니다. 이제 숨김 처리된 리뷰의 이미지는 제공되지 않습니다. 리뷰가 삭제되어 상태를 확인할 수 없는 이미지도 함께 차단합니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-1914)
- 상품·주문·리뷰·브랜드·쿠폰·배송정책·추가배송비 관리에 담당 범위 제한을 적용했습니다. 이 권한들은 "본인이 등록한 것만" 처럼 범위를 좁혀 위임할 수 있는데, 그 제한이 실제로는 어느 관리 화면에서도 적용되지 않았습니다. 목록에서 여러 건을 한 번에 처리하는 일괄 기능뿐 아니라, 항목을 하나씩 수정·삭제하는 화면에서도 마찬가지였습니다. 이제 모든 경로에서 대상마다 범위를 확인하며, 일괄 기능은 범위 밖 대상이 하나라도 섞이면 요청 전체를 거부하고 아무것도 변경하지 않습니다. 범위 제한 없이 위임받은 관리자의 작업은 종전처럼 정상 동작합니다. (KVE-2026-1919)
### Added
- 리뷰 이미지 업로드에 파일 가공 필터 훅 제공 — 확장에서 상품·카테고리 이미지와 동일하게 리뷰 이미지도 업로드 시점에 변환(압축·리사이즈·포맷 변경)할 수 있습니다. (#96 @lyg-kaban 님께서 건의해주셨습니다.)
@@ -67,6 +73,7 @@
#### 기타
- 빌드 산출물이 존재하지 않는 소스맵 파일을 참조해 브라우저 개발자 도구 사용 시 불필요한 404 요청이 발생하던 문제를 수정했습니다.
- 추가배송비(도서산간) 템플릿 상세 응답의 편집 권한 표시를 배송정책 권한 기준으로 통일했습니다. 이전에는 상세 응답만 다른 권한(설정 관리)을 기준으로 삼아, 배송정책 관리 권한만 가진 관리자에게 편집 가능 여부가 실제 권한과 다르게 표시될 수 있었습니다.
#### 배송비 구간
@@ -283,12 +283,12 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: 삭제 결과 요약 (`data` 객체)._
_단건 응답: 삭제 결과 요약 (`BrandService::deleteBrand()` 가 반환한 배열 — Resource 로 감싸지 않는다)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| brand_id | integer | `2` | 삭제된 브랜드의 기본 키 |
| products_count | integer | `0` | 삭제 시점에 이 브랜드를 쓰던 상품 수 (연결 상품이 있으면 삭제가 거부되므로 언제나 0) |
| brand_id | integer | `1` | 삭제된 브랜드의 ID |
| products_count | integer | `0` | 삭제 시점의 연결 상품 수. **항상 `0`** 이다 — 연결 상품이 하나라도 있으면 삭제 자체가 차단되므로 성공 응답에서는 0 외의 값이 나올 수 없다 |
**응답 예시**
@@ -301,7 +301,7 @@ HTTP/1.1 200
"success": true,
"message": "브랜드가 삭제되었습니다.",
"data": {
"brand_id": 2,
"brand_id": 1,
"products_count": 0
}
}
@@ -312,9 +312,9 @@ HTTP/1.1 200
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.brands.delete`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 500 | Internal Server Error | 서버 내부 오류 — 도메인 규칙 위반이 아닌 예외(인프라 장애·코드 결함)는 4xx 로 뭉개지 않고 500 으로 구분한다 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.brands.delete`)이 없거나, 대상 브랜드가 요청자의 **스코프 밖**인 경우 (`auth.scope_denied`). 존재하지 않는 ID 도 스코프 판정에서 먼저 걸려 403 이 된다 |
| 400 | Bad Request | 연결된 상품이 있어 삭제가 차단된 경우(`exceptions.brand_has_products` — 상품 수 포함), 또는 삭제 처리 중 예외 발생 (`exceptions.operation_failed`) |
| 404 | Not Found | path 파라미터 형식이 라우트에 매칭되지 않는 경우 |
<!-- @generated:end -->
@@ -425,7 +425,6 @@ HTTP/1.1 200
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.brands.update`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
| 500 | Internal Server Error | 서버 내부 오류 — 도메인 규칙 위반이 아닌 예외(인프라 장애·코드 결함)는 4xx 로 뭉개지 않고 500 으로 구분한다 |
<!-- @generated:end -->
@@ -455,7 +454,25 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: `data` 객체의 필드 (`BrandResource`). 필드 구성은 이 문서의 **PUT /api/modules/sirsoft-ecommerce/admin/brands/{id} (브랜드 수정)** 응답 필드 표와 동일합니다._
_단건 응답: `data` 가 브랜드 하나 (`BrandResource`). 필드 구성은 목록 응답의 `data.data[]` 항목과 동일하되, 목록 전용 순번(`number`)은 없다._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `20` | 기본 키 (내부 식별자) |
| name | object | `{"ko":"ASUS","en":"ASUS"}` | 다국어 원본 이름 (로케일 키 → 값) |
| localized_name | string | `ASUS` | `name` 의 현재 로케일 해석 값 |
| slug | string | `asus` | URL 친화 식별자 |
| url | string | `asus` | SortableMenuItem 표시용 URL (slug 값을 그대로 노출) |
| website | string \| null | `https://www.asus.com` | 브랜드 공식 웹사이트 URL |
| sort_order | integer | `20` | 표시 정렬 순서 값 (작을수록 우선) |
| is_active | boolean | `true` | 사용 여부 |
| icon | string | `tag` | 아이콘 식별자 (Resource 가 고정값으로 부여) |
| created_at | string | `2026-07-30 23:35:46` | 생성 일시 |
| updated_at | string | `2026-07-30 23:35:46` | 최종 수정 일시 |
| creator | object \| array | `[]` | 생성자 정보 (`id`/`name`) — 관계가 로드된 경우에만 포함 |
| updater | object \| array | `[]` | 수정자 정보 (`id`/`name`) — 관계가 로드된 경우에만 포함 |
| products_count | integer | `1` | 이 브랜드에 속한 상품 수 (집계) |
| abilities | object | `{"can_create":true,"can_update":true,"can_delete":true}` | 현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 |
**응답 예시**
@@ -466,23 +483,25 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "브랜드 정보를 조회했습니다.",
"message": "브랜드를 조회했습니다.",
"data": {
"id": 1,
"id": 20,
"name": {
"ko": "API 문서 샘플 브랜드",
"en": "API Doc Sample Brand"
"ko": "ASUS",
"en": "ASUS"
},
"localized_name": "API 문서 샘플 브랜드",
"slug": "apidoc-sample-brand",
"url": "apidoc-sample-brand",
"localized_name": "ASUS",
"slug": "asus",
"url": "asus",
"website": "https://www.asus.com",
"sort_order": 0,
"sort_order": 20,
"is_active": true,
"icon": "tag",
"created_at": "2026-07-08 10:44:49",
"updated_at": "2026-07-08 15:00:16",
"products_count": 0,
"created_at": "2026-07-30 23:35:46",
"updated_at": "2026-07-30 23:35:46",
"creator": [],
"updater": [],
"products_count": 1,
"abilities": {
"can_create": true,
"can_update": true,
@@ -498,7 +517,7 @@ HTTP/1.1 200
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.brands.read`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `id` 의 브랜드가 없는 경우 (`messages.brands.not_found`) |
<!-- @generated:end -->
@@ -528,10 +547,21 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: `data` 객체의 필드 (`BrandResource`). 필드 구성은 이 문서의 **PUT /api/modules/sirsoft-ecommerce/admin/brands/{id} (브랜드 수정)** 응답 필드 표와 동일합니다._ `is_active` 가 반전된 상태로 반환됩니다.
_단건 응답: `data` 가 토글된 브랜드 (`BrandResource`). 필드 구성은 상세 조회와 동일하며, 실질적으로 달라지는 것은 `is_active` 와 `updated_at` 이다._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| id | integer | `20` | 브랜드 기본키 |
| is_active | boolean | `false` | **토글 후** 의 사용 여부. 화면은 이 값으로 스위치 상태를 갱신한다 |
| updated_at | string | `2026-08-16 01:30:00` | 토글 시각으로 갱신된 수정 일시 |
| (그 외) | — | — | `name`·`localized_name`·`slug`·`url`·`website`·`sort_order`·`icon`·`created_at`·`creator`·`updater`·`products_count`·`abilities` — 상세 조회 응답과 동일 |
`message` 는 활성/비활성 구분 없이 `messages.brands.status_changed` 하나다. 현재 상태는 `data.is_active` 로 판정한다.
**응답 예시**
비활성으로 토글된 경우:
```http
HTTP/1.1 200
```
@@ -541,21 +571,23 @@ HTTP/1.1 200
"success": true,
"message": "브랜드 상태가 변경되었습니다.",
"data": {
"id": 1,
"id": 20,
"name": {
"ko": "API 문서 샘플 브랜드",
"en": "API Doc Sample Brand"
"ko": "ASUS",
"en": "ASUS"
},
"localized_name": "API 문서 샘플 브랜드",
"slug": "apidoc-sample-brand",
"url": "apidoc-sample-brand",
"localized_name": "ASUS",
"slug": "asus",
"url": "asus",
"website": "https://www.asus.com",
"sort_order": 0,
"is_active": true,
"sort_order": 20,
"is_active": false,
"icon": "tag",
"created_at": "2026-07-08 10:44:49",
"updated_at": "2026-07-08 15:00:16",
"products_count": 0,
"created_at": "2026-07-30 23:35:46",
"updated_at": "2026-08-16 01:30:00",
"creator": [],
"updater": [],
"products_count": 1,
"abilities": {
"can_create": true,
"can_update": true,
@@ -571,8 +603,8 @@ HTTP/1.1 200
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.brands.update`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 500 | Internal Server Error | 서버 내부 오류 — 도메인 규칙 위반이 아닌 예외(인프라 장애·코드 결함)는 4xx 로 뭉개지 않고 500 으로 구분한다 |
| 400 | Bad Request | 해당 `id` 의 브랜드가 없거나 토글 처리 중 예외 발생 (`exceptions.operation_failed`) |
| 404 | Not Found | path 파라미터 형식이 라우트에 매칭되지 않는 경우 |
<!-- @generated:end -->
@@ -637,7 +637,65 @@ _목록 응답: `data.data[]` 배열 항목의 필드. 페이지네이션 없는
**응답 예시**
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "연결 거래를 조회했습니다.",
"data": {
"data": [
{
"number": 1,
"id": 531,
"user_id": 166,
"currency": "KRW",
"type": "order_use",
"type_label": "주문 사용",
"admin_badge_group": "blue",
"user_display_category": "use",
"amount": -500,
"amount_formatted": "-500원",
"remaining_amount": 0,
"remaining_amount_formatted": "0원",
"balance_after": 500,
"order_id": 436,
"order_option_id": 824,
"order_cancel_id": null,
"source_transaction_id": 528,
"granted_by": null,
"description": "주문 마일리지 사용",
"memo": null,
"expires_at": null,
"expires_at_formatted": null,
"expires_at_date": null,
"expired_at": null,
"expired_at_formatted": null,
"created_at": "2026-07-07T05:47:31+00:00",
"created_at_formatted": "2026-07-07 14:47:31",
"created_at_date": "2026-07-07",
"is_earning": false,
"can_edit_expiry": false,
"expired_amount": 0,
"expired_amount_formatted": "0원",
"expiry_state": "active",
"abilities": {
"can_manage": true,
"can_edit": false
}
}
],
"abilities": {
"can_manage": true
},
"currencies": []
}
}
```
> 연결 거래가 없으면 `data.data` 가 빈 배열이다 (404 가 아니다 — 404 는 `{id}` 거래 자체가 없을 때뿐이다). 페이지네이션이 없는 컬렉션이라 `data.pagination` 키는 존재하지 않으며, `data.currencies` 는 이 엔드포인트가 주입하지 않아 항상 `[]` 다.
**에러 응답**
@@ -645,7 +703,7 @@ _목록 응답: `data.data[]` 배열 항목의 필드. 페이지네이션 없는
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.mileage.read`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | `{id}` 에 해당하는 마일리지 거래가 없는 경우 |
<!-- @generated:end -->
@@ -3418,7 +3418,7 @@ HTTP/1.1 200
| product | path | string | 예 | — | 대상 product의 식별자 |
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
| per_page | query | integer | 아니오 | min 1, max 100 | 페이지당 항목 수 |
| exclude_secret | query | boolean | 아니오 | — | 비밀글 제외 여부 (기본 `false` — 포함). `true` 면 비밀 문의를 목록에서 제외합니다. 쿼리 문자열 `"true"`/`"false"` 도 해석되며, 해석할 수 없는 값은 그대로 검증되어 422 가 됩니다 |
| exclude_secret | query | boolean | 아니오 | — | 비밀글 제외 여부 (기본 `false` — 포함). `true` 면 비밀 문의를 목록에서 제외합니다. 쿼리 문자열 `"true"`/`"false"` 도 해석되며, 해석할 수 없는 값은 그대로 검증되어 422 가 됩니다. **보안 경계가 아니라 단순 표시 필터입니다** — 비밀 문의의 노출/마스킹은 이 값과 무관하게 서버가 요청자 신원으로 결정합니다 |
**요청 예시**
@@ -3521,7 +3521,7 @@ HTTP/1.1 200
<!-- @generated:end -->
**설명** 상품의 1:1 문의 목록을 조회합니다. `optional.sanctum`(회원/비회원 모두 접근) + `sirsoft-ecommerce.user-products.read` 권한이 적용되며, `ProductInquiryService::getProductInquiries()`가 게시판 모듈과 연동된 문의 글을 페이지네이션해 `items`와 `board_settings`(비밀글 모드·카테고리 등) 메타를 반환합니다. `per_page`/`page`/`exclude_secret` 쿼리로 조회 범위를 조정하며, 비밀 문의는 설정과 열람 권한에 따라 마스킹됩니다. 상품 상세의 문의 탭에 사용됩니다.
**설명** 상품의 1:1 문의 목록을 조회합니다. `optional.sanctum`(회원/비회원 모두 접근) + `sirsoft-ecommerce.user-products.read` 권한이 적용되며, `ProductInquiryService::getProductInquiries()`가 게시판 모듈과 연동된 문의 글을 페이지네이션해 `items`와 `board_settings`(비밀글 모드·카테고리 등) 메타를 반환합니다. `per_page`/`page`/`exclude_secret` 쿼리로 조회 범위를 조정합니다. 비밀 문의는 요청자 신원(작성자 본인·게시판 비밀글 열람 권한)에 따라 서버가 마스킹하며, 열람 권한이 없으면 `title`은 "비밀글" 플레이스홀더로 치환되고 `content`·`reply`는 `null`, `attachments`는 빈 배열로 내려갑니다(`is_secret`·작성자·답변 여부 등 메타는 유지). 이 마스킹은 게시판 모듈이 실어 보내는 권위 플래그(`can_view_secret`)를 신뢰하며, 플래그가 없으면 fail-closed 로 마스킹합니다. `exclude_secret` 쿼리는 표시 필터일 뿐 이 판정에 관여하지 않습니다. 상품 상세의 문의 탭에 사용됩니다.
### POST /api/modules/sirsoft-ecommerce/products/{product}/inquiries
@@ -73,10 +73,12 @@ Content-Disposition: attachment; filename="review.jpg"
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 404 | Not Found | 해시에 해당하는 리뷰 이미지가 없거나(`findByHash()` → null), 레코드는 있으나 스토리지에 실제 파일이 없는 경우 (`messages.reviews.image_not_found`) |
| 404 | Not Found | 해시에 해당하는 리뷰 이미지가 없거나(`findByHash()` → null), 레코드는 있으나 스토리지에 실제 파일이 없는 경우, **또는 이미지가 속한 리뷰가 노출(VISIBLE) 상태가 아닌 경우**(숨김·블라인드·대기 리뷰의 이미지는 존재를 감추기 위해 동일하게 404) (`messages.reviews.image_not_found`) |
<!-- @generated:end -->
**설명** 리뷰에 첨부된 이미지를 해시(12자) 기반으로 공개 서빙합니다. 인증이 필요 없으며, `ReviewImageController@download` 가 `ProductReviewImageService::download()` 로 해시에 해당하는 이미지를 찾아 스트림(`StreamedResponse`)으로 반환합니다. 해시에 해당하는 이미지가 없으면 404 를 반환합니다. `<img src>` 등에서 리뷰 이미지 원본을 표시할 때 사용하며, 실제 파일 경로를 노출하지 않고 해시로만 접근하게 합니다.
**설명** 리뷰에 첨부된 이미지를 해시(12자) 기반으로 서빙합니다. `ReviewImageController@download` 가 `ProductReviewImageService::download()` 로 해시에 해당하는 이미지를 찾아 스트림(`StreamedResponse`)으로 반환합니다. `<img src>` 등에서 리뷰 이미지 원본을 표시할 때 사용하며, 실제 파일 경로를 노출하지 않고 해시로만 접근하게 합니다.
이미지 서빙은 **부모 리뷰가 노출(VISIBLE) 상태일 때로 한정**됩니다(KVE-2026-1914). 숨김·블라인드·대기 상태 리뷰의 이미지는 해시가 유효해도 서빙되지 않고 404 를 반환합니다 — 본문이 감춰진 리뷰의 이미지가 해시만으로 노출되는 것을 막고, 존재 자체를 드러내지 않기 위해 "이미지 없음"과 동일한 404 로 응답합니다. 노출 상태 리뷰의 이미지는 별도 인증 없이 공개 접근할 수 있습니다.
@@ -259,11 +259,11 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: `data` 객체의 필드._
_단건 응답: 삭제 성공 플래그만 반환한다 (Resource 로 감싸지 않는다)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| deleted | boolean | `true` | 삭제 완료 여부 (컨트롤러가 고정값 `true` 로 내려준다) |
| deleted | boolean | `true` | 삭제 성공 여부. 성공 응답에서는 항상 `true` 이며, 실패는 `500` 으로 갈린다 |
**응답 예시**
@@ -281,13 +281,16 @@ HTTP/1.1 200
}
```
> 삭제 전 컨트롤러가 `images` 관계를 로드한다 — 첨부 이미지 파일까지 함께 정리하기 위해서다. DB CASCADE 에 맡기지 않고 Service 가 명시적으로 삭제하므로 훅 발화와 파일 정리가 보장된다.
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.reviews.delete`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `review` 의 리뷰가 없는 경우 (라우트 모델 바인딩이 해석에 실패) |
| 500 | Internal Server Error | 삭제 처리 중 예외 발생 (`messages.reviews.delete_failed`) |
<!-- @generated:end -->
@@ -362,55 +365,48 @@ HTTP/1.1 200
"success": true,
"message": "리뷰를 조회했습니다.",
"data": {
"id": 12,
"product_id": 3,
"order_option_id": 45,
"user_id": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"id": 99,
"product_id": 320,
"order_option_id": 859,
"user_id": "a231747f-e82e-4cf2-9ae1-a261849dce40",
"user": {
"uuid": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"name": "실측 예시값",
"email": "실측 예시값"
"uuid": "a231747f-e82e-4cf2-9ae1-a261849dce40",
"name": "API 문서 샘플 사용자",
"email": "apidoc-sample-user@example.com"
},
"product": {
"id": 3,
"product_code": "실측 예시값",
"name": "실측 예시값",
"thumbnail_url": "실측 예시값"
"id": 320,
"name": "API 문서 샘플 상품",
"thumbnail_url": null
},
"option_snapshot": {
"option_name": "실측 예시값"
},
"option_snapshot_label": "실측 예시값",
"option_snapshot": "{\"id\":104,\"option_code\":\"FWACBAVCBKCD\"}",
"option_snapshot_label": "",
"rating": 5,
"content": "실측 예시값",
"content": "Molestiae repellendus accusantium omnis.",
"content_mode": "text",
"status": "visible",
"status_label": "노출",
"status_badge_color": "green",
"status_label": "전시중",
"status_badge_color": "blue",
"images": [],
"image_count": 0,
"orderOption": {
"id": 45,
"order_id": 4,
"order_number": "20260728-0111050215",
"id": 859,
"order_id": 455,
"order_number": "ORD-20260707-000123",
"quantity": 1,
"created_at": "2026-08-05 09:46:56"
"ordered_at": "2026-07-07 14:40:00"
},
"has_reply": true,
"has_reply_label": "답변완료",
"has_reply_badge_color": "green",
"reply_content": "실측 예시값",
"has_reply": false,
"has_reply_label": "미답변",
"has_reply_badge_color": "gray",
"reply_content": null,
"reply_content_mode": "text",
"reply_admin_uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"reply_admin": {
"uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"name": "실측 예시값",
"email": "실측 예시값"
},
"replied_at": "2026-08-05 09:46:56",
"reply_updated_at": "2026-08-05 09:46:56",
"created_at": "2026-08-05 09:46:56",
"updated_at": "2026-08-05 09:46:56",
"reply_admin_uuid": null,
"reply_admin": null,
"replied_at": null,
"reply_updated_at": null,
"created_at": "2026-07-07 14:47:31",
"updated_at": "2026-07-07 14:47:31",
"abilities": {
"can_update": true,
"can_delete": true
@@ -425,7 +421,8 @@ HTTP/1.1 200
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.reviews.read`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `review` 의 리뷰가 없는 경우 (라우트 모델 바인딩이 해석에 실패) |
| 500 | Internal Server Error | 조회 중 예외 발생 (`messages.reviews.fetch_failed`) |
<!-- @generated:end -->
@@ -492,57 +489,34 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "답변이 삭제되었습니다.",
"message": "판매자 답변이 삭제되었습니다.",
"data": {
"id": 12,
"product_id": 3,
"order_option_id": 45,
"user_id": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"id": 1,
"product_id": 1,
"order_option_id": 1,
"user_id": "a234c2b1-cde8-437f-b28b-23323be2b98d",
"user": {
"uuid": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"name": "실측 예시값",
"email": "실측 예시값"
"uuid": "a234c2b1-cde8-437f-b28b-23323be2b98d",
"name": "API 문서 샘플 사용자",
"email": "apidoc-sample-user@example.com"
},
"product": {
"id": 3,
"product_code": "실측 예시값",
"name": "실측 예시값",
"thumbnail_url": "실측 예시값"
},
"option_snapshot": {
"option_name": "실측 예시값"
},
"option_snapshot_label": "실측 예시값",
"option_snapshot": "{\"id\":104,\"option_code\":\"FWACBAVCBKCD\"}",
"option_snapshot_label": "",
"rating": 5,
"content": "실측 예시값",
"content": "Alias quas iusto dolorem eum eveniet.",
"content_mode": "text",
"status": "visible",
"status_label": "노출",
"status_badge_color": "green",
"images": [],
"image_count": 0,
"orderOption": {
"id": 45,
"order_id": 4,
"order_number": "20260728-0111050215",
"quantity": 1,
"created_at": "2026-08-05 09:46:56"
},
"has_reply": true,
"has_reply_label": "답변완료",
"has_reply_badge_color": "green",
"reply_content": "실측 예시값",
"status_label": "전시중",
"status_badge_color": "blue",
"has_reply": false,
"has_reply_label": "미답변",
"has_reply_badge_color": "gray",
"reply_content": null,
"reply_content_mode": "text",
"reply_admin_uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"reply_admin": {
"uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"name": "실측 예시값",
"email": "실측 예시값"
},
"replied_at": "2026-08-05 09:46:56",
"reply_updated_at": "2026-08-05 09:46:56",
"created_at": "2026-08-05 09:46:56",
"updated_at": "2026-08-05 09:46:56",
"replied_at": null,
"reply_updated_at": null,
"created_at": "2026-07-08 10:44:49",
"updated_at": "2026-08-16 01:30:00",
"abilities": {
"can_update": true,
"can_delete": true
@@ -551,13 +525,16 @@ HTTP/1.1 200
}
```
> 답변이 지워진 결과가 응답에 그대로 반영된다 — `has_reply` 는 `false`, `reply_content`·`replied_at`·`reply_updated_at` 은 `null` 로 비워진다. 리뷰 본문(`content`·`rating`·`status`)은 그대로 유지된다.
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.reviews.update`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 404 | Not Found | 해당 `review` 의 리뷰가 없는 경우 (라우트 모델 바인딩이 해석에 실패) |
| 500 | Internal Server Error | 답변 삭제 처리 중 예외 발생 (`messages.reviews.reply_delete_failed`) |
<!-- @generated:end -->
@@ -634,57 +611,34 @@ HTTP/1.1 200
```json
{
"success": true,
"message": "답변이 저장되었습니다.",
"message": "판매자 답변이 저장되었습니다.",
"data": {
"id": 12,
"product_id": 3,
"order_option_id": 45,
"user_id": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"id": 1,
"product_id": 1,
"order_option_id": 1,
"user_id": "a234c2b1-cde8-437f-b28b-23323be2b98d",
"user": {
"uuid": "a26219fc-94a0-4f63-9404-04c2a6ac99e4",
"name": "실측 예시값",
"email": "실측 예시값"
"uuid": "a234c2b1-cde8-437f-b28b-23323be2b98d",
"name": "API 문서 샘플 사용자",
"email": "apidoc-sample-user@example.com"
},
"product": {
"id": 3,
"product_code": "실측 예시값",
"name": "실측 예시값",
"thumbnail_url": "실측 예시값"
},
"option_snapshot": {
"option_name": "실측 예시값"
},
"option_snapshot_label": "실측 예시값",
"option_snapshot": "{\"id\":104,\"option_code\":\"FWACBAVCBKCD\"}",
"option_snapshot_label": "",
"rating": 5,
"content": "실측 예시값",
"content": "Alias quas iusto dolorem eum eveniet.",
"content_mode": "text",
"status": "visible",
"status_label": "노출",
"status_badge_color": "green",
"images": [],
"image_count": 0,
"orderOption": {
"id": 45,
"order_id": 4,
"order_number": "20260728-0111050215",
"quantity": 1,
"created_at": "2026-08-05 09:46:56"
},
"status_label": "전시중",
"status_badge_color": "blue",
"has_reply": true,
"has_reply_label": "답변완료",
"has_reply_badge_color": "green",
"reply_content": "실측 예시값",
"reply_content": "소중한 후기 감사합니다. 앞으로도 좋은 상품으로 보답하겠습니다.",
"reply_content_mode": "text",
"reply_admin_uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"reply_admin": {
"uuid": "6d1f0d0e-2a1b-4c3d-8e9f-0a1b2c3d4e5f",
"name": "실측 예시값",
"email": "실측 예시값"
},
"replied_at": "2026-08-05 09:46:56",
"reply_updated_at": "2026-08-05 09:46:56",
"created_at": "2026-08-05 09:46:56",
"updated_at": "2026-08-05 09:46:56",
"replied_at": "2026-08-16 01:30:00",
"reply_updated_at": "2026-08-16 01:30:00",
"created_at": "2026-07-08 10:44:49",
"updated_at": "2026-08-16 01:30:00",
"abilities": {
"can_update": true,
"can_delete": true
@@ -693,14 +647,17 @@ HTTP/1.1 200
}
```
> 답변 저장 결과가 응답에 반영된다 — `has_reply` 는 `true`, `has_reply_badge_color` 는 `green` 으로 바뀌고 `replied_at`·`reply_updated_at` 이 채워진다. 이미 답변이 있던 리뷰를 다시 호출하면 내용이 **갱신**되며(중복 답변이 생기지 않는다) `reply_updated_at` 만 새로 갱신된다. 답변 작성자는 요청한 관리자(`Auth::id()`)로 기록된다.
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.reviews.update`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
| 404 | Not Found | 해당 `review` 의 리뷰가 없는 경우 (라우트 모델 바인딩이 해석에 실패) |
| 422 | Unprocessable Entity | `reply_content` 가 비었거나 1~2000자 범위를 벗어난 경우, `reply_content_mode` 가 `text`/`html` 이 아닌 경우 |
| 500 | Internal Server Error | 답변 저장 중 예외 발생 (`messages.reviews.reply_save_failed`) |
<!-- @generated:end -->
@@ -937,12 +894,12 @@ HTTP/1.1 201
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.user-reviews.write`)이 없는 경우 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) 또는 작성 자격 미충족 시 `ReviewNotWritableException` 이 발생하고, 그 사유 식별자(`order_option_not_found` / `not_own_order` / `not_confirmed` / `deadline_passed` / `already_written`)에 대응하는 다국어 키로 해석된 문구가 `message` 에 담긴다 |
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) 또는 작성 자격 미충족 시 `ReviewNotWritableException`(RuntimeException) 이 발생해 사유 코드가 담긴 메시지로 응답 (`order_option_not_found` / `not_own_order` / `not_confirmed` / `deadline_passed` / `already_written`) |
| 500 | Internal Server Error | 리뷰 생성 중 예외 발생 (`messages.reviews.create_failed` — "리뷰 작성에 실패했습니다.") |
<!-- @generated:end -->
**설명** 로그인 회원이 구매한 상품에 리뷰를 작성합니다. `sirsoft-ecommerce.user-reviews.write` 권한이 필요하며, `ProductReviewService::createReview()` 가 로그인 사용자(`Auth::id()`)를 작성자로 하여 `product_id`·`order_option_id`·별점(1~5)·내용(10~2000자)으로 리뷰를 생성하고 201 로 반환합니다. 본인 주문이 아니거나 이미 작성했거나 작성 조건을 만족하지 못하면 서비스가 `ReviewNotWritableException` 을 던지고, 컨트롤러가 그 사유에 대응하는 다국어 키로 422 응답을 만듭니다. 마이페이지 리뷰 작성 폼에서 사용합니다.
**설명** 로그인 회원이 구매한 상품에 리뷰를 작성합니다. `sirsoft-ecommerce.user-reviews.write` 권한이 필요하며, `ProductReviewService::createReview()` 가 로그인 사용자(`Auth::id()`)를 작성자로 하여 `product_id`·`order_option_id`·별점(1~5)·내용(10~2000자)으로 리뷰를 생성하고 201 로 반환합니다. 본인 주문이 아니거나 이미 작성했거나 작성 조건을 만족하지 못하면 서비스가 `RuntimeException` 을 던져 422 로 응답합니다. 마이페이지 리뷰 작성 폼에서 사용합니다.
### GET /api/modules/sirsoft-ecommerce/user/reviews/can-write/{orderOptionId}
@@ -968,19 +925,44 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: `data` 객체의 필드._
_단건 응답: 작성 자격 판정 결과 (`ProductReviewService::canWrite()` 가 반환한 배열 — Resource 로 감싸지 않는다)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| can_write | boolean | `false` | 이 주문 옵션에 리뷰를 작성할 수 있는지 |
| reason | string\|null | `"already_written"` | 작성 불가 사유 식별자. `order_option_not_found` / `not_own_order` / `not_confirmed` / `deadline_passed` / `already_written` 중 하나이며, 작성 가능하면 `null` |
| can_write | boolean | `true` | 이 주문 옵션에 리뷰를 쓸 수 있는지. 화면은 이 값으로 작성 버튼 노출을 결정한다 |
| reason | string \| null | `null` | 쓸 수 없는 사유 키. `can_write` 가 `true` 면 `null` |
`reason` 이 가질 수 있는 값:
| 값 | 의미 |
| --- | --- |
| `order_option_not_found` | 해당 주문 옵션이 존재하지 않음 |
| `not_own_order` | 본인 주문이 아님 |
| `not_confirmed` | 구매확정(`CONFIRMED`) 상태가 아님 |
| `deadline_passed` | 작성 가능 기간이 지남 (판정 규칙은 `ReviewWritePolicy` 단일 SSoT) |
| `already_written` | 이 주문 옵션으로 이미 리뷰를 작성함 |
**응답 예시**
작성 가능한 경우:
```http
HTTP/1.1 200
```
```json
{
"success": true,
"message": "리뷰 작성 가능 여부를 확인했습니다.",
"data": {
"can_write": true,
"reason": null
}
}
```
작성 불가한 경우 (이미 작성함):
```json
{
"success": true,
@@ -992,12 +974,14 @@ HTTP/1.1 200
}
```
> 작성 불가는 **에러가 아니라 정상 응답**이다. 존재하지 않는 주문 옵션이나 남의 주문도 `404`/`403` 이 아니라 `200` + `can_write: false` 로 응답하므로, 이 엔드포인트로 주문 존재 여부를 탐색할 수 없다.
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 500 | Internal Server Error | 판정 중 예외 발생 (`messages.reviews.can_write_check_failed`) |
<!-- @generated:end -->
@@ -1027,11 +1011,11 @@ Authorization: Bearer {YOUR_TOKEN}
**응답 필드** (`data` 내부)
_단건 응답: `data` 객체의 필드._
_단건 응답: 삭제 성공 플래그만 반환한다 (관리자 삭제 엔드포인트와 같은 형태)._
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| deleted | boolean | `true` | 삭제 완료 여부 (컨트롤러가 고정값 `true` 로 내려준다) |
| deleted | boolean | `true` | 삭제 성공 여부. 성공 응답에서는 항상 `true` |
**응답 예시**
@@ -1049,13 +1033,16 @@ HTTP/1.1 200
}
```
> 삭제 전 `images` 관계를 로드해 첨부 이미지 파일까지 함께 정리한다.
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.user-reviews.write`)이 없는 경우 |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.user-reviews.write`)이 없는 경우, 또는 **본인이 작성한 리뷰가 아닌 경우** (`messages.reviews.forbidden`) |
| 404 | Not Found | 해당 `review` 의 리뷰가 없는 경우 (라우트 모델 바인딩이 해석에 실패) |
| 500 | Internal Server Error | 삭제 처리 중 예외 발생 (`messages.reviews.delete_failed`) |
<!-- @generated:end -->
@@ -1151,12 +1138,12 @@ HTTP/1.1 201
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
| 403 | Forbidden | 요구 권한(`sirsoft-ecommerce.user-reviews.write`)이 없거나, 대상 리뷰가 로그인 사용자의 리뷰가 아닌 경우 (`messages.reviews.forbidden` — "권한이 없습니다.") |
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
| 422 | Unprocessable Entity | `image` 파일 누락·허용 형식/용량 위반 (`error.errors` 에 필드별 메시지) 또는 리뷰당 최대 첨부 개수 초과 시 `ReviewImageUploadLimitException` — 최대 개수는 리뷰 설정 `review_settings.max_images`(기본 5) 기준이며, 응답 문구는 그 상한을 파라미터로 받는 다국어 키로 만들어진다 |
| 422 | Unprocessable Entity | `image` 파일 누락·허용 형식/용량 위반 (`error.errors` 에 필드별 메시지) 또는 리뷰당 최대 첨부 개수 초과 시 `ReviewImageUploadLimitException`(RuntimeException) — 최대 개수는 리뷰 설정 `review_settings.max_images`(기본 5) 기준 |
| 500 | Internal Server Error | 업로드 처리 중 예외 발생 (`messages.reviews.image_upload_failed` — "리뷰 이미지 업로드에 실패했습니다.") |
<!-- @generated:end -->
**설명** 로그인 회원이 자신의 리뷰에 이미지를 첨부합니다. `sirsoft-ecommerce.user-reviews.write` 권한이 필요하며, 컨트롤러가 `review->user_id` 로 본인 소유를 확인(불일치 시 403)한 뒤 `ProductReviewImageService::upload()` 가 업로드된 이미지(최대 10MB)를 저장하고 201 로 이미지 리소스를 반환합니다. 리뷰당 첨부 개수 상한을 넘기면 서비스가 `ReviewImageUploadLimitException` 을 던지고, 컨트롤러가 상한값을 파라미터로 실은 다국어 키로 422 응답을 만듭니다. 포토 리뷰 작성 시 이미지를 추가할 때 사용합니다.
**설명** 로그인 회원이 자신의 리뷰에 이미지를 첨부합니다. `sirsoft-ecommerce.user-reviews.write` 권한이 필요하며, 컨트롤러가 `review->user_id` 로 본인 소유를 확인(불일치 시 403)한 뒤 `ProductReviewImageService::upload()` 가 업로드된 이미지(최대 10MB)를 저장하고 201 로 이미지 리소스를 반환합니다. 파일 형식/크기 등 제약 위반 시 서비스가 `RuntimeException` 을 던져 422 로 응답합니다. 포토 리뷰 작성 시 이미지를 추가할 때 사용합니다.
### DELETE /api/modules/sirsoft-ecommerce/user/reviews/{review}/images/{image}
@@ -9,8 +9,12 @@
* - 폼 바인딩 및 핸들러 검증
* - 다국어 키 검증
*
* @scenario extension_payment_method method_kind=extension × capability_declared=declared × capability=pg_locked
* @effects admin_shows_pg_locked_badge, admin_hides_pg_select_for_locked, admin_shows_pg_select_for_unlocked
* 축 요약(마커 아님 — 평문): extension_payment_method 의 method_kind=extension,
* capability_declared=declared, capability=pg_locked. 요약을 시나리오 축 마커로 적을 때
* 구분자를 `×` 로 쓰면 파서가 쉼표로만 축을 분리하므로 세 축이 한 문자열로 뭉쳐
* 실재하지 않는 조합 1건이 되어 어떤 칸도 커버하지 못한다 — 요약은 평문으로 둔다.
*
* 효과 요약(마커 아님 — 평문): admin_shows_pg_locked_badge, admin_hides_pg_select_for_locked, admin_shows_pg_select_for_unlocked.
*
* @vitest-environment node
*/
@@ -580,6 +584,8 @@ describe('결제수단 Sortable 리스트 구조 검증 (_payment_methods_list.j
&& n.props['data-testid'].includes(needle),
);
/** @effects admin_shows_pg_locked_badge */
/** @effects admin_shows_pg_locked_badge */
it('PG 고정 배지가 $method.pg_locked 조건으로 렌더된다', () => {
const badge = findByTestidExpr('pg-locked-badge-');
expect(badge).not.toBeNull();
@@ -590,6 +596,7 @@ describe('결제수단 Sortable 리스트 구조 검증 (_payment_methods_list.j
expect(badge.text).toContain('pg_provider');
});
/** @effects admin_hides_pg_select_for_locked, admin_shows_pg_select_for_unlocked */
it('PG 선택 셀렉트가 !pg_locked && needs_pg && 제공자>0 조건으로만 렌더된다', () => {
const select = findByTestidExpr('pg-select-');
expect(select).not.toBeNull();
@@ -664,6 +671,7 @@ describe('결제수단 모바일 카드 구조 검증 (_payment_methods_cards.js
expect(badge.if).toBe('{{$method.pg_locked}}');
});
/** @effects admin_hides_pg_select_for_locked, admin_shows_pg_select_for_unlocked */
it('PG 선택 셀렉트가 !pg_locked && needs_pg 조건으로만 렌더된다', () => {
const select = findByTestidExpr('pg-select-');
expect(select).not.toBeNull();
@@ -55,10 +55,15 @@ class ExtraFeeTemplateResource extends BaseApiResource
*/
protected function abilityMap(): array
{
// 추가배송비 템플릿의 write 라우트는 모두 shipping-policies.{create,update,delete} 로
// 게이팅된다(라우트 SSoT). 능력 플래그도 그 리소스의 권한과 일치해야 한다 — 형제
// ExtraFeeTemplateCollection 과 동일. 과거 settings.update(타 리소스)로 게이팅해
// shipping-policies 권한만 가진 액터가 상세 화면에서 편집 능력이 false 로 보이던
// 결함을 정정한다.
return [
'can_create' => 'sirsoft-ecommerce.settings.update',
'can_update' => 'sirsoft-ecommerce.settings.update',
'can_delete' => 'sirsoft-ecommerce.settings.update',
'can_create' => 'sirsoft-ecommerce.shipping-policies.create',
'can_update' => 'sirsoft-ecommerce.shipping-policies.update',
'can_delete' => 'sirsoft-ecommerce.shipping-policies.delete',
];
}
}
@@ -14,7 +14,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* ID로 템플릿 조회
*
* @param int $id 템플릿 ID
* @param int $id 템플릿 ID
* @return ExtraFeeTemplate|null
*/
public function find(int $id): ?ExtraFeeTemplate;
@@ -22,16 +22,24 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 우편번호로 템플릿 조회
*
* @param string $zipcode 우편번호
* @param string $zipcode 우편번호
* @return ExtraFeeTemplate|null
*/
public function findByZipcode(string $zipcode): ?ExtraFeeTemplate;
/**
* 여러 우편번호로 템플릿을 한 번에 조회
*
* @param array $zipcodes 우편번호 목록
* @return Collection
*/
public function findByZipcodes(array $zipcodes): Collection;
/**
* 필터링된 템플릿 목록 조회 (페이지네이션)
*
* @param array $filters 필터 조건
* @param int $perPage 페이지당 개수
* @param array $filters 필터 조건
* @param int $perPage 페이지당 개수
* @return LengthAwarePaginator
*/
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator;
@@ -39,7 +47,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 생성
*
* @param array $data 템플릿 데이터
* @param array $data 템플릿 데이터
* @return ExtraFeeTemplate
*/
public function create(array $data): ExtraFeeTemplate;
@@ -47,8 +55,8 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 수정
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param array $data 수정 데이터
* @param ExtraFeeTemplate $template 템플릿 모델
* @param array $data 수정 데이터
* @return ExtraFeeTemplate
*/
public function update(ExtraFeeTemplate $template, array $data): ExtraFeeTemplate;
@@ -56,7 +64,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 삭제
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param ExtraFeeTemplate $template 템플릿 모델
* @return bool
*/
public function delete(ExtraFeeTemplate $template): bool;
@@ -64,7 +72,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 사용여부 토글
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param ExtraFeeTemplate $template 템플릿 모델
* @return ExtraFeeTemplate
*/
public function toggleActive(ExtraFeeTemplate $template): ExtraFeeTemplate;
@@ -72,7 +80,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 일괄 삭제
*
* @param array $ids 템플릿 ID 배열
* @param array $ids 템플릿 ID 배열
* @return int 삭제된 개수
*/
public function bulkDelete(array $ids): int;
@@ -80,8 +88,8 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 템플릿 일괄 사용여부 변경
*
* @param array $ids 템플릿 ID 배열
* @param bool $isActive 사용여부
* @param array $ids 템플릿 ID 배열
* @param bool $isActive 사용여부
* @return int 변경된 개수
*/
public function bulkToggleActive(array $ids, bool $isActive): int;
@@ -103,7 +111,7 @@ interface ExtraFeeTemplateRepositoryInterface
/**
* 일괄 등록 (CSV 또는 엑셀 업로드용)
*
* @param array $items 템플릿 데이터 배열 [{zipcode, fee, region?, description?}]
* @param array $items 템플릿 데이터 배열 [{zipcode, fee, region?, description?}]
* @return int 등록된 개수
*/
public function bulkCreate(array $items): int;
@@ -119,7 +127,7 @@ interface ExtraFeeTemplateRepositoryInterface
* ID 목록으로 추가비용 템플릿을 조회하고 ID 키 맵으로 반환합니다 (bulk activity log lookup).
*
* @param array<int, int> $ids 템플릿 ID 목록
* @return \Illuminate\Database\Eloquent\Collection
* @return Collection
*/
public function findByIdsKeyed(array $ids): \Illuminate\Database\Eloquent\Collection;
public function findByIdsKeyed(array $ids): Collection;
}
@@ -40,6 +40,21 @@ class ExtraFeeTemplateRepository implements ExtraFeeTemplateRepositoryInterface
return $this->model->where('zipcode', $zipcode)->first();
}
/**
* 여러 우편번호로 템플릿을 한 번에 조회
*
* @param array $zipcodes 우편번호 목록
* @return Collection
*/
public function findByZipcodes(array $zipcodes): Collection
{
if (empty($zipcodes)) {
return $this->model->newCollection();
}
return $this->model->whereIn('zipcode', $zipcodes)->get();
}
/**
* {@inheritDoc}
*/
@@ -9,12 +9,16 @@ use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Ecommerce\Exceptions\BrandOperationException;
use Modules\Sirsoft\Ecommerce\Models\Brand;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\BrandRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 브랜드 서비스
*/
class BrandService
{
use ReappliesPermissionScope;
public function __construct(
protected BrandRepositoryInterface $repository
) {}
@@ -108,6 +112,12 @@ class BrandService
*/
public function updateBrand(int $id, array $data): Brand
{
$brandForScope = $this->repository->findById($id);
if (! $brandForScope) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($brandForScope, 'sirsoft-ecommerce.brands.update');
$brand = $this->repository->findById($id);
if (! $brand) {
@@ -149,6 +159,12 @@ class BrandService
*/
public function toggleStatus(int $id): Brand
{
$brandForScope = $this->repository->findById($id);
if (! $brandForScope) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($brandForScope, 'sirsoft-ecommerce.brands.update');
$brand = $this->repository->findById($id);
if (! $brand) {
@@ -180,6 +196,12 @@ class BrandService
*/
public function deleteBrand(int $id): array
{
$brandForScope = $this->repository->findById($id);
if (! $brandForScope) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($brandForScope, 'sirsoft-ecommerce.brands.delete');
$brand = $this->repository->findById($id);
if (! $brand) {
@@ -12,12 +12,16 @@ use Modules\Sirsoft\Ecommerce\Models\Coupon;
use Modules\Sirsoft\Ecommerce\Models\CouponIssue;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponIssueRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 쿠폰 서비스
*/
class CouponService
{
use ReappliesPermissionScope;
public function __construct(
protected CouponRepositoryInterface $repository,
protected UserCouponService $userCouponService,
@@ -140,6 +144,12 @@ class CouponService
*/
public function updateCoupon(int $id, array $data): Coupon
{
$coupon = $this->repository->findById($id);
if (! $coupon) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($coupon, 'sirsoft-ecommerce.promotion-coupon.update');
$coupon = $this->repository->findById($id);
if (! $coupon) {
@@ -197,6 +207,12 @@ class CouponService
*/
public function deleteCoupon(int $id): array
{
$coupon = $this->repository->findById($id);
if (! $coupon) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($coupon, 'sirsoft-ecommerce.promotion-coupon.delete');
$coupon = $this->repository->findById($id);
if (! $coupon) {
@@ -232,11 +248,16 @@ class CouponService
*/
public function bulkUpdateIssueStatus(array $ids, string $issueStatus): int
{
// 스코프 검사와 스냅샷이 같은 조회를 공유한다 (Model 직접 호출 제거 겸용).
$targets = $this->repository->findByIdsKeyed($ids);
$this->assertAllWithinScope($targets, 'sirsoft-ecommerce.promotion-coupon.update');
// Before 훅
HookManager::doAction('sirsoft-ecommerce.coupon.before_bulk_status', $ids, $issueStatus);
// 수정 전 스냅샷 캡처
$snapshots = $this->repository->findByIdsKeyed($ids)->map->toArray()->all();
$snapshots = $targets->keyBy('id')->map->toArray()->all();
$count = DB::transaction(function () use ($ids, $issueStatus) {
return $this->repository->bulkUpdateIssueStatus($ids, $issueStatus);
@@ -262,6 +283,12 @@ class CouponService
*/
public function issueDirectly(int $couponId, array $userIds): array
{
$coupon = $this->repository->findById($couponId);
if (! $coupon) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
$this->assertWithinScope($coupon, 'sirsoft-ecommerce.promotion-coupon.update');
HookManager::doAction('sirsoft-ecommerce.coupon.before_direct_issue', $couponId, $userIds);
$result = DB::transaction(function () use ($couponId, $userIds) {
@@ -8,12 +8,15 @@ use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Modules\Sirsoft\Ecommerce\Models\ExtraFeeTemplate;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ExtraFeeTemplateRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
/**
* 추가배송비 템플릿 서비스
*/
class ExtraFeeTemplateService
{
use ReappliesPermissionScope;
public function __construct(
protected ExtraFeeTemplateRepositoryInterface $repository
) {}
@@ -21,7 +24,7 @@ class ExtraFeeTemplateService
/**
* 템플릿 목록 조회
*
* @param array $filters 필터 조건
* @param array $filters 필터 조건
* @return LengthAwarePaginator
*/
public function getList(array $filters): LengthAwarePaginator
@@ -47,7 +50,7 @@ class ExtraFeeTemplateService
/**
* 템플릿 상세 조회
*
* @param int $id 템플릿 ID
* @param int $id 템플릿 ID
* @return ExtraFeeTemplate|null
*/
public function getDetail(int $id): ?ExtraFeeTemplate
@@ -64,7 +67,7 @@ class ExtraFeeTemplateService
/**
* 우편번호로 템플릿 조회
*
* @param string $zipcode 우편번호
* @param string $zipcode 우편번호
* @return ExtraFeeTemplate|null
*/
public function findByZipcode(string $zipcode): ?ExtraFeeTemplate
@@ -75,7 +78,7 @@ class ExtraFeeTemplateService
/**
* 템플릿 생성
*
* @param array $data 템플릿 데이터
* @param array $data 템플릿 데이터
* @return ExtraFeeTemplate
*/
public function create(array $data): ExtraFeeTemplate
@@ -101,12 +104,14 @@ class ExtraFeeTemplateService
/**
* 템플릿 수정
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param array $data 수정 데이터
* @param ExtraFeeTemplate $template 템플릿 모델
* @param array $data 수정 데이터
* @return ExtraFeeTemplate
*/
public function update(ExtraFeeTemplate $template, array $data): ExtraFeeTemplate
{
$this->assertWithinScope($template, 'sirsoft-ecommerce.shipping-policies.update');
// 수정 전 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.before_update', $template, $data);
@@ -130,11 +135,13 @@ class ExtraFeeTemplateService
/**
* 템플릿 삭제
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param ExtraFeeTemplate $template 템플릿 모델
* @return bool
*/
public function delete(ExtraFeeTemplate $template): bool
{
$this->assertWithinScope($template, 'sirsoft-ecommerce.shipping-policies.delete');
// 삭제 전 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.before_delete', $template);
@@ -149,11 +156,13 @@ class ExtraFeeTemplateService
/**
* 템플릿 사용여부 토글
*
* @param ExtraFeeTemplate $template 템플릿 모델
* @param ExtraFeeTemplate $template 템플릿 모델
* @return ExtraFeeTemplate
*/
public function toggleActive(ExtraFeeTemplate $template): ExtraFeeTemplate
{
$this->assertWithinScope($template, 'sirsoft-ecommerce.shipping-policies.update');
// 토글 전 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.before_toggle_active', $template);
@@ -168,13 +177,18 @@ class ExtraFeeTemplateService
/**
* 템플릿 일괄 삭제
*
* @param array $ids 템플릿 ID 배열
* @param array $ids 템플릿 ID 배열
* @return int 삭제된 개수
*/
public function bulkDelete(array $ids): int
{
// 스코프 검사와 스냅샷이 같은 조회를 공유한다 (Model 직접 호출 제거 겸용).
$targets = $this->repository->findByIdsKeyed($ids);
$this->assertAllWithinScope($targets, 'sirsoft-ecommerce.shipping-policies.delete');
// 삭제 전 스냅샷 캡처 (after_bulk_delete 훅에 전달)
$snapshots = ExtraFeeTemplate::whereIn('id', $ids)->get()->keyBy('id')->map->toArray()->all();
$snapshots = $targets->keyBy('id')->map->toArray()->all();
// 일괄 삭제 전 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.before_bulk_delete', $ids);
@@ -190,14 +204,19 @@ class ExtraFeeTemplateService
/**
* 템플릿 일괄 사용여부 변경
*
* @param array $ids 템플릿 ID 배열
* @param bool $isActive 사용여부
* @param array $ids 템플릿 ID 배열
* @param bool $isActive 사용여부
* @return int 변경된 개수
*/
public function bulkToggleActive(array $ids, bool $isActive): int
{
// 스코프 검사와 스냅샷이 같은 조회를 공유한다 (Model 직접 호출 제거 겸용).
$targets = $this->repository->findByIdsKeyed($ids);
$this->assertAllWithinScope($targets, 'sirsoft-ecommerce.shipping-policies.update');
// 변경 전 스냅샷 캡처 (after_bulk_toggle_active 훅에 전달)
$snapshots = ExtraFeeTemplate::whereIn('id', $ids)->get()->keyBy('id')->map->toArray()->all();
$snapshots = $targets->keyBy('id')->map->toArray()->all();
// 일괄 변경 전 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.before_bulk_toggle_active', $ids, $isActive);
@@ -233,7 +252,7 @@ class ExtraFeeTemplateService
/**
* 일괄 등록 (CSV 또는 엑셀 업로드용)
*
* @param array $items 템플릿 데이터 배열 [{zipcode, fee, region?, description?}]
* @param array $items 템플릿 데이터 배열 [{zipcode, fee, region?, description?}]
* @return int 등록된 개수
*/
public function bulkCreate(array $items): int
@@ -248,7 +267,7 @@ class ExtraFeeTemplateService
// 생성/업데이트된 레코드 조회 (per-item 로깅용)
$zipcodes = array_column($items, 'zipcode');
$createdTemplates = ExtraFeeTemplate::whereIn('zipcode', $zipcodes)->get();
$createdTemplates = $this->repository->findByZipcodes($zipcodes);
// 일괄 등록 후 훅
HookManager::doAction('sirsoft-ecommerce.extra_fee_template.after_bulk_create', $items, $count, $createdTemplates);
@@ -19,12 +19,15 @@ use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\UserAddressRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
/**
* 주문 서비스
*/
class OrderService
{
use ReappliesPermissionScope;
public function __construct(
protected OrderRepositoryInterface $repository,
protected UserAddressRepositoryInterface $userAddressRepository,
@@ -161,6 +164,8 @@ class OrderService
*/
public function update(Order $order, array $data): Order
{
$this->assertWithinScope($order, 'sirsoft-ecommerce.orders.update');
$oldStatus = $order->order_status?->value;
// 수정 전 훅
@@ -350,6 +355,8 @@ class OrderService
*/
public function delete(Order $order): bool
{
$this->assertWithinScope($order, 'sirsoft-ecommerce.orders.delete');
// 삭제 전 훅
HookManager::doAction('sirsoft-ecommerce.order.before_delete', $order);
@@ -390,6 +397,8 @@ class OrderService
*/
public function bulkUpdate(array $data): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($data['ids'] ?? []), 'sirsoft-ecommerce.orders.update');
$ids = $data['ids'] ?? [];
$orderStatus = $data['order_status'] ?? null;
$carrierId = $data['carrier_id'] ?? null;
@@ -506,6 +515,8 @@ class OrderService
*/
public function bulkUpdateStatus(array $ids, string $status): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($ids), 'sirsoft-ecommerce.orders.update');
// 스냅샷 캡처 (ChangeDetector용 + 전이 감지용 이전 order_status)
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -548,6 +559,8 @@ class OrderService
*/
public function bulkUpdateShipping(array $ids, ?int $carrierId, ?string $trackingNumber): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($ids), 'sirsoft-ecommerce.orders.update');
// 스냅샷 캡처 (ChangeDetector용)
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -628,6 +641,8 @@ class OrderService
*/
public function updateShippingAddress(Order $order, array $data): Order
{
$this->assertWithinScope($order, 'sirsoft-ecommerce.orders.update');
$status = $order->order_status;
if (! $status->isBeforeShipping()) {
@@ -108,7 +108,10 @@ class ProductInquiryService
}
}
// 비밀글 제외 필터 적용 (Post의 is_secret 기준)
// 비밀글 원문 마스킹은 게시판 훅(getByIds)이 요청자 신원 기준으로 서버측에서
// 이미 수행한다(KVE-2026-1914, SecretContentGate SSoT). 아래 exclude_secret 은
// 보안 판정이 아니라 단순 "비밀글 행 숨김" 표시 필터일 뿐이며, 노출 여부는
// 클라이언트 파라미터와 무관하게 서버가 결정한다.
if ($excludeSecret) {
$pivots = $pivots->filter(function ($pivot) use ($posts) {
$post = $posts[$pivot->inquirable_id] ?? null;
@@ -132,21 +135,37 @@ class ProductInquiryService
$userId = $post['user_id'] ?? null;
$name = $userId ? ($userMap[$userId] ?? $post['author_name'] ?? null) : ($post['author_name'] ?? null);
// 비밀글 이중 방어(KVE-2026-1914): 게시판 훅(getByIds)이 이미 요청자 신원으로
// 원문을 마스킹하지만, 훅이 신원 판정만 하고 특정 필드 null 처리를 누락하는 회귀에
// 대비해 훅이 실어 보낸 권위 플래그(can_view_secret)로 payload 를 재확정한다.
// 자기 권한을 재계산하지 않으므로(플래그만 신뢰) 게이트 강도가 훅과 갈리지 않는다.
//
// fail-closed: 비밀글인데 권위 플래그가 없으면(훅 미치환·타 확장 치환으로 누락)
// 열람 가능으로 가정하지 않고 마스킹한다. 플래그 부재 = 권위 미상 = 안전 측(감춤).
// 비밀글이 아니면($isSecret=false) 어느 경우에도 마스킹되지 않으므로 영향 없다.
$isSecret = $post['is_secret'] ?? false;
$secretMasked = $isSecret && $post !== null && ($post['can_view_secret'] ?? false) === false;
return [
'id' => $pivot->id,
'post_id' => $pivot->inquirable_id,
'user_id' => $userId,
'author_name' => $this->maskAuthorName($name),
'title' => $post['title'] ?? null,
// 비밀글이면 title 도 fail-closed 로 재마스킹한다(KVE-2026-1914 A2b).
// 훅이 신원 판정만 하고 title 치환을 누락하는 회귀에 대비 — 플레이스홀더 텍스트
// 자체는 게시판 lang 키(post.secret_post_title)가 SSoT 로, 훅의 마스킹 값과 동일하다.
'title' => $secretMasked
? __('sirsoft-board::messages.post.secret_post_title')
: ($post['title'] ?? null),
'category' => $post['category'] ?? null,
'content' => $post['content'] ?? null,
'is_secret' => $post['is_secret'] ?? false,
'content' => $secretMasked ? null : ($post['content'] ?? null),
'is_secret' => $isSecret,
'is_owner' => $isOwner,
'is_answered' => $pivot->is_answered ?? false,
'answered_at' => $pivot->answered_at?->toIso8601String(),
'created_at' => $pivot->created_at?->toIso8601String(),
'reply' => $post['reply'] ?? null,
'attachments' => $post['attachments'] ?? [],
'reply' => $secretMasked ? null : ($post['reply'] ?? null),
'attachments' => $secretMasked ? [] : ($post['attachments'] ?? []),
];
})->values()->all();
@@ -222,6 +241,12 @@ class ProductInquiryService
$data['user_id'] = Auth::id();
}
// 클라이언트 IP 를 요청 경계(Service)에서 캡처해 게시판 훅 payload 로 전달한다.
// 게시판 Listener 가 request() 를 직접 참조하지 않도록 소유 서비스가 주입한다.
if (empty($data['ip_address'])) {
$data['ip_address'] = request()->ip() ?? '0.0.0.0';
}
$inquiry = DB::transaction(function () use ($productId, $product, $boardSlug, $data) {
// 게시판 훅으로 Post 생성
$postResult = HookManager::applyFilters(
@@ -600,6 +625,11 @@ class ProductInquiryService
$boardSlug = $this->getInquiryBoardSlug();
// 클라이언트 IP 를 요청 경계(Service)에서 캡처해 게시판 훅 payload 로 전달한다.
if (empty($data['ip_address'])) {
$data['ip_address'] = request()->ip() ?? '0.0.0.0';
}
$updated = DB::transaction(function () use ($inquiry, $boardSlug, $data) {
// 게시판 훅으로 Reply Post 생성 (title은 리스너에서 Re: 부모글제목 형식으로 설정)
$replyData = array_merge($data, [
@@ -9,6 +9,7 @@ use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Sirsoft\Ecommerce\Enums\ReviewStatus;
use Modules\Sirsoft\Ecommerce\Exceptions\ReviewImageUploadLimitException;
use Modules\Sirsoft\Ecommerce\Models\ProductReview;
use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
@@ -165,6 +166,18 @@ class ProductReviewImageService
return null;
}
// 숨김(HIDDEN) 리뷰의 이미지는 서빙하지 않는다(KVE-2026-1914 S-2).
// 관리자가 숨긴 리뷰의 이미지가 해시만으로 공개 서빙되던 불일치를 정합화한다.
//
// 부모 리뷰를 못 읽으면 **가린다**(fail-closed). ProductReview 는 소프트 삭제되므로
// 관계 조회가 null 을 돌려줄 수 있는데, 그때 게이트가 성립하지 않아 통과하면
// "부모가 사라진 이미지는 무조건 공개" 가 된다 — 첨부 게이트가 채택한 방향과 반대다.
// 현재는 리뷰 삭제 시 이미지도 함께 삭제돼 여기까지 오지 않지만, 그 두 서비스가
// 계속 동기화된다는 암묵 불변식에 보안을 걸지 않는다.
if (! $image->review || $image->review->status !== ReviewStatus::VISIBLE) {
return null;
}
$response = $this->storageForRow($image->disk)->response(
'images',
$image->path,
@@ -17,6 +17,7 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewImageRepositor
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Services\Concerns\ResolvesRowStorage;
use Modules\Sirsoft\Ecommerce\Support\ReviewWritePolicy;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
/**
* 상품 리뷰 서비스
@@ -25,6 +26,7 @@ use Modules\Sirsoft\Ecommerce\Support\ReviewWritePolicy;
*/
class ProductReviewService
{
use ReappliesPermissionScope;
use ResolvesRowStorage;
/**
@@ -168,6 +170,8 @@ class ProductReviewService
*/
public function updateStatus(ProductReview $review, string $status): ProductReview
{
$this->assertWithinScope($review, 'sirsoft-ecommerce.reviews.update');
return $this->repository->update($review, ['status' => $status]);
}
@@ -200,6 +204,8 @@ class ProductReviewService
*/
public function deleteReply(ProductReview $review): ProductReview
{
$this->assertWithinScope($review, 'sirsoft-ecommerce.reviews.update');
return $this->repository->update($review, [
'reply_content' => null,
'reply_content_mode' => 'text',
@@ -217,6 +223,8 @@ class ProductReviewService
*/
public function deleteReview(ProductReview $review): bool
{
$this->assertWithinScope($review, 'sirsoft-ecommerce.reviews.delete');
HookManager::doAction('sirsoft-ecommerce.product-review.before_delete', $review);
return DB::transaction(function () use ($review) {
@@ -251,6 +259,8 @@ class ProductReviewService
*/
public function bulkUpdateStatus(array $ids, string $status): int
{
$this->assertAllWithinScope($this->repository->getByIdsWithImages($ids), 'sirsoft-ecommerce.reviews.update');
return $this->repository->bulkUpdateStatus($ids, $status);
}
@@ -264,6 +274,8 @@ class ProductReviewService
{
$reviews = $this->repository->getByIdsWithImages($ids);
$this->assertAllWithinScope($reviews, 'sirsoft-ecommerce.reviews.delete');
// 삭제 전 스냅샷 캡처 (after_bulk_delete 훅에 전달)
$snapshots = $reviews->keyBy('id')->map->toArray()->all();
@@ -22,12 +22,15 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderOptionRepositoryInterf
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductAdditionalOptionValueRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductLabelRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
/**
* 상품 서비스
*/
class ProductService
{
use ReappliesPermissionScope;
/**
* 검색 정렬 이름 → [실제 컬럼, 방향] 선언
*
@@ -301,6 +304,8 @@ class ProductService
*/
public function update(Product $product, array $data): Product
{
$this->assertWithinScope($product, 'sirsoft-ecommerce.products.update');
// 수정 전 훅
HookManager::doAction('sirsoft-ecommerce.product.before_update', $product, $data);
@@ -405,6 +410,8 @@ class ProductService
*/
public function delete(Product $product): bool
{
$this->assertWithinScope($product, 'sirsoft-ecommerce.products.delete');
// 도메인 가드: 주문 이력이 있는 상품은 삭제 불가 (컨트롤러 우회·bulk 경로 방어)
// DB FK restrictOnDelete 가 거부하기 전에 사유가 명확한 예외로 차단한다.
$ordersCount = $this->orderOptionRepository->countByProductId($product->id);
@@ -489,6 +496,8 @@ class ProductService
*/
public function bulkUpdateStatus(array $ids, string $field, string $value): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($ids), 'sirsoft-ecommerce.products.update');
// 스냅샷 캡처 (활동 로그 변경 감지용)
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -522,6 +531,8 @@ class ProductService
*/
public function bulkUpdatePrice(array $ids, string $method, float $value, string $unit): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($ids), 'sirsoft-ecommerce.products.update');
// 스냅샷 캡처 (활동 로그 변경 감지용)
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -554,6 +565,8 @@ class ProductService
*/
public function bulkUpdateStock(array $ids, string $method, int $value): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($ids), 'sirsoft-ecommerce.products.update');
// 스냅샷 캡처 (활동 로그 변경 감지용)
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -584,6 +597,8 @@ class ProductService
*/
public function bulkUpdate(array $data): array
{
$this->assertAllWithinScope($this->repository->findByIdsKeyed($data['ids'] ?? []), 'sirsoft-ecommerce.products.update');
// 스냅샷 캡처 (활동 로그 변경 감지용)
$ids = $data['ids'] ?? [];
$snapshots = $this->repository->getSnapshotsByIds($ids);
@@ -9,12 +9,15 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Ecommerce\Models\ShippingPolicy;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ShippingPolicyRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Traits\ReappliesPermissionScope;
/**
* 배송정책 서비스
*/
class ShippingPolicyService
{
use ReappliesPermissionScope;
public function __construct(
protected ShippingPolicyRepositoryInterface $repository
) {}
@@ -118,6 +121,8 @@ class ShippingPolicyService
*/
public function update(ShippingPolicy $shippingPolicy, array $data): ShippingPolicy
{
$this->assertWithinScope($shippingPolicy, 'sirsoft-ecommerce.shipping-policies.update');
// 수정 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_update', $shippingPolicy, $data);
@@ -239,6 +244,9 @@ class ShippingPolicyService
*/
public function delete(ShippingPolicy $shippingPolicy): bool
{
// 라우트가 강제하는 권한(SSoT)과 같은 식별자를 쓴다 — 삭제 경로는 `.delete` 다.
$this->assertWithinScope($shippingPolicy, 'sirsoft-ecommerce.shipping-policies.delete');
// 삭제 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_delete', $shippingPolicy);
@@ -264,6 +272,8 @@ class ShippingPolicyService
*/
public function toggleActive(ShippingPolicy $shippingPolicy): ShippingPolicy
{
$this->assertWithinScope($shippingPolicy, 'sirsoft-ecommerce.shipping-policies.update');
// 토글 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_toggle_active', $shippingPolicy);
@@ -283,8 +293,14 @@ class ShippingPolicyService
*/
public function bulkDelete(array $ids): int
{
// 스코프 검사와 스냅샷이 같은 조회를 공유한다 — 두 번 부르면 쿼리가 늘고,
// 그 사이에 대상이 바뀌면 검사한 것과 기록하는 것이 달라진다.
$targets = $this->repository->findByIdsKeyed($ids);
$this->assertAllWithinScope($targets, 'sirsoft-ecommerce.shipping-policies.delete');
// 삭제 전 스냅샷 캡처 (after_bulk_delete 훅에 전달)
$snapshots = $this->repository->findByIdsKeyed($ids)->map->toArray()->all();
$snapshots = $targets->map->toArray()->all();
// 일괄 삭제 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_bulk_delete', $ids);
@@ -309,8 +325,13 @@ class ShippingPolicyService
*/
public function bulkToggleActive(array $ids, bool $isActive): int
{
// 스코프 검사와 스냅샷이 같은 조회를 공유한다(위 bulkDelete 와 동일 이유).
$targets = $this->repository->findByIdsKeyed($ids);
$this->assertAllWithinScope($targets, 'sirsoft-ecommerce.shipping-policies.update');
// 변경 전 스냅샷 캡처 (after_bulk_toggle_active 훅에 전달)
$snapshots = $this->repository->findByIdsKeyed($ids)->map->toArray()->all();
$snapshots = $targets->map->toArray()->all();
// 일괄 변경 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_bulk_toggle_active', $ids, $isActive);
@@ -341,6 +362,8 @@ class ShippingPolicyService
*/
public function setDefault(ShippingPolicy $shippingPolicy): ShippingPolicy
{
$this->assertWithinScope($shippingPolicy, 'sirsoft-ecommerce.shipping-policies.update');
// 기본값 설정 전 훅
HookManager::doAction('sirsoft-ecommerce.shipping_policy.before_set_default', $shippingPolicy);
@@ -0,0 +1,59 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Traits;
use App\Helpers\PermissionHelper;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 서비스 계층 스코프 게이트 재적용
*
* `PermissionMiddleware` 는 라우트 파라미터가 **Model 로 resolve 될 때만** 스코프를 검사하고,
* 아니면 "목록 엔드포인트" 로 보아 건너뛴다. 이 모듈은 두 형태가 모두 존재한다:
*
* 1. **정적 경로** — `bulk-*`, `reorder` 처럼 리소스 파라미터 자체가 없는 라우트
* 2. **파라미터명 불일치** — 권한은 `resource_route_key` 로 `shippingPolicy`/`coupon` 을
* 가리키는데 라우트는 `{id}` 로 선언돼 바인딩이 일어나지 않는 경우. 이쪽은 **상세 경로까지**
* 무가드가 된다.
*
* 두 경우 모두 미들웨어가 아무 것도 하지 않으므로 서비스가 같은 판정을 재적용한다. 판정은
* `PermissionHelper::checkScopeAccess` 단일 SSoT 에 위임한다 — 여기서 재구현하면 스코프
* 유형 하나가 빠지는 식으로 경로별 강도가 갈린다.
*/
trait ReappliesPermissionScope
{
/**
* 단일 대상이 액터의 스코프 안에 있는지 검사합니다.
*
* @param Model $model 대상 모델
* @param string $permission 스코프 대상 권한 식별자
*
* @throws AccessDeniedHttpException 스코프 밖인 경우
*/
protected function assertWithinScope(Model $model, string $permission): void
{
if (! PermissionHelper::checkScopeAccess($model, $permission)) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
}
/**
* 일괄 대상 전체가 액터의 스코프 안에 있는지 검사합니다.
*
* 걸러내지 않고 **전량 거부**한다. 일괄 작업은 호출자가 지정한 집합에 대한 한 번의
* 의사표시라, 일부만 조용히 빠지면 호출자는 전부 반영됐다고 믿는다(응답의 처리 건수만
* 다를 뿐 어느 것이 빠졌는지 알 수 없다).
*
* @param iterable<Model> $models 대상 모델들
* @param string $permission 스코프 대상 권한 식별자
*
* @throws AccessDeniedHttpException 스코프 밖 대상이 하나라도 있는 경우
*/
protected function assertAllWithinScope(iterable $models, string $permission): void
{
foreach ($models as $model) {
$this->assertWithinScope($model, $permission);
}
}
}
@@ -484,4 +484,52 @@ class ExtraFeeTemplateControllerTest extends ModuleTestCase
$response = $this->getJson('/api/modules/sirsoft-ecommerce/admin/extra-fee-templates');
$response->assertStatus(401);
}
// ────────────────────────────────────────────────────────
// 능력(abilities) 게이트 정합성 — 라우트 SSoT(shipping-policies.*) 일치
// ────────────────────────────────────────────────────────
/**
* 상세 리소스의 can_* 능력은 라우트 SSoT(shipping-policies.*)로 게이팅된다.
*
* 회귀 방지: 과거 상세 리소스만 abilityMap 을 settings.update(타 리소스)로 게이팅해,
* shipping-policies.* 만 보유한(=라우트상 편집 권한이 있는) 액터가 상세 화면에서 can_update
* 가 false 로 보이던 결함. 이제 상세도 형제 Collection·라우트와 동일한 권한으로 게이팅한다.
*/
public function test_show_abilities_follow_shipping_policies_permission(): void
{
$template = $this->createTemplate();
// adminUser 는 shipping-policies.* 만 보유하고 settings.update 는 없다(setUp).
$response = $this->actingAs($this->adminUser)
->getJson("/api/modules/sirsoft-ecommerce/admin/extra-fee-templates/{$template->id}");
$response->assertOk();
$this->assertTrue($response->json('data.abilities.can_update'), 'can_update 는 shipping-policies.update 로 게이팅되어야 합니다');
$this->assertTrue($response->json('data.abilities.can_create'), 'can_create 는 shipping-policies.create 로 게이팅되어야 합니다');
$this->assertTrue($response->json('data.abilities.can_delete'), 'can_delete 는 shipping-policies.delete 로 게이팅되어야 합니다');
}
/**
* settings.update 만 있고 shipping-policies 권한이 없으면 상세 능력은 모두 false 여야 한다.
*
* (게이트가 실제로 shipping-policies 로 옮겨졌음을 반대 방향으로 고정 — settings.update 로는
* 더 이상 편집 능력이 켜지지 않는다)
*/
public function test_show_abilities_false_with_only_settings_permission(): void
{
$settingsOnlyUser = $this->createAdminUser([
'sirsoft-ecommerce.shipping-policies.read', // 상세 조회용
'sirsoft-ecommerce.settings.update',
]);
$template = $this->createTemplate();
$response = $this->actingAs($settingsOnlyUser)
->getJson("/api/modules/sirsoft-ecommerce/admin/extra-fee-templates/{$template->id}");
$response->assertOk();
$this->assertFalse($response->json('data.abilities.can_update'), 'settings.update 로는 편집 능력이 켜지면 안 됩니다');
$this->assertFalse($response->json('data.abilities.can_create'));
$this->assertFalse($response->json('data.abilities.can_delete'));
}
}
@@ -128,6 +128,195 @@ class PublicProductInquiryControllerTest extends ModuleTestCase
$this->assertSame('홍*동', $items[0]['author_name']);
}
/**
* 게시판 훅이 신원 판정(can_view_secret=false)만 하고 원문 필드 null 처리를 누락하더라도
* 서비스가 그 권위 플래그로 payload 를 재확정한다 (KVE-2026-1914 A-2 이중 방어).
*
* 훅(get_by_ids)이 마스킹을 누락한 채 content/reply/attachments 를 실어 보내는 회귀를
* 모사한다 — 서비스가 can_view_secret=false 를 신뢰해 content/reply/attachments 를
* 다시 마스킹해야 원문이 새지 않는다. 자기 권한을 재계산하지 않으므로(플래그만 신뢰)
* 게이트 강도가 훅과 갈리지 않는다.
*
* @scenario layer=service, viewer=non_viewer
*
* @effects service_remasks_when_hook_omits_masking, service_remasks_title_with_shared_placeholder
*/
#[Test]
public function 훅이_마스킹을_누락해도_서비스가_can_view_secret_플래그로_원문을_재차단한다(): void
{
app(EcommerceSettingsService::class)->setSetting('inquiry.board_slug', 'test-board');
$owner = $this->createUser(); // 조회자(비회원)와 다른 작성자
$pivot = ProductInquiry::create([
'product_id' => $this->product->id,
'inquirable_type' => 'board_post',
'inquirable_id' => 555,
'user_id' => $owner->id,
]);
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_settings',
fn ($defaults) => $defaults,
priority: 1
);
// 훅이 신원 판정만 하고 필드 마스킹을 누락한 상태(회귀)를 모사 — content/reply/attachments 가 원문 그대로 실려온다.
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_by_ids',
fn () => [[
'id' => $pivot->inquirable_id,
'user_id' => $owner->id,
'author_name' => '작성자',
'title' => '비밀 문의 제목',
'is_secret' => true,
'can_view_secret' => false,
'content' => '유출되면 안 되는 비밀 내용',
'reply' => '유출되면 안 되는 답변',
'attachments' => [['id' => 1, 'original_filename' => 'secret.pdf']],
]],
priority: 1
);
$response = $this->getJson(
"/api/modules/sirsoft-ecommerce/products/{$this->product->id}/inquiries"
);
$response->assertOk();
$items = $response->json('data.items');
$this->assertCount(1, $items);
$this->assertTrue($items[0]['is_secret']);
$this->assertNull($items[0]['content'], '훅 누락 시에도 서비스가 content 를 재마스킹해야 합니다');
$this->assertNull($items[0]['reply'], '훅 누락 시에도 서비스가 reply 를 재마스킹해야 합니다');
$this->assertSame([], $items[0]['attachments'], '훅 누락 시에도 서비스가 attachments 를 비워야 합니다');
// A2b: title 도 재마스킹 대상 — 훅이 실어 보낸 원문 제목이 유출되면 안 된다.
$this->assertNotSame('비밀 문의 제목', $items[0]['title'], '훅 누락 시에도 서비스가 title 원문을 유출하면 안 됩니다');
$this->assertSame(
__('sirsoft-board::messages.post.secret_post_title'),
$items[0]['title'],
'훅 누락 시에도 서비스가 title 을 게시판 비밀글 플레이스홀더로 재마스킹해야 합니다'
);
}
/**
* 훅 payload 에 can_view_secret 키가 **아예 없으면** 서비스는 마스킹 쪽으로 닫힌다.
*
* `ProductInquiryService` 의 판정은 `($post['can_view_secret'] ?? false) === false` 라
* 플래그 부재 시 fail-closed 다. 그런데 이 분기를 밟는 테스트가 없으면 `?? false` 를
* `?? true`(fail-open)로 바꿔도 전 스위트가 green 이다 — 게시판 훅을 대체 구현한
* 확장이 플래그를 실어 보내지 않는 순간 비밀 문의 원문이 그대로 나간다.
*
* 플래그를 명시 전달하는 위 테스트와 달리, 여기서는 키 자체를 생략한다.
*
* @scenario layer=service, viewer=non_viewer
*
* @effects service_fails_closed_when_flag_absent
*/
#[Test]
public function can_view_secret_키가_없으면_서비스가_마스킹_쪽으로_닫힌다(): void
{
app(EcommerceSettingsService::class)->setSetting('inquiry.board_slug', 'test-board');
$owner = $this->createUser();
$pivot = ProductInquiry::create([
'product_id' => $this->product->id,
'inquirable_type' => 'board_post',
'inquirable_id' => 556,
'user_id' => $owner->id,
]);
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_settings',
fn ($defaults) => $defaults,
priority: 1
);
// can_view_secret 키를 의도적으로 생략 — 권위 플래그를 실어 보내지 않는 훅 구현을 모사한다.
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_by_ids',
fn () => [[
'id' => $pivot->inquirable_id,
'user_id' => $owner->id,
'author_name' => '작성자',
'title' => '비밀 문의 제목',
'is_secret' => true,
'content' => '유출되면 안 되는 비밀 내용',
'reply' => '유출되면 안 되는 답변',
'attachments' => [['id' => 1, 'original_filename' => 'secret.pdf']],
]],
priority: 1
);
$response = $this->getJson(
"/api/modules/sirsoft-ecommerce/products/{$this->product->id}/inquiries"
);
$response->assertOk();
$items = $response->json('data.items');
$this->assertCount(1, $items);
$this->assertTrue($items[0]['is_secret']);
$this->assertNull($items[0]['content'], '플래그 부재 시 content 는 마스킹되어야 합니다(fail-closed)');
$this->assertNull($items[0]['reply'], '플래그 부재 시 reply 는 마스킹되어야 합니다(fail-closed)');
$this->assertSame([], $items[0]['attachments'], '플래그 부재 시 attachments 는 비워져야 합니다');
$this->assertSame(
__('sirsoft-board::messages.post.secret_post_title'),
$items[0]['title'],
'플래그 부재 시 title 도 플레이스홀더로 마스킹되어야 합니다'
);
}
/**
* 열람 권한이 있으면(can_view_secret=true) 비밀글 원문이 그대로 노출된다 (과잉 차단 회귀 방지).
*
* @scenario layer=service, viewer=owner
*
* @effects service_exposes_original_when_flag_true
*/
#[Test]
public function can_view_secret_true면_비밀글_원문이_노출된다(): void
{
app(EcommerceSettingsService::class)->setSetting('inquiry.board_slug', 'test-board');
$owner = $this->createUser();
$pivot = ProductInquiry::create([
'product_id' => $this->product->id,
'inquirable_type' => 'board_post',
'inquirable_id' => 556,
'user_id' => $owner->id,
]);
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_settings',
fn ($defaults) => $defaults,
priority: 1
);
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.get_by_ids',
fn () => [[
'id' => $pivot->inquirable_id,
'user_id' => $owner->id,
'author_name' => '작성자',
'title' => '비밀 문의 제목',
'is_secret' => true,
'can_view_secret' => true,
'content' => '열람 가능한 비밀 내용',
'reply' => '열람 가능한 답변',
'attachments' => [['id' => 1, 'original_filename' => 'ok.pdf']],
]],
priority: 1
);
$items = $this->getJson(
"/api/modules/sirsoft-ecommerce/products/{$this->product->id}/inquiries"
)->assertOk()->json('data.items');
$this->assertCount(1, $items);
$this->assertSame('열람 가능한 비밀 내용', $items[0]['content']);
$this->assertSame('열람 가능한 답변', $items[0]['reply']);
$this->assertCount(1, $items[0]['attachments']);
// 과잉 차단 회귀 방지: 열람 권한이 있으면 title 도 원문 그대로여야 한다(A2b 재마스킹이 과하지 않음).
$this->assertSame('비밀 문의 제목', $items[0]['title']);
}
#[Test]
public function board_slug_미설정_시_빈_목록과_inquiry_available_false를_반환한다(): void
{
@@ -183,6 +372,49 @@ class PublicProductInquiryControllerTest extends ModuleTestCase
$response->assertUnauthorized();
}
/**
* 서비스가 클라이언트 IP 를 게시판 훅 payload 에 주입한다 (문의 생성 경로).
*
* 게시판 Listener 는 `request()->ip()` 를 참조하지 않고 payload 의 ip_address 만
* 쓰도록 경계가 잡혀 있다(Listener 측 회귀 테스트 별도 존재). 그 경계가 성립하려면
* **요청 경계인 이 서비스가 IP 를 실어 보내야** 하는데, 주입 측을 단언하는 테스트가
* 없으면 주입 코드를 지워도 스위트가 green 이고 문의 IP 가 조용히 0.0.0.0 이 된다.
*
* @effects service_injects_client_ip_into_hook_payload
*/
#[Test]
public function 서비스가_문의_생성_훅_payload_에_클라이언트_ip_를_주입한다(): void
{
$user = $this->createUser();
app(EcommerceSettingsService::class)->setSetting('inquiry.board_slug', 'test-board');
$capturedIp = null;
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.create',
function ($result, $slug, $data) use (&$capturedIp) {
$capturedIp = $data['ip_address'] ?? null;
return ['post_id' => 999, 'inquirable_type' => 'Modules\\Sirsoft\\Board\\Models\\Post'];
},
priority: 1
);
$this->actingAs($user)
->withServerVariables(['REMOTE_ADDR' => '203.0.113.55'])
->postJson(
"/api/modules/sirsoft-ecommerce/products/{$this->product->id}/inquiries",
['content' => '문의 내용입니다 자세하게']
)
->assertStatus(201);
$this->assertSame(
'203.0.113.55',
$capturedIp,
'서비스가 요청 IP 를 게시판 훅 payload 로 주입해야 합니다'
);
}
#[Test]
public function 로그인_사용자는_문의를_작성할_수_있다(): void
{
@@ -9,6 +9,7 @@ use App\Models\Role;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Mockery;
use Mockery\MockInterface;
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
use Modules\Sirsoft\Ecommerce\Enums\ReviewStatus;
use Modules\Sirsoft\Ecommerce\Models\Order;
@@ -19,6 +20,7 @@ use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
use Modules\Sirsoft\Ecommerce\Services\ProductReviewImageService;
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
use PHPUnit\Framework\Attributes\Test;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 사용자 리뷰 이미지 API Feature 테스트
@@ -36,7 +38,7 @@ class ReviewImageControllerTest extends ModuleTestCase
private ProductReview $review;
/** @var \Mockery\MockInterface&StorageInterface */
/** @var MockInterface&StorageInterface */
private $storageMock;
protected function setUp(): void
@@ -351,4 +353,61 @@ class ReviewImageControllerTest extends ModuleTestCase
// Then
$response->assertUnauthorized();
}
// ========================================
// download() — 해시 기반 공개 서빙 (KVE-2026-1914 S-2)
// ========================================
/**
* @scenario resource=review_image, parent_state=restricted
*
* @effects hidden_review_image_download_blocked
*/
#[Test]
public function test_download_blocks_hidden_review_image(): void
{
// Given: 관리자가 숨긴(HIDDEN) 리뷰의 이미지
$hiddenReview = ProductReview::factory()->create([
'product_id' => $this->product->id,
'order_option_id' => $this->orderOption->id,
'user_id' => $this->user->id,
'status' => ReviewStatus::HIDDEN->value,
]);
$image = ProductReviewImage::factory()->create([
'review_id' => $hiddenReview->id,
]);
// When: 해시로 이미지 다운로드 시도
$response = $this->get(
"/api/modules/sirsoft-ecommerce/review-image/{$image->hash}"
);
// Then: 숨김 리뷰 이미지는 서빙 차단(404)
$response->assertNotFound();
}
/**
* @scenario resource=review_image, parent_state=public
*
* @effects visible_review_image_download_still_served
*/
#[Test]
public function test_download_serves_visible_review_image(): void
{
// Given: 전시중(VISIBLE) 리뷰의 이미지 + storage response mock
$image = ProductReviewImage::factory()->create([
'review_id' => $this->review->id,
]);
$this->storageMock->allows('response')->andReturn(
new StreamedResponse(fn () => null, 200)
);
// When
$response = $this->get(
"/api/modules/sirsoft-ecommerce/review-image/{$image->hash}"
);
// Then: VISIBLE 리뷰 이미지는 상태 게이트를 통과(404 아님)
$this->assertNotSame(404, $response->getStatusCode(), 'VISIBLE 리뷰 이미지는 서빙되어야 합니다');
}
}
@@ -3,6 +3,7 @@
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\User;
use App\Extension\HookManager;
use App\Models\User;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Modules\Sirsoft\Ecommerce\Models\ProductInquiry;
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
@@ -20,7 +21,7 @@ use PHPUnit\Framework\Attributes\Test;
*/
class UserProductInquiryControllerTest extends ModuleTestCase
{
private \App\Models\User $user;
private User $user;
private Product $product;
@@ -69,7 +70,7 @@ class UserProductInquiryControllerTest extends ModuleTestCase
);
$this->inquiry = ProductInquiry::factory()->create([
'user_id' => $this->user->id,
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'is_answered' => false,
]);
@@ -237,11 +238,58 @@ class UserProductInquiryControllerTest extends ModuleTestCase
$response->assertStatus(201);
$this->assertDatabaseHas('ecommerce_product_inquiries', [
'id' => $this->inquiry->id,
'id' => $this->inquiry->id,
'is_answered' => true,
]);
}
/**
* 서비스가 클라이언트 IP 를 게시판 훅 payload 에 주입한다 (답변 경로).
*
* 게시판 Listener 는 `request()->ip()` 를 참조하지 않고 payload 의 ip_address 만 쓴다.
* 그 경계는 **요청 경계인 서비스가 IP 를 실어 보낼 때만** 성립하는데, 생성 경로
* (`createInquiry`)와 답변 경로(`createReply`)는 서로 다른 메서드라 주입 코드도 각각
* 있다. 생성 경로만 단언하면 답변 경로의 주입을 지워도 스위트가 green 이고 답변 IP 가
* 조용히 0.0.0.0 으로 기록된다.
*
* @effects service_injects_client_ip_into_reply_hook_payload
*/
#[Test]
public function 서비스가_답변_훅_payload_에_클라이언트_ip_를_주입한다(): void
{
$manager = $this->createAdminUser(['sirsoft-ecommerce.inquiries.update']);
// setUp 의 기본 모킹을 걷어내고 payload 를 캡처하는 훅으로 교체한다.
HookManager::clearFilter('sirsoft-ecommerce.inquiry.create');
$capturedIp = null;
HookManager::addFilter(
'sirsoft-ecommerce.inquiry.create',
function ($result, $slug, $data) use (&$capturedIp) {
$capturedIp = $data['ip_address'] ?? null;
return ['post_id' => 999, 'inquirable_type' => 'Modules\\Sirsoft\\Board\\Models\\Post'];
},
priority: 1
);
// 요청 IP 를 비-0.0.0.0 으로 세팅한다 — 기본 request 로는 폴백값과 구분되지 않아
// 주입 코드를 지워도 단언이 통과한다(무증상 green).
$this->actingAs($manager)
->withServerVariables(['REMOTE_ADDR' => '203.0.113.77'])
->postJson(
"/api/modules/sirsoft-ecommerce/user/inquiries/{$this->inquiry->id}/reply",
['content' => '답변 내용입니다 친절하게 작성']
)
->assertStatus(201);
$this->assertSame(
'203.0.113.77',
$capturedIp,
'서비스가 답변 작성 시에도 요청 IP 를 게시판 훅 payload 로 주입해야 합니다'
);
}
// ========================================
// updateReply() — 답변 수정 (관리자 권한 필요)
// ========================================
@@ -250,8 +298,8 @@ class UserProductInquiryControllerTest extends ModuleTestCase
public function 권한_없는_사용자는_답변을_수정할_수_없다(): void
{
$answeredInquiry = ProductInquiry::factory()->create([
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'is_answered' => true,
]);
@@ -269,8 +317,8 @@ class UserProductInquiryControllerTest extends ModuleTestCase
{
$manager = $this->createAdminUser(['sirsoft-ecommerce.inquiries.update']);
$answeredInquiry = ProductInquiry::factory()->create([
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'is_answered' => true,
]);
@@ -291,8 +339,8 @@ class UserProductInquiryControllerTest extends ModuleTestCase
public function 권한_없는_사용자는_답변을_삭제할_수_없다(): void
{
$answeredInquiry = ProductInquiry::factory()->create([
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'is_answered' => true,
]);
@@ -309,8 +357,8 @@ class UserProductInquiryControllerTest extends ModuleTestCase
{
$manager = $this->createAdminUser(['sirsoft-ecommerce.inquiries.update']);
$answeredInquiry = ProductInquiry::factory()->create([
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'user_id' => $this->user->id,
'product_id' => $this->product->id,
'is_answered' => true,
]);
@@ -321,7 +369,7 @@ class UserProductInquiryControllerTest extends ModuleTestCase
$response->assertOk();
$this->assertDatabaseHas('ecommerce_product_inquiries', [
'id' => $answeredInquiry->id,
'id' => $answeredInquiry->id,
'is_answered' => false,
]);
}
@@ -0,0 +1,207 @@
<?php
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Security;
use App\Enums\PermissionType;
use App\Helpers\PermissionHelper;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Modules\Sirsoft\Ecommerce\Models\ExtraFeeTemplate;
use Modules\Sirsoft\Ecommerce\Models\ShippingPolicy;
use Modules\Sirsoft\Ecommerce\Services\ExtraFeeTemplateService;
use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyService;
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 서비스 계층 스코프 게이트 재적용 (KVE-2026-1919 형제)
*
* `PermissionMiddleware` 는 라우트 파라미터가 Model 로 resolve 될 때만 스코프를 검사하고,
* 아니면 "목록 엔드포인트" 로 보아 건너뛴다. 이 모듈에는 두 형태가 모두 있었다:
*
* 1. 정적 경로 — `bulk-*` 처럼 리소스 파라미터 자체가 없음
* 2. 파라미터명 불일치 — 권한은 `shippingPolicy`/`coupon` 을 가리키는데 라우트는 `{id}`
* 라 바인딩이 안 일어남. 이쪽은 **상세 경로까지** 무가드였다.
*
* 조사 시점 이 모듈 전체의 `checkScopeAccess`/`filterByScope` 호출은 **0건**이었다 —
* 미들웨어가 스킵되면 어떤 2차 방어도 없었다는 뜻이다.
*
* 대표 경로(상세 1 + 일괄 1)를 고정한다. 나머지 서비스도 같은 trait 을 쓴다.
*/
class ServiceScopeReapplyTest extends ModuleTestCase
{
/**
* 지정한 스코프로 권한을 보유한 관리자를 만듭니다.
*
* @param string $identifier 권한 식별자
* @param string|null $scope 스코프 유형 (self / role / null=전체)
* @return User 생성된 관리자
*/
private function adminWithScope(string $identifier, ?string $scope): User
{
$user = User::factory()->create();
$role = Role::create([
'identifier' => 'scoped-'.$user->id.'-'.uniqid(),
'name' => ['ko' => '스코프 관리자', 'en' => 'Scoped Admin'],
]);
$user->roles()->attach($role->id);
foreach (['admin.access', $identifier] as $key) {
$permission = Permission::firstOrCreate(
['identifier' => $key],
['name' => ['ko' => $key, 'en' => $key], 'type' => PermissionType::Admin]
);
if ($key === $identifier) {
// 스코프 대상 권한임을 명시 — 미들웨어가 상세 경로에서 쓰는 것과 같은 메타데이터
$permission->update(['resource_route_key' => 'shippingPolicy', 'owner_key' => 'created_by']);
}
$role->permissions()->syncWithoutDetaching([
$permission->id => ['scope_type' => $key === $identifier ? $scope : null],
]);
}
// PermissionHelper 정적 캐시 초기화 (다른 액터의 판정이 남지 않도록)
$reflection = new \ReflectionClass(PermissionHelper::class);
$prop = $reflection->getProperty('permissionCache');
$prop->setAccessible(true);
$prop->setValue(null, []);
return $user->fresh();
}
/**
* @scenario route_shape=param_name_mismatch
*
* @effects detail_route_reapplies_scope_gate_when_binding_absent
*/
public function test_self_scoped_admin_cannot_update_others_shipping_policy(): void
{
$actor = $this->adminWithScope('sirsoft-ecommerce.shipping-policies.update', 'self');
$owner = User::factory()->create();
$this->actingAs($actor);
$policy = $this->makePolicy($owner->id);
$this->expectException(AccessDeniedHttpException::class);
app(ShippingPolicyService::class)->update($policy, ['name' => ['ko' => '변경', 'en' => 'Changed']]);
}
/**
* (과차단 회귀) 자기 소유 대상은 그대로 수정할 수 있어야 한다.
*
* @scenario route_shape=param_name_mismatch
*
* @effects detail_route_allows_in_scope_target
*/
public function test_self_scoped_admin_can_update_own_shipping_policy(): void
{
$actor = $this->adminWithScope('sirsoft-ecommerce.shipping-policies.update', 'self');
$this->actingAs($actor);
$policy = $this->makePolicy($actor->id);
$updated = app(ShippingPolicyService::class)->update($policy, [
'name' => ['ko' => '변경', 'en' => 'Changed'],
]);
$this->assertNotNull($updated, '자기 소유 정책은 수정할 수 있어야 합니다');
}
/**
* @scenario route_shape=static_bulk
*
* @effects static_bulk_route_reapplies_scope_gate
*/
public function test_self_scoped_admin_cannot_bulk_toggle_others_extra_fee_templates(): void
{
$actor = $this->adminWithScope('sirsoft-ecommerce.shipping-policies.update', 'self');
$owner = User::factory()->create();
$this->actingAs($actor);
$mine = $this->makeTemplate($actor->id, '63001');
$theirs = $this->makeTemplate($owner->id, '63002');
try {
app(ExtraFeeTemplateService::class)->bulkToggleActive([$mine->id, $theirs->id], false);
$this->fail('스코프 밖 대상이 섞이면 거부되어야 합니다');
} catch (AccessDeniedHttpException) {
// 기대 경로
}
// 전량 거부 — 내 것도 바뀌지 않아야 한다.
$this->assertTrue((bool) $mine->fresh()->is_active, '거부된 일괄 요청은 아무것도 바꾸지 않아야 합니다');
$this->assertTrue((bool) $theirs->fresh()->is_active);
}
/**
* (과차단 회귀) 글로벌 스코프 액터의 일괄 작업은 종전대로 동작해야 한다.
*
* @scenario route_shape=static_bulk
*
* @effects static_bulk_route_allows_global_scoped_actor
*/
public function test_global_scoped_admin_can_bulk_toggle_any_extra_fee_template(): void
{
$actor = $this->adminWithScope('sirsoft-ecommerce.shipping-policies.update', null);
$owner = User::factory()->create();
$this->actingAs($actor);
$theirs = $this->makeTemplate($owner->id, '63003');
$count = app(ExtraFeeTemplateService::class)->bulkToggleActive([$theirs->id], false);
$this->assertSame(1, $count);
$this->assertFalse((bool) $theirs->fresh()->is_active);
}
/**
* 소유자를 지정해 배송정책을 만듭니다 (팩토리 부재 — 기존 테스트와 같은 직접 생성).
*
* @param int $ownerId 소유자 ID
* @return ShippingPolicy 생성된 배송정책
*/
private function makePolicy(int $ownerId): ShippingPolicy
{
$policy = ShippingPolicy::create([
'name' => ['ko' => '정책', 'en' => 'Policy'],
'is_active' => true,
'is_default' => false,
'sort_order' => 1,
'created_by' => $ownerId,
]);
$policy->countrySettings()->create([
'country_code' => 'KR',
'shipping_method' => 'parcel',
'currency_code' => 'KRW',
'charge_policy' => 'fixed',
'base_fee' => 3000,
]);
return $policy;
}
/**
* 소유자를 지정해 추가배송비 템플릿을 만듭니다.
*
* @param int $ownerId 소유자 ID
* @param string $zipcode 우편번호 (유니크 충돌 회피용)
* @return ExtraFeeTemplate 생성된 템플릿
*/
private function makeTemplate(int $ownerId, string $zipcode): ExtraFeeTemplate
{
return ExtraFeeTemplate::create([
'zipcode' => $zipcode,
'fee' => 3000.00,
'region' => '제주도',
'description' => '제주도 추가배송비',
'is_active' => true,
'created_by' => $ownerId,
]);
}
}
@@ -22,11 +22,12 @@
* 태그로 찾지 말고 `data-testid` (`pg-select-{id}` / `pg-locked-badge-{id}` / `pg-not-required-{id}`)
* 로 분기 결과를 조회한다 — 컴포넌트 내부 구현이 바뀌어도 이 spec 은 유지된다.
*
* @scenario extension_payment_method method_kind=extension × capability_declared=declared × capability=pg_locked
* @effects admin_shows_pg_locked_badge,
* admin_hides_pg_select_for_locked,
* admin_shows_pg_select_for_unlocked,
* saved_null_pg_provider_self_healed
* 축 요약(마커 아님 — 평문): method_kind=extension, capability_declared=declared,
* capability=pg_locked. 요약을 시나리오 축 마커로 적으면 마커 파서가
* 쉼표로만 축을 분리하므로 `×` 표기는 첫 축만, 그것도 오염된 형태로 집계된다 — 실재하지 않는
* 조합이 커버된 것처럼 쌓이는 방향이라 요약은 평문으로 둔다. 실제 커버는 각 test 의 라인 마커가 담당한다.
*
* 효과 요약(마커 아님 — 평문): admin_shows_pg_locked_badge, admin_hides_pg_select_for_locked, admin_shows_pg_select_for_unlocked, saved_null_pg_provider_self_healed.
*/
import { test, expect, authenticatePage } from '../../fixtures/ecommerce-auth';
import type { Page } from '@playwright/test';
@@ -1,12 +1,11 @@
/**
* 관리자 배송정책 — 계산 API 연동 고급 설정 (skeleton, placeholder).
*
* @scenario http_method GET POST × auth_type none bearer custom_header × response_type json text
* @effects method_get_sends_query_string, bearer_attaches_authorization_header,
* custom_header_requires_header_name, field_map_renames_request_keys,
* json_nested_path_extracted, text_currency_stripped_to_number,
* auth_token_masked_in_response, test_call_returns_preview_and_fee,
* options_from_backend_enum_ssot
* 축 요약(마커 아님 — 평문): http_method=GET|POST, auth_type=none|bearer|custom_header,
* response_type=json|text. 요약을 시나리오 축 마커로 적으면 파서가 `=` 없는 토큰을 버려 빈 조합
* `{}` 이 되고, 축이 0개인 매니페스트가 생기면 어떤 케이스든 커버된 것으로 오집계될 수 있다.
*
* 효과 요약(마커 아님 — 평문): method_get_sends_query_string, bearer_attaches_authorization_header, custom_header_requires_header_name, field_map_renames_request_keys, json_nested_path_extracted, text_currency_stripped_to_number, auth_token_masked_in_response, test_call_returns_preview_and_fee, options_from_backend_enum_ssot.
*
* 배경(MP12): 배송정책 부과정책 "외부 API 연동" 선택 시 HTTP 메서드/인증/필드매핑/응답형식을
* 설정하고, "테스트 호출" 버튼으로 실제 API 응답·추출 배송비를 미리볼 수 있다. 인증 토큰은
@@ -34,6 +33,7 @@ import { test, expect, authenticatePage } from '../../fixtures/ecommerce-auth';
const NEW_POLICY_URL = '/admin/ecommerce/shipping-policies/create';
test.describe.skip('관리자 배송정책 — 계산 API 연동 고급 설정 (placeholder — data-testid 보강 후 활성화)', () => {
/** @effects custom_header_requires_header_name */
test('인증 custom_header 선택 시 헤더명 입력란이 노출된다', async ({ page, settingsToken }) => {
await authenticatePage(page, settingsToken);
await page.goto(NEW_POLICY_URL);
@@ -45,6 +45,7 @@ test.describe.skip('관리자 배송정책 — 계산 API 연동 고급 설정 (
await expect(page.getByTestId('api-auth-token')).toBeVisible();
});
/** @effects options_from_backend_enum_ssot */
test('응답 형식 text 선택 시 응답 경로 입력란이 숨겨진다', async ({ page, settingsToken }) => {
await authenticatePage(page, settingsToken);
await page.goto(NEW_POLICY_URL);
@@ -55,6 +56,7 @@ test.describe.skip('관리자 배송정책 — 계산 API 연동 고급 설정 (
await expect(page.getByTestId('api-response-path')).not.toBeVisible();
});
/** @effects method_get_sends_query_string, test_call_returns_preview_and_fee */
test('테스트 호출 → 요청 메서드 + 응답 상태 + 추출 배송비가 표시된다', async ({ page, settingsToken }) => {
await authenticatePage(page, settingsToken);
await page.goto(NEW_POLICY_URL);
@@ -19,11 +19,11 @@
* 폴백)만 골라 보면 통과해 버린다. **ko 값과 다른 국가가 하나라도 있는지** 먼저 확인한
* 뒤, 그 국가에서 화면값 === en 값을 단언한다.
*
* @scenario shipping_country_i18n locale=en|ja × surface=settings_list|add_form
* @effects country_names_localized_by_active_locale,
* country_names_not_pinned_to_ko,
* add_form_inputs_follow_installed_locales,
* add_button_enabled_by_any_locale_name
* 축 요약(마커 아님 — 평문): locale=en|ja, surface=settings_list|add_form. 요약을 시나리오 축 마커
* 로 적으면 파서가 쉼표로만 축을 분리하므로 `×` 표기는 첫 축만, 그것도 나머지 전부를 값으로
* 삼킨 형태로 집계된다. 실제 커버는 각 test 의 라인 마커가 담당한다.
*
* 효과 요약(마커 아님 — 평문): country_names_localized_by_active_locale, country_names_not_pinned_to_ko, add_form_inputs_follow_installed_locales, add_button_enabled_by_any_locale_name.
*/
import { test, expect, authenticatePage } from '../../fixtures/ecommerce-auth';
import type { Page } from '@playwright/test';
@@ -13,8 +13,11 @@ use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
/**
* OrderPayment 모델 테스트
*
* @scenario extension_payment_method method_kind=extension × capability_declared=declared × capability=refund_method
* @effects extension_id_persisted_as_is, builtin_capability_unchanged, refund_method_is_pg
* 축 요약(마커 아님 — 평문): method_kind=extension, capability_declared=declared,
* capability=refund_method. 요약을 시나리오 축 마커로 적으면 파서가 쉼표로만 축을 분리하므로 `×`
* 표기는 실재하지 않는 조합 1건으로 집계된다(커버리지를 부풀리는 방향).
*
* 효과 요약(마커 아님 — 평문): extension_id_persisted_as_is, builtin_capability_unchanged, refund_method_is_pg.
*/
class OrderPaymentTest extends ModuleTestCase
{
@@ -42,6 +45,9 @@ class OrderPaymentTest extends ModuleTestCase
$this->assertEquals($order->id, $payment->order->id);
}
/**
* @effects builtin_capability_unchanged
*/
public function test_order_payment_method_is_stored_as_plain_string(): void
{
// payment_method 는 enum 캐스트를 두지 않는다 (#475) — PG 플러그인이 등록하는
@@ -54,6 +60,9 @@ class OrderPaymentTest extends ModuleTestCase
$this->assertTrue($payment->isCardPayment());
}
/**
* @effects extension_id_persisted_as_is
*/
public function test_order_payment_accepts_extension_payment_method_id(): void
{
// 확장 결제수단 ID 를 1급 시민으로 저장할 수 있어야 한다 (캐스트가 있으면 ValueError).
@@ -164,7 +164,7 @@ class EcommerceSettingsServiceCurrencyTombstoneTest extends ModuleTestCase
$this->assertArrayHasKey('removed_default_currencies', $saved, '삭제 기록이 저장되지 않았습니다.');
$this->assertSame(['JPY', 'CNY', 'EUR'], $saved['removed_default_currencies']);
// 비연속 키가 JSON 객체로 직렬화되지 않도록 array_values 재정렬 (CLAUDE.md 규칙)
// 비연속 키가 JSON 객체로 직렬화되지 않도록 array_values 재정렬 (코딩 규약)
$this->assertSame([0, 1, 2], array_keys($saved['removed_default_currencies']));
}
@@ -408,11 +408,13 @@ class OrderServiceTest extends ModuleTestCase
->once()
->andReturn(5);
// 전이 알림 발화용 — 스냅샷이 비어(이전 상태 null) 전 주문이 전이 대상 → fresh 조회
// 전이 알림 발화용(fresh 조회) + 서비스 진입부의 스코프 재적용 조회 두 곳에서 호출된다.
// 일괄 라우트는 라우트 모델이 없어 미들웨어 스코프 검사가 스킵되므로 서비스가 재적용한다.
// 상한을 없애지 않고 2회로 좁힌다 — 상한을 지우면 중복 조회 회귀를 못 잡는다.
$this->mockRepository
->shouldReceive('findByIdsKeyed')
->with($ids)
->once()
->twice()
->andReturn(new Collection);
// When: bulkUpdate 호출
@@ -446,6 +448,13 @@ class OrderServiceTest extends ModuleTestCase
->once()
->andReturn(2);
// 서비스 진입부의 스코프 재적용 조회 — 일괄 라우트는 라우트 모델이 없어
// PermissionMiddleware 의 스코프 검사가 스킵되므로 서비스가 재적용한다.
$this->mockRepository
->shouldReceive('findByIdsKeyed')
->once()
->andReturn(new Collection);
// When: bulkUpdate 호출
$result = $this->service->bulkUpdate($data);
@@ -633,7 +642,8 @@ class OrderServiceTest extends ModuleTestCase
$this->mockRepository->shouldReceive('getSnapshotsByIds')->with($ids)->once()->andReturn([]);
$this->mockRepository->shouldReceive('bulkUpdateStatus')->once()->andReturn(3);
$this->mockRepository->shouldReceive('bulkUpdateOptionStatus')->once()->andReturn(3);
$this->mockRepository->shouldReceive('findByIdsKeyed')->once()->andReturn(new Collection);
// 스코프 재적용 조회 + 전이 알림 fresh 조회 = 2회 (상한 유지)
$this->mockRepository->shouldReceive('findByIdsKeyed')->twice()->andReturn(new Collection);
$approveCount = 0;
$cb = function () use (&$approveCount) {
@@ -3,6 +3,7 @@
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
use App\Contracts\Extension\StorageInterface;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Queue;
@@ -432,6 +433,14 @@ class ProductReviewServiceTest extends ModuleTestCase
#[Test]
public function test_bulk_update_status_delegates_to_repository(): void
{
// 일괄 라우트는 라우트 모델이 없어 PermissionMiddleware 의 스코프 검사가 스킵되므로
// 서비스가 대상을 조회해 스코프를 재적용한다 — 순수 위임이 아니다.
$this->repository
->shouldReceive('getByIdsWithImages')
->with([1, 2, 3])
->once()
->andReturn(new EloquentCollection);
$this->repository
->shouldReceive('bulkUpdateStatus')
->with([1, 2, 3], 'hidden')
@@ -0,0 +1,35 @@
feature: 서비스 계층 스코프 게이트 재적용 (KVE-2026-1919 형제)
description: |
`PermissionMiddleware` 는 라우트 파라미터가 Model 로 resolve 될 때만 스코프를 검사하고,
아니면 "목록 엔드포인트" 로 보아 건너뛴다. 이 모듈에는 그 스킵이 성립하는 두 형태가
모두 있었고, 조사 시점 모듈 전체의 `checkScopeAccess`/`filterByScope` 호출은 0건이었다 —
미들웨어가 스킵되면 어떤 2차 방어도 없었다는 뜻이다.
축은 그 **우회 메커니즘**이다. 두 형태는 노출 범위가 다르므로 한쪽만 검증하면 나머지가
무보호로 남는다:
- static_bulk — `bulk-*` 처럼 리소스 파라미터 자체가 없는 정적 경로. 일괄 경로만 뚫린다.
- param_name_mismatch — 권한의 `resource_route_key` 는 `shippingPolicy`/`coupon` 인데
라우트는 `{id}` 라 바인딩이 일어나지 않는다. 이쪽은 **상세 경로까지** 무가드다.
공용 trait `ReappliesPermissionScope` 가 두 형태 모두에서 코어 SSoT
(`PermissionHelper::checkScopeAccess` / `filterByScope`)에 판정을 위임한다. 대표 경로
(상세 1 + 일괄 1)를 고정하며, 나머지 서비스도 같은 trait 을 쓴다.
각 형태마다 **차단 축과 과차단 회귀 축을 짝으로** 둔다 — 차단만 단언하면 가드가 정상
대상까지 막는 회귀가 green 으로 통과한다.
axes:
route_shape: [static_bulk, param_name_mismatch]
effects:
# param_name_mismatch — 상세 경로
- detail_route_reapplies_scope_gate_when_binding_absent
- detail_route_allows_in_scope_target
# static_bulk — 일괄 경로
- static_bulk_route_reapplies_scope_gate
- static_bulk_route_allows_global_scoped_actor
test_files:
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Security/ServiceScopeReapplyTest.php
@@ -6,6 +6,11 @@
## [1.0.3] - 2026-08-13
### Security
- 미발행(초안) 페이지에 붙은 이미지 첨부의 미리보기가 주소만 알면 누구에게나 열리던 문제를 수정했습니다. 다운로드는 이미 발행 상태를 확인하고 있었지만 미리보기는 확인하지 않아, 발행 전 콘텐츠의 이미지가 새어 나갈 수 있었습니다. 이제 미리보기도 다운로드와 같은 기준을 적용해, 발행된 페이지의 첨부는 누구나, 미발행 페이지의 첨부는 페이지 조회 권한이 있는 관리자만 미리볼 수 있습니다. 편집 중인 초안의 썸네일은 편집 권한이 있는 관리자에게 종전처럼 정상 표시됩니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-1914)
- 페이지 일괄 발행/발행취소와 첨부파일 삭제·순서 변경에 담당 범위 제한을 적용했습니다. 페이지를 하나씩 여는 화면에는 이 확인이 있었지만 목록에서 여러 건을 한 번에 처리하는 경로와 첨부 관리 경로에는 없어, "본인이 만든 페이지만" 으로 범위를 좁혀 위임받은 관리자가 담당 밖 페이지까지 발행 상태를 바꾸거나 첨부를 지울 수 있었습니다. 이제 대상마다 같은 기준으로 확인하며, 범위 밖 대상이 섞이면 요청 전체를 거부하고 아무것도 변경하지 않습니다. 범위 제한 없이 위임받은 관리자의 작업은 종전처럼 정상 동작합니다. (KVE-2026-1919)
### Changed
- 첨부 개수 상한 초과 안내 문구를 만드는 시점이 응답을 만드는 시점과 어긋나 있던 것을 맞췄습니다. 표시되는 문구와 상태는 종전과 동일합니다.
@@ -1230,11 +1230,11 @@ Content-Disposition: inline
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 404 | Not Found | 해시에 해당하는 첨부가 없는 경우(`첨부파일을 찾을 수 없습니다.`), 첨부가 이미지가 아니거나 스토리지에 실제 파일이 없는 경우(`첨부파일이 스토리지에 존재하지 않습니다.`). 미리보기는 발행/미발행과 무관하게 공개 서빙되므로 권한에 의한 404 는 없습니다 |
| 404 | Not Found | 해시에 해당하는 첨부가 없는 경우(`첨부파일을 찾을 수 없습니다.`), 미발행 페이지의 첨부를 `sirsoft-page.pages.read` 권한 없이 요청한 경우(존재를 숨기기 위해 동일하게 404), 첨부가 이미지가 아니거나 스토리지에 실제 파일이 없는 경우(`첨부파일이 스토리지에 존재하지 않습니다.`) |
<!-- @generated:end -->
**설명** 이미지 첨부 썸네일을 인라인으로 미리봅니다(해시 기반, 12자). 썸네일 `<img>` 는 토큰을 실을 수 없으므로 발행/미발행과 무관하게 공개 서빙합니다. 미발행 콘텐츠의 썸네일은 해시를 보유해야만 조회 가능(비추측성)하며, 실제 파일 다운로드는 `download` 의 권한 게이트로 보호됩니다. 이미지 스트리밍 응답이므로 실측 대상이 아닙니다.
**설명** 이미지 첨부 썸네일을 인라인으로 미리봅니다(해시 기반, 12자). `download` 와 동일한 발행상태 게이트를 적용합니다 — 발행된 페이지의 썸네일은 누구나, 미발행 페이지의 썸네일은 `sirsoft-page.pages.read` 권한 관리자만 미리볼 수 있습니다. 편집 중인 초안(미발행)의 `<img>` 썸네일은 편집 권한을 가진 관리자에게 정상 노출되고, 무인가 사용자에게는 미발행 썸네일이 차단됩니다. 이미지 스트리밍 응답이므로 실측 대상이 아닙니다.
### GET /api/modules/sirsoft-page/pages/{slug}
@@ -14,8 +14,11 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
*
* 첨부파일 서빙(다운로드/미리보기)을 처리합니다. 썸네일 <img>·다운로드는 브라우저 직접
* GET 이라 토큰을 실을 수 없으므로 공개 hash 라우트로 단일화합니다.
* - 미리보기(썸네일): 공개 서빙 (미발행 콘텐츠도 hash 보유 시 조회 가능 — 트레이드오프 수용)
* - 미리보기(썸네일): 발행 첨부는 누구나, 미발행 첨부는 pages.read 관리자만 (download 와 동일 게이트)
* - 다운로드: 발행 첨부는 누구나, 미발행 첨부는 pages.read 관리자만 (파일 보호)
*
* preview 와 download 는 동일한 발행상태 게이트를 공유한다 — 한쪽만 열려 있으면
* 미발행 콘텐츠가 무인가로 새는 경로가 남는다(preview↔download 정합).
*/
class PublicPageAttachmentController extends PublicBaseController
{
@@ -60,20 +63,34 @@ class PublicPageAttachmentController extends PublicBaseController
/**
* 이미지 첨부파일을 미리봅니다 (해시 기반, inline).
*
* 썸네일 <img> 는 토큰을 실을 수 없으므로 발행/미발행 무관 공개 서빙합니다.
* 미발행 콘텐츠의 썸네일은 hash 를 보유해야만 조회 가능하며(비추측성), 파일
* 다운로드는 download() 의 권한 게이트로 보호됩니다.
* 발행된 페이지의 썸네일은 누구나, 미발행 페이지의 썸네일은 페이지 조회 권한
* (sirsoft-page.pages.read) 관리자만 미리볼 수 있습니다(download 와 동일 게이트).
* 편집 중인 초안(미발행)의 <img> 썸네일은 편집 권한을 가진 관리자가 보므로
* 정상 노출되며, 무인가 사용자에게만 미발행 썸네일이 차단됩니다.
*
* @param Request $request HTTP 요청 객체 (미리보기 권한 판정용)
* @param string $hash 첨부파일 해시 (12자)
* @return StreamedResponse|JsonResponse 파일 스트리밍 응답 또는 오류
*/
public function preview(string $hash): StreamedResponse|JsonResponse
// audit:allow controller-base-request-injection reason: GET 이미지 서빙. 인증 사용자만 read-only 참조($request->user())해 미발행 첨부 미리보기 권한을 판정. 검증할 body 없음(hash 는 라우트 파라미터)
public function preview(Request $request, string $hash): StreamedResponse|JsonResponse
{
$attachment = $this->attachmentService->getByHash($hash);
if (! $attachment) {
return $this->notFound('sirsoft-page::messages.attachment.not_found');
}
// 미발행 페이지의 첨부는 페이지 조회 권한 관리자만 미리보기 가능 (download 와 동일 게이트)
$published = $attachment->page && $attachment->page->published;
$canReadUnpublished = $request->user()?->hasPermission(
'sirsoft-page.pages.read',
PermissionType::Admin
) ?? false;
if (! $published && ! $canReadUnpublished) {
return $this->notFound('sirsoft-page::messages.attachment.not_found');
}
$response = $this->attachmentService->preview($attachment);
return $response ?: $this->error('sirsoft-page::messages.attachment.file_not_found', 404);
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Page\Services;
use App\Contracts\Extension\StorageInterface;
use App\Extension\HookManager;
use App\Helpers\PermissionHelper;
use App\Support\ImageResizer;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@@ -14,6 +15,7 @@ use Modules\Sirsoft\Page\Exceptions\AttachmentLimitExceededException;
use Modules\Sirsoft\Page\Models\PageAttachment;
use Modules\Sirsoft\Page\Repositories\Contracts\PageAttachmentRepositoryInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* 페이지 첨부파일 서비스
@@ -191,6 +193,8 @@ class PageAttachmentService
*/
public function deleteAttachment(PageAttachment $attachment): bool
{
$this->assertPageScope($attachment);
HookManager::doAction('sirsoft-page.attachment.before_delete', $attachment);
// 물리 파일 삭제
@@ -212,6 +216,8 @@ class PageAttachmentService
*/
public function reorder(array $orders): bool
{
$this->assertReorderScope($orders);
HookManager::doAction('sirsoft-page.attachment.before_reorder', $orders);
$result = $this->attachmentRepository->reorder($orders);
@@ -221,6 +227,52 @@ class PageAttachmentService
return $result;
}
/**
* 첨부의 부모 페이지가 액터의 스코프 안에 있는지 검사합니다.
*
* 첨부 라우트는 `{id}`(정수)로 선언돼 있어 라우트 모델 바인딩이 일어나지 않고,
* 순서 변경은 아예 정적 경로다. 두 경우 모두 PermissionMiddleware 의 스코프 검사가
* 스킵되므로(모델이 resolve 되지 않으면 목록 엔드포인트로 간주) 서비스가 재적용한다.
* 스코프 대상은 첨부가 아니라 **부모 페이지**다 — `sirsoft-page.pages.update` 의
* owner_key 가 페이지의 `created_by` 이기 때문이다.
*
* @param PageAttachment $attachment 대상 첨부
*
* @throws AccessDeniedHttpException 부모 페이지가 스코프 밖인 경우
*/
private function assertPageScope(PageAttachment $attachment): void
{
$page = $attachment->page;
// 부모를 못 읽으면 막는다(fail-closed) — 첨부에 page_id 가 있는데 페이지를 못 찾는
// 것은 정상 상태가 아니고, 통과시키면 게이트가 있어야 할 자리가 비어 버린다.
if (! $page || ! PermissionHelper::checkScopeAccess($page, 'sirsoft-page.pages.update')) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
}
/**
* 순서 변경 대상 첨부 전체가 액터의 스코프 안에 있는지 검사합니다.
*
* 순서는 집합 전체에 대한 하나의 배열이라 일부만 반영하면 나머지와 어긋난다 —
* 걸러내지 않고 전량 거부한다(코어 첨부/메뉴 순서 변경과 같은 의미론).
*
* @param array<int, array{id: int, order: int}> $orders 순서 데이터
*
* @throws AccessDeniedHttpException 스코프 밖 첨부가 하나라도 포함된 경우
*/
private function assertReorderScope(array $orders): void
{
$ids = array_values(array_unique(array_filter(
array_map(static fn ($item): int => (int) ($item['id'] ?? 0), $orders)
)));
foreach ($ids as $id) {
// 존재하지 않는 id 는 findOrFail 이 404 로 끊는다 — 통과시키면 안 된다.
$this->assertPageScope($this->attachmentRepository->findOrFail($id));
}
}
/**
* 해시로 첨부파일을 조회합니다.
*
@@ -246,6 +246,15 @@ class PageService
// 존재하지 않는 페이지가 섞이면 예외 → 트랜잭션 전체 롤백 (all-or-nothing)
$page = $this->pageRepository->findOrFail((int) $id);
// 일괄 라우트(`PATCH admin/pages/bulk-publish`)에는 `{page}` 파라미터가 없어
// PermissionMiddleware 의 스코프 검사가 통째로 스킵된다. 단건 경로
// (updatePage/deletePage 등)는 전부 이 검사를 하는데 일괄만 비어 있으면
// 그 경로가 우회로다 — 같은 판정을 여기서 재적용한다.
// 예외는 위 findOrFail 과 같은 all-or-nothing 롤백을 탄다.
if (! PermissionHelper::checkScopeAccess($page, 'sirsoft-page.pages.update')) {
throw new AccessDeniedHttpException(__('auth.scope_denied'));
}
HookManager::doAction('sirsoft-page.page.before_publish', $page, $published);
$updateData = [
@@ -127,7 +127,7 @@ Route::prefix('pages')->middleware(['optional.sanctum', 'throttle:600,1'])->name
->where('hash', '[a-zA-Z0-9]{12}')
->name('attachment.download');
// 첨부 이미지 미리보기 (공개 - 토큰 없는 <img> 직접 GET 을 위해 권한 체크 없이 이미지만 제공)
// 첨부 이미지 미리보기 (해시 기반, 발행 상태에 따라 컨트롤러에서 접근 제어 — download 와 동일 게이트)
Route::get('/attachment/{hash}/preview', [PublicPageAttachmentController::class, 'preview'])
->where('hash', '[a-zA-Z0-9]{12}')
->name('attachment.preview');
@@ -0,0 +1,198 @@
<?php
namespace Modules\Sirsoft\Page\Tests\Feature\User;
// FeatureTestCase를 수동으로 require (autoload 전에 로드 필요)
require_once __DIR__.'/../../FeatureTestCase.php';
use App\Models\User;
use Mockery;
use Modules\Sirsoft\Page\Models\Page;
use Modules\Sirsoft\Page\Models\PageAttachment;
use Modules\Sirsoft\Page\Services\PageAttachmentService;
use Modules\Sirsoft\Page\Tests\FeatureTestCase;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 공개 페이지 첨부 미리보기/다운로드 접근 게이트 테스트 (KVE-2026-1914 A-6 S-1)
*
* preview() 는 과거 발행상태 무관 공개 서빙이라, 미발행(초안) 페이지의 첨부 썸네일을
* hash 만 있으면 무인가로 볼 수 있었다(preview↔download 게이트 불일치). 이 클래스는
* preview 가 download 와 동일하게 "발행 첨부는 공개, 미발행 첨부는 pages.read 관리자만"
* 게이트를 적용하는지 실제 HTTP 요청으로 고정한다.
*
* 게이트 통과/차단을 응답코드로 명확히 구분하기 위해 Service 를 모킹한다 —
* 게이트 통과 시 200(스트리밍), 게이트 차단 시 컨트롤러가 Service 호출 전에 404 를 낸다.
*/
class PublicPageAttachmentAccessTest extends FeatureTestCase
{
private const BASE = '/api/modules/sirsoft-page/pages/attachment';
protected function tearDown(): void
{
Page::where('slug', 'like', 'attach-access-%')->forceDelete();
Mockery::close();
parent::tearDown();
}
/**
* Service 를 모킹해 게이트 통과 시 200 을 반환하도록 만든다.
*
* @param PageAttachment $attachment getByHash 가 반환할 첨부
*/
private function mockServicePassThrough(PageAttachment $attachment): void
{
$svc = Mockery::mock(PageAttachmentService::class);
$svc->shouldReceive('getByHash')->andReturn($attachment);
$svc->shouldReceive('preview')->andReturn(new StreamedResponse(fn () => null, 200));
$svc->shouldReceive('download')->andReturn(new StreamedResponse(fn () => null, 200));
$this->app->instance(PageAttachmentService::class, $svc);
}
/**
* 첨부를 만든다.
*
* @param bool $published 부모 페이지 발행 여부
* @param string $slug 페이지 슬러그
* @return PageAttachment 생성된 첨부
*/
private function makeAttachment(bool $published, string $slug): PageAttachment
{
$pageFactory = Page::factory()->state(['slug' => $slug]);
if ($published) {
$pageFactory = $pageFactory->published();
}
$page = $pageFactory->create();
return PageAttachment::factory()->image()->create(['page_id' => $page->id]);
}
// ── preview 게이트 (S-1 핵심) ──────────────────────────
/**
* 미발행 페이지 첨부 미리보기는 비인가 사용자에게 404 로 차단된다 (S-1 수정 핵심)
*
* @scenario resource=page_attachment, parent_state=restricted
*
* @effects unpublished_page_attachment_preview_blocked_for_guest
*/
public function test_unpublished_preview_blocked_for_anonymous(): void
{
$attachment = $this->makeAttachment(false, 'attach-access-draft');
$this->mockServicePassThrough($attachment);
$this->getJson(self::BASE.'/'.$attachment->hash.'/preview')
->assertStatus(404);
}
/**
* 미발행 페이지 첨부 미리보기는 권한 없는 로그인 사용자에게도 404 로 차단된다
*
* @scenario resource=page_attachment, parent_state=restricted
*
* @effects unpublished_page_attachment_preview_blocked_without_permission
*/
public function test_unpublished_preview_blocked_for_user_without_permission(): void
{
$attachment = $this->makeAttachment(false, 'attach-access-draft-user');
$this->mockServicePassThrough($attachment);
$user = User::factory()->create();
$this->actingAs($user)
->getJson(self::BASE.'/'.$attachment->hash.'/preview')
->assertStatus(404);
}
/**
* 미발행 페이지 첨부 미리보기는 pages.read 관리자에게 허용된다 (초안 편집 썸네일 회귀 방지)
*
* @scenario resource=page_attachment, parent_state=restricted
*
* @effects unpublished_page_attachment_preview_allowed_with_pages_read
*/
public function test_unpublished_preview_allowed_for_admin_with_pages_read(): void
{
$attachment = $this->makeAttachment(false, 'attach-access-draft-admin');
$this->mockServicePassThrough($attachment);
$admin = $this->createAdminUser(['sirsoft-page.pages.read']);
$this->actingAs($admin)
->getJson(self::BASE.'/'.$attachment->hash.'/preview')
->assertStatus(200);
}
/**
* 발행된 페이지 첨부 미리보기는 비인가 사용자에게도 공개된다 (정상 흐름 회귀 방지)
*
* @scenario resource=page_attachment, parent_state=public
*
* @effects published_page_attachment_preview_still_public
*/
public function test_published_preview_allowed_for_anonymous(): void
{
$attachment = $this->makeAttachment(true, 'attach-access-live');
$this->mockServicePassThrough($attachment);
$this->getJson(self::BASE.'/'.$attachment->hash.'/preview')
->assertStatus(200);
}
// ── download 게이트 (기존 동작 회귀 대조) ──────────────
/**
* 미발행 페이지 첨부 다운로드는 비인가 사용자에게 404 로 차단된다 (기존 게이트 회귀 대조)
*
* @scenario resource=page_attachment, parent_state=restricted
*
* @effects unpublished_page_attachment_download_blocked_for_guest
*/
public function test_unpublished_download_blocked_for_anonymous(): void
{
$attachment = $this->makeAttachment(false, 'attach-access-dl-draft');
$this->mockServicePassThrough($attachment);
$this->getJson(self::BASE.'/'.$attachment->hash)
->assertStatus(404);
}
/**
* 미발행 페이지 첨부 다운로드는 pages.read 관리자에게 허용된다.
*
* preview 축은 4건(게스트/무권한 회원/관리자/발행글)인데 download 축은 차단 1건뿐이라
* 두 경로의 커버리지 강도가 갈려 있었다. 게이트를 조일 때 download 만 과차단으로
* 회귀해도 스위트가 green 이 되므로 허용 축을 함께 고정한다.
*
* @scenario resource=page_attachment, parent_state=restricted
*
* @effects unpublished_page_attachment_download_allowed_with_pages_read
*/
public function test_unpublished_download_allowed_for_admin_with_pages_read(): void
{
$attachment = $this->makeAttachment(false, 'attach-access-dl-draft-admin');
$this->mockServicePassThrough($attachment);
$admin = $this->createAdminUser(['sirsoft-page.pages.read']);
$this->actingAs($admin)
->getJson(self::BASE.'/'.$attachment->hash)
->assertStatus(200);
}
/**
* 발행된 페이지 첨부 다운로드는 비인가 사용자에게도 공개된다 (정상 흐름 회귀 방지).
*
* @scenario resource=page_attachment, parent_state=public
*
* @effects published_page_attachment_download_still_public
*/
public function test_published_download_allowed_for_anonymous(): void
{
$attachment = $this->makeAttachment(true, 'attach-access-dl-live');
$this->mockServicePassThrough($attachment);
$this->getJson(self::BASE.'/'.$attachment->hash)
->assertStatus(200);
}
}
@@ -561,6 +561,67 @@ class PageServiceTest extends ModuleTestCase
$this->service->restoreVersion($page, $version->id);
}
/**
* 일괄 발행 경로도 단건 경로와 같은 스코프 게이트를 적용하는지 확인
*
* `PATCH admin/pages/bulk-publish` 에는 `{page}` 파라미터가 없어 PermissionMiddleware 의
* 스코프 검사가 통째로 스킵된다. 위 단건 경로 5곳은 전부 검사하는데 일괄만 비어 있으면
* 그 경로가 우회로가 된다.
*/
public function test_bulk_change_publish_status_throws_exception_for_scope_denied(): void
{
$scopeUser = $this->setupScopeUser(ScopeType::Self);
Auth::setUser($scopeUser);
$this->actingAs($scopeUser);
$mine = Page::factory()->create([
'slug' => 'test-svc-bulk-mine',
'published' => false,
'created_by' => $scopeUser->id,
'updated_by' => $scopeUser->id,
]);
$theirs = Page::factory()->create([
'slug' => 'test-svc-bulk-theirs',
'published' => false,
'created_by' => $this->adminUser->id,
'updated_by' => $this->adminUser->id,
]);
try {
$this->service->bulkChangePublishStatus([$mine->id, $theirs->id], true);
$this->fail('스코프 밖 페이지가 섞이면 거부되어야 합니다');
} catch (AccessDeniedHttpException) {
// 기대 경로
}
// all-or-nothing — 내 페이지도 발행되지 않아야 한다(트랜잭션 롤백).
$this->assertFalse($mine->fresh()->published, '거부된 일괄 요청은 아무것도 바꾸지 않아야 합니다');
$this->assertFalse($theirs->fresh()->published);
}
/**
* (과차단 회귀) 자기 소유 페이지만 넘기면 일괄 발행이 정상 동작한다
*/
public function test_bulk_change_publish_status_allows_own_pages(): void
{
$scopeUser = $this->setupScopeUser(ScopeType::Self);
Auth::setUser($scopeUser);
$this->actingAs($scopeUser);
$mine = Page::factory()->create([
'slug' => 'test-svc-bulk-own',
'published' => false,
'created_by' => $scopeUser->id,
'updated_by' => $scopeUser->id,
]);
$count = $this->service->bulkChangePublishStatus([$mine->id], true);
$this->assertSame(1, $count);
$this->assertTrue($mine->fresh()->published);
}
// ─── 헬퍼 ────────────────────────────────────────
/**