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:
1 parent
cd84b63d2b
commit
71abdeaf60
249 files changed
+14354
-1134
No files matched your search
@@ -40,6 +40,17 @@ interface MenuRepositoryInterface
|
||||
*/
|
||||
public function findById(int $id): ?Menu;
|
||||
|
||||
/**
|
||||
* 여러 ID로 메뉴를 한 번에 조회합니다.
|
||||
*
|
||||
* 정적 라우트(`PUT menus/order`)에서 스코프 게이트를 재적용할 때 대상 전체를 한 번에
|
||||
* 확인하기 위한 조회입니다. 관계는 로드하지 않습니다(소유자 판정에 불필요).
|
||||
*
|
||||
* @param array<int, int> $ids 메뉴 ID 목록
|
||||
* @return Collection 메뉴 컬렉션
|
||||
*/
|
||||
public function findByIds(array $ids): Collection;
|
||||
|
||||
/**
|
||||
* 슬러그로 메뉴를 찾습니다.
|
||||
*
|
||||
|
||||
@@ -31,6 +31,14 @@ interface PermissionRepositoryInterface
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Permission;
|
||||
|
||||
/**
|
||||
* 여러 ID로 권한을 일괄 조회합니다.
|
||||
*
|
||||
* @param array<int> $ids 권한 ID 배열
|
||||
* @return Collection 권한 컬렉션 (ID 기준)
|
||||
*/
|
||||
public function getByIds(array $ids): Collection;
|
||||
|
||||
/**
|
||||
* 새로운 권한을 생성합니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* 보호된 역할(코어/확장 소유) 수정 시도 시 발생하는 예외
|
||||
*
|
||||
* 삭제 경로에만 있던 코어/확장 소유 역할 보호를 수정·상태변경 경로까지 대칭
|
||||
* 적용하기 위한 예외입니다. 비-슈퍼관리자 액터는 `admin` 등 코어/확장 소유
|
||||
* 역할의 권한·활성상태를 변경할 수 없습니다(KVE-2026-1919).
|
||||
*/
|
||||
class CannotModifyProtectedRoleException extends Exception
|
||||
{
|
||||
/**
|
||||
* 보호된 역할 수정 시도 시 예외를 생성합니다.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('exceptions.cannot_modify_protected_role'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* 비-슈퍼관리자 액터가 슈퍼 관리자 계정/역할을 수정하려 할 때 발생하는 예외
|
||||
*
|
||||
* 삭제 경로에만 있던 슈퍼 관리자 보호 가드를 수정·상태변경·권한부여 경로까지
|
||||
* 대칭 적용하기 위한 등급 상한(rank ceiling) 위반 예외입니다.
|
||||
*/
|
||||
class CannotModifySuperAdminException extends Exception
|
||||
{
|
||||
/**
|
||||
* 슈퍼 관리자 수정 시도 시 예외를 생성합니다.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('exceptions.cannot_modify_super_admin'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* 권한 상승(escalation) 시도 시 발생하는 예외
|
||||
*
|
||||
* 비-슈퍼관리자 액터가 역할에 자신이 보유하지 않은 권한, 또는 자신의 범위(scope)보다
|
||||
* 넓은 범위의 권한을 부여하려 할 때 발생합니다(KVE-2026-1919 권한 상승 차단).
|
||||
*/
|
||||
class PermissionEscalationException extends Exception
|
||||
{
|
||||
/**
|
||||
* 권한 상승 시도 시 예외를 생성합니다.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('exceptions.cannot_grant_unheld_permission'));
|
||||
}
|
||||
}
|
||||
@@ -927,6 +927,31 @@ abstract class AbstractModule implements CacheableExtensionInterface, ModuleInte
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 신뢰하는 외부 스크립트 호스트 목록을 반환합니다.
|
||||
*
|
||||
* module.json 의 `trusted_script_hosts` 배열에서 읽습니다. 이 모듈이 레이아웃
|
||||
* `scripts[].src` 로 로드하는 외부 CDN 호스트를 선언합니다. 코어는 이 목록을
|
||||
* 집계(AbstractModule/AbstractPlugin → TrustedScriptHosts)해 런타임 스크립트 로더·
|
||||
* 저장측 검증·정적 검사가 same-origin 이 아닌 스크립트 중 **선언된 호스트만** 허용하도록
|
||||
* 합니다 (KVE-2026-1915 신뢰 출처 허용목록).
|
||||
*
|
||||
* @return array<int, string> 신뢰 호스트명 목록 (예: ['cdn.example.com'])
|
||||
*/
|
||||
public function getTrustedScriptHosts(): array
|
||||
{
|
||||
$hosts = $this->loadManifest()['trusted_script_hosts'] ?? [];
|
||||
|
||||
if (! is_array($hosts)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
array_map(fn ($host) => is_string($host) ? trim($host) : '', $hosts),
|
||||
fn ($host) => $host !== ''
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로 반환
|
||||
*
|
||||
|
||||
@@ -771,6 +771,31 @@ abstract class AbstractPlugin implements CacheableExtensionInterface, PluginInte
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 신뢰하는 외부 스크립트 호스트 목록을 반환합니다.
|
||||
*
|
||||
* plugin.json 의 `trusted_script_hosts` 배열에서 읽습니다. 이 플러그인이 레이아웃
|
||||
* `scripts[].src` 로 로드하는 외부 CDN 호스트(예: `cdn.ckeditor.com`)를 선언합니다.
|
||||
* 코어는 이 목록을 집계(AbstractPlugin/AbstractModule → TrustedScriptHosts)해 런타임
|
||||
* 스크립트 로더·저장측 검증·정적 검사가 same-origin 이 아닌 스크립트 중 **선언된
|
||||
* 호스트만** 허용하도록 합니다 (KVE-2026-1915 신뢰 출처 허용목록).
|
||||
*
|
||||
* @return array<int, string> 신뢰 호스트명 목록 (예: ['cdn.ckeditor.com'])
|
||||
*/
|
||||
public function getTrustedScriptHosts(): array
|
||||
{
|
||||
$hosts = $this->loadManifest()['trusted_script_hosts'] ?? [];
|
||||
|
||||
if (! is_array($hosts)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
array_map(fn ($host) => is_string($host) ? trim($host) : '', $hosts),
|
||||
fn ($host) => $host !== ''
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로 반환
|
||||
*
|
||||
|
||||
@@ -204,6 +204,38 @@ class PermissionHelper
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 스코프 접근이 허용되는 모델만 남긴 배열을 반환합니다 (정적 일괄 라우트용).
|
||||
*
|
||||
* `PermissionMiddleware` 의 스코프 검사는 라우트에서 모델이 resolve 될 때만
|
||||
* 동작합니다 — 모델이 없으면 목록 엔드포인트로 보아 건너뜁니다. 따라서
|
||||
* `{user}` 같은 파라미터가 없는 **정적 일괄 라우트**(예: `PATCH users/bulk-status`)
|
||||
* 에서는 스코프 검사가 통째로 우회됩니다. 상세 경로가 403 으로 막는 대상을
|
||||
* 일괄 경로로는 바꿀 수 있으면 그 경로가 우회로이므로, 서비스 계층에서
|
||||
* 같은 판정(`checkScopeAccess`)을 재적용해야 합니다.
|
||||
*
|
||||
* 판정은 대상별로 이뤄집니다 — 액터의 유효 스코프가 self 면 자기 소유만,
|
||||
* role 이면 같은 역할 범위까지, 미지정(글로벌)이면 전체가 통과합니다.
|
||||
*
|
||||
* @param iterable<Model> $models 검사 대상 모델 목록
|
||||
* @param string $permission 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자)
|
||||
* @return array<Model> 스코프 접근이 허용된 모델 목록
|
||||
*/
|
||||
public static function filterByScope(iterable $models, string $permission, ?User $user = null): array
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
$allowed = [];
|
||||
foreach ($models as $model) {
|
||||
if (self::checkScopeAccess($model, $permission, $user)) {
|
||||
$allowed[] = $model;
|
||||
}
|
||||
}
|
||||
|
||||
return $allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission 스코프 데이터를 static 캐시와 함께 조회합니다.
|
||||
*
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Http\Resources\AttachmentResource;
|
||||
use App\Models\Attachment;
|
||||
use App\Services\AttachmentService;
|
||||
use Exception;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
/**
|
||||
@@ -21,7 +22,7 @@ class AttachmentController extends AdminBaseController
|
||||
/**
|
||||
* AttachmentController 생성자
|
||||
*
|
||||
* @param AttachmentService $attachmentService 첨부파일 서비스
|
||||
* @param AttachmentService $attachmentService 첨부파일 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private AttachmentService $attachmentService
|
||||
@@ -32,7 +33,7 @@ class AttachmentController extends AdminBaseController
|
||||
/**
|
||||
* 단일 파일 업로드
|
||||
*
|
||||
* @param UploadAttachmentRequest $request 업로드 요청
|
||||
* @param UploadAttachmentRequest $request 업로드 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function upload(UploadAttachmentRequest $request): JsonResponse
|
||||
@@ -64,7 +65,7 @@ class AttachmentController extends AdminBaseController
|
||||
/**
|
||||
* 여러 파일 일괄 업로드
|
||||
*
|
||||
* @param UploadBatchAttachmentRequest $request 일괄 업로드 요청
|
||||
* @param UploadBatchAttachmentRequest $request 일괄 업로드 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function uploadBatch(UploadBatchAttachmentRequest $request): JsonResponse
|
||||
@@ -117,7 +118,7 @@ class AttachmentController extends AdminBaseController
|
||||
/**
|
||||
* 순서 변경
|
||||
*
|
||||
* @param ReorderAttachmentsRequest $request 순서 변경 요청
|
||||
* @param ReorderAttachmentsRequest $request 순서 변경 요청
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function reorder(ReorderAttachmentsRequest $request): JsonResponse
|
||||
@@ -126,9 +127,12 @@ class AttachmentController extends AdminBaseController
|
||||
$this->attachmentService->reorder($request->input('order'));
|
||||
|
||||
return $this->success('attachment.reorder_success');
|
||||
} catch (AuthorizationException $e) {
|
||||
// 스코프 밖 첨부가 포함된 경우. 아래 제네릭 catch 보다 앞에 둬야 한다 —
|
||||
// 뒤에 두면 인가 거부가 500 으로 뭉개져 상세 경로(403)와 응답이 갈린다.
|
||||
return $this->error('auth.scope_denied', 403, $e->getMessage());
|
||||
} catch (Exception $e) {
|
||||
return $this->error('attachment.reorder_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,6 +12,7 @@ use App\Http\Resources\MenuCollection;
|
||||
use App\Http\Resources\MenuResource;
|
||||
use App\Models\Menu;
|
||||
use App\Services\MenuService;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -222,6 +223,10 @@ class MenuController extends AdminBaseController
|
||||
}
|
||||
} catch (ValidationException $e) {
|
||||
return $this->error('menu.order_update_failed', 422, $e->errors());
|
||||
} catch (AuthorizationException $e) {
|
||||
// 스코프 밖 메뉴가 포함된 경우. 제네릭 catch 보다 앞에 둬야 인가 거부가 500 으로
|
||||
// 뭉개지지 않고 상세 경로(403)와 같은 응답이 된다.
|
||||
return $this->error('auth.scope_denied', 403, $e->getMessage());
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('menu.update_error', 500, $e->getMessage());
|
||||
}
|
||||
|
||||
@@ -2,20 +2,23 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Exceptions\CannotModifyProtectedRoleException;
|
||||
use App\Exceptions\ExtensionOwnedRoleDeleteException;
|
||||
use App\Exceptions\PermissionEscalationException;
|
||||
use App\Exceptions\SystemRoleDeleteException;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\Role\ActiveRolesRequest;
|
||||
use App\Http\Requests\Role\RoleListRequest;
|
||||
use App\Http\Requests\Role\StoreRoleRequest;
|
||||
use App\Http\Requests\Role\UpdateRoleRequest;
|
||||
use App\Http\Resources\RoleCollection;
|
||||
use App\Http\Resources\RoleResource;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Services\RoleService;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
@@ -60,13 +63,13 @@ class RoleController extends AdminBaseController
|
||||
* core.permissions.read 권한 보유 시 전체 활성 역할을 반환하고,
|
||||
* 미보유 시 현재 사용자에게 부여된 역할만 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @param ActiveRolesRequest $request 활성 역할 조회 요청
|
||||
* @return JsonResponse 활성화된 역할 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function active(Request $request): JsonResponse
|
||||
public function active(ActiveRolesRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
/** @var \App\Models\User $user */
|
||||
/** @var User $user */
|
||||
$user = $request->user();
|
||||
|
||||
// 역할 관리 권한(core.permissions.read) 보유 → 전체 활성 역할 (사용자 관리용)
|
||||
@@ -78,7 +81,10 @@ class RoleController extends AdminBaseController
|
||||
return $this->success('role.fetch_success', [
|
||||
'data' => RoleResource::collection($roles),
|
||||
'abilities' => [
|
||||
'can_assign_roles' => PermissionHelper::check('core.permissions.update'),
|
||||
// 역할 부여는 "사용자 관리"(core.users.update)의 일부다 — "역할 정의 수정"
|
||||
// (core.permissions.update)이 아니다. 부여 가능한 개별 역할의 범위는 서버
|
||||
// 상한(PermissionEscalationGuard)이 역할별로 강제한다.
|
||||
'can_assign_roles' => PermissionHelper::check('core.users.update'),
|
||||
],
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
@@ -122,6 +128,8 @@ class RoleController extends AdminBaseController
|
||||
new RoleResource($role),
|
||||
201
|
||||
);
|
||||
} catch (PermissionEscalationException $e) {
|
||||
return $this->error('exceptions.cannot_grant_unheld_permission', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->error('role.create_failed', 422, $e->errors());
|
||||
} catch (Exception $e) {
|
||||
@@ -145,6 +153,10 @@ class RoleController extends AdminBaseController
|
||||
'role.update_success',
|
||||
new RoleResource($updatedRole)
|
||||
);
|
||||
} catch (CannotModifyProtectedRoleException $e) {
|
||||
return $this->error('exceptions.cannot_modify_protected_role', 403);
|
||||
} catch (PermissionEscalationException $e) {
|
||||
return $this->error('exceptions.cannot_grant_unheld_permission', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->error('role.update_failed', 422, $e->errors());
|
||||
} catch (Exception $e) {
|
||||
@@ -174,6 +186,8 @@ class RoleController extends AdminBaseController
|
||||
} else {
|
||||
return $this->error('role.update_failed');
|
||||
}
|
||||
} catch (CannotModifyProtectedRoleException $e) {
|
||||
return $this->error('exceptions.cannot_modify_protected_role', 403);
|
||||
} catch (Exception $e) {
|
||||
return $this->error('role.update_failed', 500, $e->getMessage());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Exceptions\CannotModifySuperAdminException;
|
||||
use App\Exceptions\PermissionEscalationException;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\User\BulkUpdateUserStatusRequest;
|
||||
use App\Http\Requests\User\CheckEmailRequest;
|
||||
@@ -74,6 +76,8 @@ class UserController extends AdminBaseController
|
||||
new UserResource($user),
|
||||
201
|
||||
);
|
||||
} catch (PermissionEscalationException $e) {
|
||||
return $this->error('exceptions.cannot_grant_unheld_permission', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->error('user.create_failed', 422, $e->errors());
|
||||
} catch (Exception $e) {
|
||||
@@ -122,6 +126,10 @@ class UserController extends AdminBaseController
|
||||
'user.update_success',
|
||||
new UserResource($updatedUser)
|
||||
);
|
||||
} catch (CannotModifySuperAdminException $e) {
|
||||
return $this->error('exceptions.cannot_modify_super_admin', 403);
|
||||
} catch (PermissionEscalationException $e) {
|
||||
return $this->error('exceptions.cannot_grant_unheld_permission', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->error('user.update_failed', 422, $e->errors());
|
||||
} catch (Exception $e) {
|
||||
@@ -148,6 +156,8 @@ class UserController extends AdminBaseController
|
||||
'auth.account_unlocked',
|
||||
new UserResource($unlocked)
|
||||
);
|
||||
} catch (CannotModifySuperAdminException $e) {
|
||||
return $this->error('exceptions.cannot_modify_super_admin', 403);
|
||||
} catch (Exception $e) {
|
||||
return $this->error('user.update_failed', 500, $e, ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
@@ -7,8 +7,10 @@ use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Rules\ComponentExists;
|
||||
use App\Rules\NoExternalUrls;
|
||||
use App\Rules\SafeLayoutExpressions;
|
||||
use App\Rules\ValidLayoutStructure;
|
||||
use App\Rules\WhitelistedEndpoint;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -24,6 +26,8 @@ class StoreLayoutRequest extends FormRequest
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어가 담당)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -33,7 +37,7 @@ class StoreLayoutRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -67,6 +71,8 @@ class StoreLayoutRequest extends FormRequest
|
||||
new WhitelistedEndpoint,
|
||||
// 4. 외부 URL 차단
|
||||
new NoExternalUrls,
|
||||
// 5. 표현식 샌드박스 우회/원격 스크립트 저장측 차단
|
||||
new SafeLayoutExpressions,
|
||||
],
|
||||
];
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Requests\Layout;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\NoExternalUrls;
|
||||
use App\Rules\SafeLayoutExpressions;
|
||||
use App\Rules\ValidDataSourceMerge;
|
||||
use App\Rules\ValidLayoutStructure;
|
||||
use App\Rules\ValidParentLayout;
|
||||
@@ -265,6 +266,14 @@ class UpdateLayoutContentRequest extends FormRequest
|
||||
'required',
|
||||
'array',
|
||||
new ValidLayoutStructure,
|
||||
// 표현식 샌드박스 우회/원격 스크립트 저장측 차단 (KVE-2026-1915).
|
||||
// content 트리 전체를 재귀 순회해야 하므로 배열 규칙에 부착한다 — 문자열
|
||||
// 필드(endpoint)에 부착하면 is_array 가드로 early-return 되어 무력화된다.
|
||||
new SafeLayoutExpressions,
|
||||
// props·actions·init_actions 의 외부 URL 차단. 편집기 저장 경로이므로
|
||||
// Store/UpdateLayoutRequest 와 동일 강도여야 한다 — 여기 누락 시 다른
|
||||
// 경로에서 막히는 외부 URL 이 편집기 저장으로는 통과한다.
|
||||
new NoExternalUrls,
|
||||
],
|
||||
|
||||
// 버전 필드
|
||||
@@ -426,6 +435,8 @@ class UpdateLayoutContentRequest extends FormRequest
|
||||
'string',
|
||||
new WhitelistedEndpoint,
|
||||
new NoExternalUrls,
|
||||
// SafeLayoutExpressions 는 content 배열 규칙에서 트리 전체를 순회하므로 여기(문자열
|
||||
// endpoint)에는 부착하지 않는다 — 문자열에 부착 시 is_array 가드로 no-op 이 된다.
|
||||
];
|
||||
|
||||
if (! $isExtending && ! $isBaseLayout) {
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Requests\Layout;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Rules\NoExternalUrls;
|
||||
use App\Rules\SafeLayoutExpressions;
|
||||
use App\Rules\ValidDataSourceMerge;
|
||||
use App\Rules\ValidLayoutExtensionStructure;
|
||||
use App\Rules\WhitelistedEndpoint;
|
||||
@@ -62,6 +63,11 @@ class UpdateLayoutExtensionContentRequest extends FormRequest
|
||||
'required',
|
||||
'array',
|
||||
new ValidLayoutExtensionStructure,
|
||||
// 표현식 샌드박스 우회/원격 스크립트 저장측 차단 (KVE-2026-1915).
|
||||
// content 트리 전체(data_sources·scripts·표현식 문자열)를 재귀 순회한다.
|
||||
new SafeLayoutExpressions,
|
||||
// props·actions·init_actions 의 외부 URL 차단 (Store/UpdateLayoutRequest 와 동일 강도)
|
||||
new NoExternalUrls,
|
||||
],
|
||||
|
||||
// 우선순위 (선택 — content.priority 와 별개로 직접 지정 가능)
|
||||
@@ -74,6 +80,8 @@ class UpdateLayoutExtensionContentRequest extends FormRequest
|
||||
'content.data_sources' => ['nullable', 'array', new ValidDataSourceMerge],
|
||||
|
||||
// 데이터소스 endpoint 검증
|
||||
// SafeLayoutExpressions 는 content 배열 규칙이 트리 전체를 순회하며 data_sources[].endpoint
|
||||
// same-origin 까지 검사하므로 여기(문자열)에는 부착하지 않는다 (문자열 부착 시 no-op).
|
||||
'content.data_sources.*.endpoint' => [
|
||||
'nullable',
|
||||
'string',
|
||||
|
||||
@@ -7,8 +7,10 @@ use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Rules\ComponentExists;
|
||||
use App\Rules\NoExternalUrls;
|
||||
use App\Rules\SafeLayoutExpressions;
|
||||
use App\Rules\ValidLayoutStructure;
|
||||
use App\Rules\WhitelistedEndpoint;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -24,6 +26,8 @@ class UpdateLayoutRequest extends FormRequest
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어가 담당)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -33,7 +37,7 @@ class UpdateLayoutRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -71,6 +75,8 @@ class UpdateLayoutRequest extends FormRequest
|
||||
new WhitelistedEndpoint,
|
||||
// 4. 외부 URL 차단
|
||||
new NoExternalUrls,
|
||||
// 5. 표현식 샌드박스 우회/원격 스크립트 저장측 차단
|
||||
new SafeLayoutExpressions,
|
||||
],
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Role;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 활성 역할 목록(선택 옵션용) 조회 요청
|
||||
*
|
||||
* 별도 검증 규칙 없이 인증 컨텍스트만 전달하는 엔드포인트지만, 컨트롤러가 base
|
||||
* Illuminate\Http\Request 를 직접 주입받지 않도록 전용 FormRequest 서브클래스를 둔다.
|
||||
* 인증/권한은 permission 미들웨어 체인이 담당하므로 authorize() 는 true 고정.
|
||||
*/
|
||||
class ActiveRolesRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어 체인이 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class UserCollection extends BaseApiCollection
|
||||
{
|
||||
@@ -20,7 +21,10 @@ class UserCollection extends BaseApiCollection
|
||||
'can_create' => 'core.users.create',
|
||||
'can_update' => 'core.users.update',
|
||||
'can_delete' => 'core.users.delete',
|
||||
'can_assign_roles' => 'core.permissions.update',
|
||||
// 역할 부여는 "사용자 관리"(core.users.update)의 일부다 — "역할 정의 수정"
|
||||
// (core.permissions.update)이 아니다. 부여 가능한 개별 역할의 범위는 서버
|
||||
// 상한(PermissionEscalationGuard)이 역할별로 강제한다.
|
||||
'can_assign_roles' => 'core.users.update',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -36,7 +40,7 @@ class UserCollection extends BaseApiCollection
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
return (new UserResource($user))->toListArray(request());
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator, [
|
||||
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
@@ -56,7 +60,7 @@ class UserCollection extends BaseApiCollection
|
||||
*/
|
||||
public function withStatistics(array $statistics = []): array
|
||||
{
|
||||
$isPaginator = $this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator;
|
||||
$isPaginator = $this->resource instanceof LengthAwarePaginator;
|
||||
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
@@ -87,7 +91,7 @@ class UserCollection extends BaseApiCollection
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
return (new UserResource($user))->withAdminInfo();
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator, [
|
||||
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
|
||||
@@ -204,7 +204,10 @@ class UserResource extends BaseApiResource
|
||||
'can_create' => 'core.users.create',
|
||||
'can_update' => 'core.users.update',
|
||||
'can_delete' => 'core.users.delete',
|
||||
'can_assign_roles' => 'core.permissions.update',
|
||||
// 역할 부여는 "사용자 관리"(core.users.update)의 일부다 — "역할 정의 수정"
|
||||
// (core.permissions.update: 역할에 권한을 가감)이 아니다. 부여 가능한 개별 역할의
|
||||
// 범위는 서버 상한(PermissionEscalationGuard)이 역할별로 강제한다.
|
||||
'can_assign_roles' => 'core.users.update',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use App\Services\ModuleSettingsService;
|
||||
use App\Services\PluginSettingsService;
|
||||
use App\Services\SettingsService;
|
||||
use App\Services\TemplateService;
|
||||
use App\Support\TrustedScriptHosts;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class TemplateComposer
|
||||
@@ -103,6 +104,10 @@ class TemplateComposer
|
||||
// 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
|
||||
$bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
|
||||
|
||||
// 신뢰 외부 스크립트 호스트 — 레이아웃 scripts[].src same-origin 예외 허용목록
|
||||
// (KVE-2026-1915: 확장이 manifest 로 선언한 CDN 호스트만 런타임 로더가 허용)
|
||||
$trustedScriptHosts = TrustedScriptHosts::hosts();
|
||||
|
||||
$view->with('activeAdminTemplate', $activeTemplate);
|
||||
$view->with('extensionCacheVersion', $extensionCacheVersion);
|
||||
$view->with('frontendSettings', $frontendSettings);
|
||||
@@ -115,5 +120,6 @@ class TemplateComposer
|
||||
$view->with('activePluginsMeta', $activePluginsMeta);
|
||||
$view->with('appConfig', $appConfig);
|
||||
$view->with('templateExternals', $templateExternals);
|
||||
$view->with('trustedScriptHosts', $trustedScriptHosts);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use App\Services\ModuleSettingsService;
|
||||
use App\Services\PluginSettingsService;
|
||||
use App\Services\SettingsService;
|
||||
use App\Services\TemplateService;
|
||||
use App\Support\TrustedScriptHosts;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
@@ -109,6 +110,10 @@ class UserTemplateComposer
|
||||
// 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
|
||||
$bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
|
||||
|
||||
// 신뢰 외부 스크립트 호스트 — 레이아웃 scripts[].src same-origin 예외 허용목록
|
||||
// (KVE-2026-1915: 확장이 manifest 로 선언한 CDN 호스트만 런타임 로더가 허용)
|
||||
$trustedScriptHosts = TrustedScriptHosts::hosts();
|
||||
|
||||
$view->with('activeUserTemplate', $activeTemplate);
|
||||
$view->with('extensionCacheVersion', $extensionCacheVersion);
|
||||
$view->with('frontendSettings', $frontendSettings);
|
||||
@@ -121,5 +126,6 @@ class UserTemplateComposer
|
||||
$view->with('activePluginsMeta', $activePluginsMeta);
|
||||
$view->with('appConfig', $appConfig);
|
||||
$view->with('templateExternals', $templateExternals);
|
||||
$view->with('trustedScriptHosts', $trustedScriptHosts);
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,21 @@ class MenuRepository implements MenuRepositoryInterface
|
||||
return Menu::with(['creator', 'parent', 'children'])->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 ID로 메뉴를 한 번에 조회합니다.
|
||||
*
|
||||
* @param array<int, int> $ids 메뉴 ID 목록
|
||||
* @return Collection 메뉴 컬렉션
|
||||
*/
|
||||
public function findByIds(array $ids): Collection
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return Menu::query()->whereRaw('1 = 0')->get();
|
||||
}
|
||||
|
||||
return Menu::whereIn('id', $ids)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 슬러그로 메뉴를 찾습니다.
|
||||
*
|
||||
|
||||
@@ -30,6 +30,21 @@ class PermissionRepository implements PermissionRepositoryInterface
|
||||
return Permission::find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 ID로 권한을 일괄 조회합니다.
|
||||
*
|
||||
* @param array<int> $ids 권한 ID 배열
|
||||
* @return Collection 권한 컬렉션 (ID 기준)
|
||||
*/
|
||||
public function getByIds(array $ids): Collection
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
return Permission::whereIn('id', $ids)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 식별자로 권한을 찾습니다.
|
||||
*
|
||||
|
||||
@@ -8,8 +8,14 @@ use Illuminate\Contracts\Validation\ValidationRule;
|
||||
/**
|
||||
* 레이아웃 JSON에서 외부 URL을 차단하는 Custom Rule
|
||||
*
|
||||
* props와 actions 내의 http://, https://, data:, javascript: 등
|
||||
* 위험한 URI 스킴을 감지하여 차단합니다.
|
||||
* 컴포넌트 props·actions 와 최상위 init_actions 내의 http://, https://, data:,
|
||||
* javascript: 등 위험한 URI 스킴을 감지하여 차단합니다.
|
||||
*
|
||||
* 검사 대상 구분(신뢰 경계): init_actions 는 로드 시 자동 실행되는 액션이라 외부
|
||||
* navigate/apiCall URL 이 곧 자동 리다이렉트·데이터 유출 경로가 되므로 실행 지점에서
|
||||
* 차단합니다. 반면 state/computed 는 데이터 값이며, 실제 위험은 그 값이 바인딩되는
|
||||
* sink(컴포넌트 prop = img src 등)에서 발생하고 그 sink 는 이미 여기서 검사됩니다 —
|
||||
* 예시/안내용 URL 을 담는 정당한 용례를 깨지 않기 위해 데이터 계층은 재차단하지 않습니다.
|
||||
*/
|
||||
class NoExternalUrls implements ValidationRule
|
||||
{
|
||||
@@ -31,6 +37,15 @@ class NoExternalUrls implements ValidationRule
|
||||
*/
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
// 문자열 스칼라 필드에도 부착되므로(`content.endpoint` ·
|
||||
// `content.data_sources.*.endpoint`) 그 값을 직접 검사한다. 배열만 처리하고
|
||||
// 반환하면 그 부착이 조용한 no-op 이 된다.
|
||||
if (is_string($value)) {
|
||||
$this->checkForDangerousUrl($value, $attribute, $fail);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
return;
|
||||
}
|
||||
@@ -39,6 +54,16 @@ class NoExternalUrls implements ValidationRule
|
||||
if (isset($value['components']) && is_array($value['components'])) {
|
||||
$this->validateComponents($value['components'], $fail);
|
||||
}
|
||||
|
||||
// init_actions: 로드 시 자동 실행되는 액션 — 외부 navigate/apiCall URL 은 로드 시점
|
||||
// 자동 리다이렉트/데이터 유출 경로가 되므로 컴포넌트 actions 와 동일하게 검사한다.
|
||||
if (isset($value['init_actions']) && is_array($value['init_actions'])) {
|
||||
foreach ($value['init_actions'] as $i => $action) {
|
||||
if (is_array($action)) {
|
||||
$this->validateObject($action, "init_actions[$i]", $fail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,7 +137,11 @@ class NoExternalUrls implements ValidationRule
|
||||
}
|
||||
|
||||
// 추가 패턴 검사: //로 시작 (프로토콜 상대 URL)
|
||||
if (str_starts_with($lowerValue, '//')) {
|
||||
//
|
||||
// 브라우저 URL 파서는 파싱 전에 ASCII tab·개행을 제거하고 백슬래시를 슬래시와
|
||||
// 동등하게 처리하므로, `/\/evil.com` · `/{tab}/evil.com` 도 실제로는 외부
|
||||
// origin 이 된다. 접두 검사 전에 동일하게 정규화한다(SafeLayoutExpressions 와 동형).
|
||||
if (str_starts_with(SafeLayoutExpressions::normalizeForOriginCheck($lowerValue), '//')) {
|
||||
$fail(__('validation.external_url.detected_in_props', ['url' => $value]));
|
||||
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
<?php
|
||||
|
||||
namespace App\Rules;
|
||||
|
||||
use App\Support\TrustedScriptHosts;
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
/**
|
||||
* 레이아웃 JSON 표현식 저장측 심층 방어 규칙 (KVE-2026-1915)
|
||||
*
|
||||
* 클라이언트의 화이트리스트 AST 평가기(SafeExpressionEvaluator)가 표현식 실행의
|
||||
* 1차 방어입니다. 이 규칙은 저장 시점에 위험 토큰을 거부하는 서버측 보조 방어로,
|
||||
* 편집자가 저장한 레이아웃이 애초에 샌드박스 우회 표현식/원격 스크립트를 담지
|
||||
* 못하게 합니다.
|
||||
*
|
||||
* 차단 대상(레이아웃 JSON 전체를 재귀 순회하며 모든 문자열 값 검사):
|
||||
* - 프로토타입 체인 접근: `.constructor` / `.__proto__` / `.prototype`,
|
||||
* `['constructor']` 등 문자열 리터럴 computed 접근 → Function 도달 경로
|
||||
* - 함수 생성/코드 실행: `Function(`, `eval(`, 동적 `import(`
|
||||
* - 원격 스크립트: `scripts[].src` 는 same-origin path-only(`/` 시작, `//`·scheme 금지),
|
||||
* 단 확장이 manifest(`trusted_script_hosts`)로 선언한 신뢰 호스트는 예외로 허용
|
||||
* - 외부 데이터 소스: `data_sources[].endpoint` 도 동일 (same-origin 또는 신뢰 호스트)
|
||||
*
|
||||
* 화살표 함수(`=>`)는 정상 표현식에서 광범위하게 사용되므로 차단하지 않습니다
|
||||
* (클라이언트 평가기가 인터프리터로 안전하게 실행).
|
||||
*/
|
||||
class SafeLayoutExpressions implements ValidationRule
|
||||
{
|
||||
/**
|
||||
* 위험 표현식 토큰 패턴 (문자열 값 대상)
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private const DANGEROUS_PATTERNS = [
|
||||
// 프로토타입/생성자 체인 접근 (dot)
|
||||
'/\.\s*(constructor|__proto__|prototype)\b/i',
|
||||
// 프로토타입/생성자 체인 접근 (문자열 리터럴 computed 키) — 중첩 배열 키
|
||||
// `[['constructor']]` 도 내부 `['constructor']` 가 매칭된다.
|
||||
'/\[\s*[\'"](constructor|__proto__|prototype)[\'"]\s*\]/i',
|
||||
// Object 리플렉션 static 호출 — 프로토타입/디스크립터를 읽어 Function 도달·프로토타입
|
||||
// 오염 경로. **호출 위치(뒤에 `(`)만** 매칭해 안내 문구의 단순 단어 언급은 오탐하지 않는다.
|
||||
// 리플렉션 인자 `getOwnPropertyDescriptor(x, 'constructor')` 는 이 메서드명이 반드시
|
||||
// 동반되므로 여기서 잡히고, 금지 프로퍼티를 그냥 문자열로 비교하는 정상 표현식
|
||||
// (`{{ mode === 'prototype' }}` — 런타임 평가기가 허용)은 차단하지 않는다.
|
||||
'/\b(getPrototypeOf|setPrototypeOf|getOwnPropertyDescriptors?|defineProperty|defineProperties)\s*\(/i',
|
||||
// 함수 생성자 / eval 호출
|
||||
'/\bFunction\s*\(/',
|
||||
'/\beval\s*\(/',
|
||||
// 동적 import() — 원격 ES 모듈 로드/코드 실행 경로 (런타임 AST 평가기와 저장측 패리티)
|
||||
'/\bimport\s*\(/',
|
||||
// 원시 __proto__ 식별자
|
||||
'/\b__proto__\b/',
|
||||
// legacy 접근자 4종 — 프로퍼티를 **문자열 인자**로 지목해 프로토타입을 읽고 쓴다.
|
||||
// Object 리플렉션 static 과 같은 능력을 모든 객체가 상속으로 제공하므로 같은 강도로
|
||||
// 막는다. 배포 레이아웃 전수에서 사용 0건이라 정상 표현식 회귀가 없다.
|
||||
'/\b__(lookup|define)(Getter|Setter)__\b/',
|
||||
];
|
||||
|
||||
// 주의: 문자열 조립 난독화(`['const' + 'ructor']`)는 정적 토큰 매칭으로 잡을 수 없다.
|
||||
// 그 형태의 최종 방어는 런타임 화이트리스트 인터프리터(SafeExpressionEvaluator)가
|
||||
// 담당한다 — 키를 1회 정규화(String 강제변환)한 뒤 금지 프로퍼티를 차단하므로,
|
||||
// 조립·배열·toString 강제변환 등 모든 우회 형태가 접근 시점에 거부된다. 이 저장측
|
||||
// 규칙은 리터럴·리플렉션 형태를 저장 단계에서 조기 차단하는 심층 방어 계층이다.
|
||||
|
||||
/**
|
||||
* 신뢰 외부 스크립트 호스트 캐시 (검증 1회당 집계 1회).
|
||||
*
|
||||
* @var array<int, string>|null
|
||||
*/
|
||||
private ?array $trustedHosts = null;
|
||||
|
||||
/**
|
||||
* 검증 수행
|
||||
*/
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->walk($value, $fail);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 JSON 트리를 재귀 순회하며 문자열 값을 검사합니다.
|
||||
*
|
||||
* @param array<mixed> $node 현재 노드
|
||||
* @param Closure $fail 검증 실패 콜백
|
||||
*/
|
||||
private function walk(array $node, Closure $fail): void
|
||||
{
|
||||
foreach ($node as $key => $item) {
|
||||
// 백틱 템플릿 리터럴을 포함한 위험 표현식 토큰 검사
|
||||
if (is_string($item)) {
|
||||
$this->assertSafeExpression($item, $fail);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// scripts[].src same-origin 검증
|
||||
if ($key === 'scripts') {
|
||||
$this->assertSameOriginList($item, 'src', $fail);
|
||||
}
|
||||
|
||||
// data_sources[].endpoint same-origin 검증
|
||||
if ($key === 'data_sources') {
|
||||
$this->assertSameOriginList($item, 'endpoint', $fail);
|
||||
}
|
||||
|
||||
$this->walk($item, $fail);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 표현식에 위험 토큰이 포함되어 있으면 검증을 실패시킵니다.
|
||||
*
|
||||
* @param string $value 검사 대상 문자열
|
||||
* @param Closure $fail 검증 실패 콜백
|
||||
*/
|
||||
private function assertSafeExpression(string $value, Closure $fail): void
|
||||
{
|
||||
// 백틱 템플릿 리터럴은 차단하지 않는다 — 레이아웃이 내비게이션 경로 조립 등에
|
||||
// 정상적으로 사용하며(예: `/mypage/${$args[0]}`), `${...}` 는 클라이언트
|
||||
// 평가기가 인터프리터로 안전하게 해석한다. constructor/Function 등 실제 위험
|
||||
// 토큰만 아래에서 거부한다.
|
||||
foreach (self::DANGEROUS_PATTERNS as $pattern) {
|
||||
if (preg_match($pattern, $value) === 1) {
|
||||
$fail(__('validation.layout.dangerous_expression', ['snippet' => mb_substr($value, 0, 80)]));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* scripts/data_sources 배열의 지정 필드가 same-origin path-only 인지 검증합니다.
|
||||
*
|
||||
* @param array<mixed> $list scripts 또는 data_sources 배열
|
||||
* @param string $field 검사할 필드명 (src | endpoint)
|
||||
* @param Closure $fail 검증 실패 콜백
|
||||
*/
|
||||
private function assertSameOriginList(array $list, string $field, Closure $fail): void
|
||||
{
|
||||
foreach ($list as $entry) {
|
||||
if (! is_array($entry) || ! isset($entry[$field]) || ! is_string($entry[$field])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$url = trim($entry[$field]);
|
||||
|
||||
if ($url === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 표현식 바인딩(`{{...}}`)은 런타임 해석 대상이라 여기서 판정하지 않는다.
|
||||
if (str_starts_with($url, '{{')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// same-origin path 이거나, 확장이 선언한 신뢰 호스트면 허용. 그 외 외부 origin 차단.
|
||||
if (! $this->isSameOriginPath($url)
|
||||
&& ! TrustedScriptHosts::isTrustedUrl($url, $this->trustedHosts())) {
|
||||
$fail(__('validation.layout.external_resource_url', ['url' => $url]));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 신뢰 외부 스크립트 호스트 목록을 반환합니다 (검증 1회당 1회 집계 후 캐시).
|
||||
*
|
||||
* @return array<int, string> 신뢰 호스트명 목록
|
||||
*/
|
||||
private function trustedHosts(): array
|
||||
{
|
||||
return $this->trustedHosts ??= TrustedScriptHosts::hosts();
|
||||
}
|
||||
|
||||
/**
|
||||
* same-origin path-only URL 인지 판정합니다.
|
||||
*
|
||||
* 허용: `/` 로 시작하는 경로. 차단: `//`(protocol-relative), scheme 포함 절대 URL.
|
||||
*
|
||||
* @param string $url 검사 대상 URL
|
||||
* @return bool same-origin path 이면 true
|
||||
*/
|
||||
private function isSameOriginPath(string $url): bool
|
||||
{
|
||||
$normalized = self::normalizeForOriginCheck($url);
|
||||
|
||||
// protocol-relative (`//evil.com/...`) 차단
|
||||
if (str_starts_with($normalized, '//')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// scheme 포함 절대 URL(`https://`, `javascript:`, `data:` 등) 차단
|
||||
if (preg_match('/^[a-z][a-z0-9+.\-]*:/i', $normalized) === 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// path-only: `/` 로 시작해야 same-origin 절대 경로
|
||||
return str_starts_with($normalized, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* origin 판정 전에 URL 을 브라우저 URL 파서와 동일하게 정규화합니다.
|
||||
*
|
||||
* 문자열 접두 검사만으로는 authority 우회를 막지 못합니다. 브라우저(WHATWG URL)는
|
||||
* 파싱 전에 ASCII tab·개행을 제거하고, special scheme(http/https)에서 백슬래시를
|
||||
* 슬래시와 동등하게 처리하기 때문입니다. 따라서 `/\/evil.com/x.js` ·
|
||||
* `/{tab}/evil.com/x.js` 는 `//` 로 시작하지 않는데도 실제로는
|
||||
* `https://evil.com/x.js` 로 해석됩니다.
|
||||
*
|
||||
* 정규화 후 판정하면 경로 중간의 백슬래시·탭(`/js/a\b.js`)은 authority 를 만들지
|
||||
* 않으므로 그대로 통과합니다(과차단 없음).
|
||||
*
|
||||
* 클라이언트(`TemplateApp.isAllowedScriptSrc`)·정적 검사
|
||||
* (`layout-scripts-src-same-origin`)와 3층 동형이어야 합니다.
|
||||
*
|
||||
* 구현 SSoT 는 `TrustedScriptHosts::normalizeForOriginCheck` 입니다 — 같은 저장측
|
||||
* 판정 안에서 same-origin 검사(이 규칙)와 신뢰 호스트 검사(`TrustedScriptHosts`)가
|
||||
* 이어 붙으므로, 두 검사가 서로 다른 정규화를 쓰면 한 URL 이 "path 도 아니고
|
||||
* 외부 호스트도 아닌" 상태로 빠져나간다. 위임으로 그 갈림을 구조적으로 막는다.
|
||||
*
|
||||
* @param string $url 원본 URL
|
||||
* @return string 정규화된 URL
|
||||
*/
|
||||
public static function normalizeForOriginCheck(string $url): string
|
||||
{
|
||||
return TrustedScriptHosts::normalizeForOriginCheck($url);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Contracts\Extension\StorageInterface;
|
||||
use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Enums\AttachmentSourceType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\User;
|
||||
use App\Support\ImageResizer;
|
||||
@@ -231,6 +232,8 @@ class AttachmentService
|
||||
*/
|
||||
public function reorder(array $orderData): void
|
||||
{
|
||||
$this->assertReorderWithinScope($orderData);
|
||||
|
||||
// Before 훅
|
||||
HookManager::doAction('core.attachment.before_reorder', $orderData);
|
||||
|
||||
@@ -240,6 +243,44 @@ class AttachmentService
|
||||
HookManager::doAction('core.attachment.after_reorder', $orderData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 순서 변경 대상이 액터의 스코프 안에 있는지 검사합니다.
|
||||
*
|
||||
* `PATCH admin/attachments/reorder` 는 라우트 모델이 없는 정적 경로다. PermissionMiddleware
|
||||
* 는 `$request->route('attachment')` 가 Model 일 때만 스코프를 검사하고 없으면 목록
|
||||
* 엔드포인트로 보아 건너뛰므로(`PermissionMiddleware`), 상세 경로(`DELETE {attachment}`)가
|
||||
* 미들웨어로 강제하는 스코프 축이 이 경로에서만 비어 있었다. 배포 기본 역할 `manager` 가
|
||||
* `core.attachments.update` 를 `self` 스코프로 보유하므로 이론 구성이 아니라 기본값에서
|
||||
* 성립한다 — 타인 소유 첨부의 순서를 바꿀 수 있었다.
|
||||
*
|
||||
* 대상 일부만 걸러내지 않고 **전체를 거부**한다. 순서는 집합 전체에 대한 하나의 배열이라
|
||||
* 일부만 반영하면 나머지와 어긋난 순서가 저장되기 때문이다(사용자 일괄 상태변경이
|
||||
* "제외" 를 택한 것과 의미론이 다르다).
|
||||
*
|
||||
* @param array<int, array{id: int, order: int}> $orderData 순서 데이터
|
||||
*
|
||||
* @throws AuthorizationException 스코프 밖 첨부가 하나라도 포함된 경우
|
||||
*/
|
||||
private function assertReorderWithinScope(array $orderData): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_filter(
|
||||
array_map(static fn ($item): int => (int) ($item['id'] ?? 0), $orderData)
|
||||
)));
|
||||
|
||||
if (empty($ids)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$attachments = $this->repository->findByIds($ids);
|
||||
|
||||
// 판정은 상세 경로와 같은 SSoT 에 위임한다 — 여기서 재구현하면 두 경로의 강도가 갈린다.
|
||||
$permitted = PermissionHelper::filterByScope($attachments, 'core.attachments.update');
|
||||
|
||||
if (count($permitted) !== $attachments->count()) {
|
||||
throw new AuthorizationException(__('auth.scope_denied'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 다운로드 응답 생성
|
||||
*
|
||||
|
||||
@@ -7,8 +7,10 @@ use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\MenuPermissionType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\Menu;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -203,11 +205,19 @@ class MenuService
|
||||
/**
|
||||
* 메뉴 순서를 업데이트합니다 (드래그 앤 드롭).
|
||||
*
|
||||
* 형제 `updateMenuOrderWithHierarchy` 와 같은 리소스를 같은 방식으로 쓰므로 스코프
|
||||
* 가드도 대칭이어야 한다. 코어 내 호출부가 없다는 사실은 방어가 아니다 — 이 서비스는
|
||||
* 확장이 주입받을 수 있고, 가드가 형제 경로에만 있으면 여기가 우회로가 된다.
|
||||
*
|
||||
* @param array $menuOrders 메뉴 ID와 순서 매핑 배열
|
||||
* @return bool 업데이트 성공 여부
|
||||
*
|
||||
* @throws AuthorizationException 스코프 밖 메뉴가 하나라도 포함된 경우
|
||||
*/
|
||||
public function updateMenuOrder(array $menuOrders): bool
|
||||
{
|
||||
$this->assertMenusWithinScope(array_map('intval', array_values($menuOrders)));
|
||||
|
||||
// 훅: 메뉴 순서 변경 전 (IDV 정책 가드 지점)
|
||||
HookManager::doAction('core.menu.before_update_order', $menuOrders);
|
||||
|
||||
@@ -227,6 +237,8 @@ class MenuService
|
||||
*/
|
||||
public function updateMenuOrderWithHierarchy(array $orderData): bool
|
||||
{
|
||||
$this->assertOrderTargetsWithinScope($orderData);
|
||||
|
||||
$result = $this->menuRepository->updateOrderWithHierarchy($orderData);
|
||||
|
||||
// 훅: 메뉴 계층 순서 변경 후
|
||||
@@ -235,6 +247,74 @@ class MenuService
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 순서 변경 대상 메뉴가 액터의 스코프 안에 있는지 검사합니다.
|
||||
*
|
||||
* `PUT admin/menus/order` 는 라우트 모델이 없는 정적 경로라 PermissionMiddleware 의
|
||||
* 스코프 검사가 스킵된다(`{menu}` 파라미터 부재 → "목록 엔드포인트" 로 간주). 상세
|
||||
* 경로(`PUT menus/{menu}`)가 미들웨어로 강제하는 축이 이 경로에서만 비어 있었다.
|
||||
* 배포 기본 역할은 `core.menus.update` 를 글로벌로 주므로 기본값 노출은 아니지만,
|
||||
* 운영자가 역할 화면에서 스코프를 self/role 로 좁히는 순간 우회로가 된다.
|
||||
*
|
||||
* 첨부 순서 변경과 같은 이유로 **전량 거부**다 — 순서는 트리 전체에 대한 하나의
|
||||
* 배열이라 일부만 반영하면 나머지와 어긋난 계층이 저장된다.
|
||||
*
|
||||
* @param array $orderData 순서 데이터 (parent_menus / child_menus / moved_items)
|
||||
*
|
||||
* @throws AuthorizationException 스코프 밖 메뉴가 하나라도 포함된 경우
|
||||
*/
|
||||
private function assertOrderTargetsWithinScope(array $orderData): void
|
||||
{
|
||||
$ids = [];
|
||||
|
||||
foreach ($orderData['parent_menus'] ?? [] as $item) {
|
||||
$ids[] = (int) ($item['id'] ?? 0);
|
||||
}
|
||||
|
||||
foreach ($orderData['child_menus'] ?? [] as $children) {
|
||||
foreach ($children as $item) {
|
||||
$ids[] = (int) ($item['id'] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
// 이동 항목은 **옮기는 메뉴 자신**만 확인한다. 새 부모까지 검사하면, 공용 상위 메뉴
|
||||
// 아래에 자기 메뉴를 다는 정상 사용이 막힌다 — 결함은 "남의 메뉴 순서를 바꾼다" 였지
|
||||
// "남의 메뉴 아래에 못 붙인다" 가 아니다.
|
||||
foreach ($orderData['moved_items'] ?? [] as $item) {
|
||||
$ids[] = (int) ($item['id'] ?? 0);
|
||||
}
|
||||
|
||||
$this->assertMenusWithinScope($ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 메뉴 ID 집합이 전부 액터의 스코프 안에 있는지 검사합니다.
|
||||
*
|
||||
* 순서 변경 두 경로(`updateMenuOrder` · `updateMenuOrderWithHierarchy`)가 공유하는
|
||||
* 판정부다. 한쪽만 검사하면 형제 경로가 우회로가 되므로 판정을 한 곳에 둔다.
|
||||
*
|
||||
* @param array<int> $ids 검사 대상 메뉴 ID 목록
|
||||
*
|
||||
* @throws AuthorizationException 스코프 밖 메뉴가 하나라도 포함된 경우
|
||||
*/
|
||||
private function assertMenusWithinScope(array $ids): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_filter($ids)));
|
||||
|
||||
if (empty($ids)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$menus = $this->menuRepository->findByIds($ids);
|
||||
|
||||
// 판정은 상세 경로와 같은 SSoT 에 위임한다.
|
||||
$permitted = PermissionHelper::filterByScope($menus, 'core.menus.update');
|
||||
|
||||
if (count($permitted) !== $menus->count()) {
|
||||
throw new AuthorizationException(__('auth.scope_denied'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메뉴의 활성화 상태를 토글합니다.
|
||||
*
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Exceptions\CannotModifyProtectedRoleException;
|
||||
use App\Exceptions\ExtensionOwnedRoleDeleteException;
|
||||
use App\Exceptions\SystemRoleDeleteException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Support\PermissionEscalationGuard;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
@@ -17,7 +19,8 @@ use Illuminate\Support\Str;
|
||||
class RoleService
|
||||
{
|
||||
public function __construct(
|
||||
private RoleRepositoryInterface $roleRepository
|
||||
private RoleRepositoryInterface $roleRepository,
|
||||
private PermissionEscalationGuard $escalationGuard
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -105,6 +108,12 @@ class RoleService
|
||||
$permissions = $data['permissions'] ?? [];
|
||||
unset($data['permissions']);
|
||||
|
||||
// 권한 상승 상한을 **역할 생성 전에** 검사한다. 생성 뒤에 검사하면 거부된 요청이
|
||||
// 권한 0개짜리 고아 역할 행을 남긴다(사용자 경로와 동일한 "가드 → 쓰기" 순서).
|
||||
if (! empty($permissions)) {
|
||||
$this->escalationGuard->assertGrantWithinActorCeiling($permissions);
|
||||
}
|
||||
|
||||
// 훅: 생성 전
|
||||
HookManager::doAction('core.role.before_create', $data);
|
||||
|
||||
@@ -134,10 +143,20 @@ class RoleService
|
||||
*/
|
||||
public function updateRole(Role $role, array $data): Role
|
||||
{
|
||||
// 보호된 역할(코어/확장 소유) 수정 상한: 삭제 경로와 대칭.
|
||||
// 비-슈퍼관리자 액터는 admin 등 코어/확장 소유 역할을 변경할 수 없다.
|
||||
$this->assertActorMayModifyRole($role);
|
||||
|
||||
// 권한 목록 분리
|
||||
$permissions = $data['permissions'] ?? null;
|
||||
unset($data['permissions']);
|
||||
|
||||
// 권한 상승 상한을 **속성 업데이트 전에** 검사한다. update 뒤에 검사하면
|
||||
// 403 을 받은 요청이 name/is_active 변경만 반영된 상태를 남긴다.
|
||||
if ($permissions !== null) {
|
||||
$this->escalationGuard->assertGrantWithinActorCeiling($permissions);
|
||||
}
|
||||
|
||||
// 훅: 업데이트 전 (원본 data 전달)
|
||||
HookManager::doAction('core.role.before_update', $role, $data);
|
||||
|
||||
@@ -213,6 +232,15 @@ class RoleService
|
||||
*/
|
||||
public function syncPermissions(Role $role, array $permissions): void
|
||||
{
|
||||
// 보호된 역할(코어/확장 소유) 수정 상한: updateRole·toggleRoleStatus 와 대칭.
|
||||
// 이 메서드는 public 이므로 서비스를 주입한 확장이 직접 호출할 수 있다 —
|
||||
// 형제 경로에만 가드를 두면 여기가 코어 역할 보호의 우회로가 된다.
|
||||
$this->assertActorMayModifyRole($role);
|
||||
|
||||
// 권한 상승 상한(ceiling): 비-슈퍼관리자 액터는 자신이 보유하지 않았거나
|
||||
// 자신의 범위(scope)보다 넓은 범위의 권한을 부여할 수 없다(SSoT 가드에 위임).
|
||||
$this->escalationGuard->assertGrantWithinActorCeiling($permissions);
|
||||
|
||||
// 동기화 전 현재 권한 식별자 캡처 (Listener diff 계산용)
|
||||
$previousPermIdentifiers = $role->permissions()->pluck('identifier')->toArray();
|
||||
|
||||
@@ -244,6 +272,9 @@ class RoleService
|
||||
*/
|
||||
public function toggleRoleStatus(Role $role): bool
|
||||
{
|
||||
// 보호된 역할(코어/확장 소유) 상태변경 상한: 삭제 경로와 대칭.
|
||||
$this->assertActorMayModifyRole($role);
|
||||
|
||||
$newStatus = ! $role->is_active;
|
||||
|
||||
// 훅: 상태 변경 전
|
||||
@@ -259,6 +290,37 @@ class RoleService
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 액터가 보호된 역할(코어/확장 소유)을 수정할 수 있는지 확인합니다.
|
||||
*
|
||||
* 인증 액터가 없으면(Artisan/내부 시더) 신뢰 경로로 간주해 통과시킵니다.
|
||||
* 슈퍼 관리자는 모든 역할을 수정할 수 있고, 그 외 액터는 삭제 경로와 동일하게
|
||||
* 코어/확장 소유 역할을 수정할 수 없습니다.
|
||||
*
|
||||
* @param Role $role 대상 역할
|
||||
*
|
||||
* @throws CannotModifyProtectedRoleException 상한 위반 시
|
||||
*/
|
||||
private function assertActorMayModifyRole(Role $role): void
|
||||
{
|
||||
$actor = Auth::user();
|
||||
|
||||
// 인증 액터 부재 = 내부/Artisan 신뢰 경로 → 가드 미적용
|
||||
if (! $actor instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 슈퍼 관리자는 모든 역할 수정 가능
|
||||
if ($actor->isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 비-슈퍼관리자는 코어/확장 소유 역할 수정 불가
|
||||
if ($role->isCore() || $role->isExtensionOwned()) {
|
||||
throw new CannotModifyProtectedRoleException;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* name에서 identifier를 자동 생성합니다.
|
||||
*
|
||||
|
||||
@@ -6,12 +6,15 @@ use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Exceptions\PermissionEscalationException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\User;
|
||||
use App\Support\PermissionEscalationGuard;
|
||||
use App\Support\UserGradeGuard;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -26,7 +29,8 @@ class UserService
|
||||
public function __construct(
|
||||
private UserRepositoryInterface $userRepository,
|
||||
private RoleRepositoryInterface $roleRepository,
|
||||
private AttachmentService $attachmentService
|
||||
private AttachmentService $attachmentService,
|
||||
private PermissionEscalationGuard $escalationGuard
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -79,10 +83,19 @@ class UserService
|
||||
}
|
||||
unset($data['roles']);
|
||||
|
||||
// 역할 할당 권한 체크: core.permissions.update 권한 없으면 기본 역할 자동 할당
|
||||
if (! PermissionHelper::check('core.permissions.update')) {
|
||||
// 역할 할당: 요청 역할이 없으면 기본 역할('user')을 자동 배정하고, 요청 역할이
|
||||
// 있으면 액터 상한(ceiling) 검사만 받는다.
|
||||
//
|
||||
// 역할 부여는 "사용자 관리"(core.users.create — 이 경로는 라우트에서 이미 강제됨)의
|
||||
// 일부이지, "역할 정의 수정"(core.permissions.update — 역할에 권한을 가감하는 권한)을
|
||||
// 요구하지 않는다. 권한 상승 방지는 오직 상한(ceiling)이 담당한다: 액터가 보유하지
|
||||
// 않았거나 자신의 범위보다 넓은 권한을 담은 역할은 부여할 수 없다(KVE-2026-1919).
|
||||
// 신규 사용자는 기존 역할이 없으므로 요청 역할 전부가 새로 부여되는 역할이다.
|
||||
if ($roleIds === null || count($roleIds) === 0) {
|
||||
$defaultRoleId = $this->roleRepository->findByIdentifier('user')?->id;
|
||||
$roleIds = $defaultRoleId ? [$defaultRoleId] : null;
|
||||
} else {
|
||||
$this->escalationGuard->assertRoleAssignmentWithinActorCeiling($roleIds);
|
||||
}
|
||||
|
||||
$user = $this->userRepository->create($data);
|
||||
@@ -102,6 +115,11 @@ class UserService
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// 권한 상승 상한 위반은 그대로 전파해 컨트롤러가 403 으로 매핑하도록 한다.
|
||||
if ($e instanceof PermissionEscalationException) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'general' => [__('user.create_failed', ['error' => $e->getMessage()])],
|
||||
]);
|
||||
@@ -119,6 +137,10 @@ class UserService
|
||||
*/
|
||||
public function updateUser(User $user, array $data): User
|
||||
{
|
||||
// 등급 상한 가드: 비-슈퍼관리자 액터는 슈퍼 관리자 계정을 수정할 수 없다.
|
||||
// (비밀번호·status(withdrawn/blocked)·email 등 모든 수정 경로를 한 지점에서 차단)
|
||||
UserGradeGuard::assertActorMayModify($user);
|
||||
|
||||
try {
|
||||
// 원본 데이터 보관 (after_update 훅에서 사용)
|
||||
$originalData = $data;
|
||||
@@ -148,17 +170,35 @@ class UserService
|
||||
}
|
||||
unset($data['roles']);
|
||||
|
||||
// 역할 할당 권한 체크
|
||||
// 역할 할당
|
||||
if ($roleIds !== null) {
|
||||
$authUser = Auth::user();
|
||||
|
||||
// core.permissions.update 권한 없으면 역할 변경 불가
|
||||
if (! PermissionHelper::check('core.permissions.update', $authUser)) {
|
||||
$roleIds = null;
|
||||
// 역할 조작 상한(ceiling): 이번 변경으로 붙거나 떨어지는 역할이 액터가 전부
|
||||
// 부여할 수 있는 권한만 담고 있는지 확인한다(KVE-2026-1919). 역할 부여는
|
||||
// "사용자 관리"(core.users.update — 이 경로는 라우트에서 이미 강제됨)의 일부이며,
|
||||
// "역할 정의 수정"(core.permissions.update — 역할에 권한을 가감하는 권한)을
|
||||
// 요구하지 않는다. 권한 상승 방지는 오직 상한이 담당한다: 액터가 보유하지
|
||||
// 않았거나 자신의 범위보다 넓은 권한을 담은 역할은 부여할 수 없고, 위반 시
|
||||
// PermissionEscalationException 이 전파되어 403 으로 명시 거부된다(과거처럼 조용히
|
||||
// 무시하지 않는다).
|
||||
//
|
||||
// 검사 대상은 **추가·제거 양방향의 변경분**이다. 추가는 그 역할의 권한을
|
||||
// 부여하는 것이고, 제거는 상위 역할의 권한 구성을 박탈하는 하향 조작이므로 —
|
||||
// 액터가 스스로 부여할 수 없는(상한 밖) 역할은 붙이지도 떼지도 못한다. 추가만
|
||||
// 검사하면 core.users.update 만 가진 하위 관리자가 다른 관리자의 상위 역할을
|
||||
// 박탈하는 경로가 상한 없이 뚫린다. 기존 유지 역할은 변경이 아니므로 제외한다.
|
||||
$currentRoleIds = $user->roles->pluck('id')->all();
|
||||
$changedRoleIds = array_values(array_unique(array_merge(
|
||||
array_diff($roleIds, $currentRoleIds), // 추가되는 역할
|
||||
array_diff($currentRoleIds, $roleIds), // 제거되는 역할
|
||||
)));
|
||||
if (! empty($changedRoleIds)) {
|
||||
$this->escalationGuard->assertRoleAssignmentWithinActorCeiling($changedRoleIds);
|
||||
}
|
||||
|
||||
// 자기잠금 방지: 마지막 admin 역할 사용자가 자기 admin 역할을 제거하려는 경우 차단
|
||||
if ($roleIds !== null && $authUser && $authUser->id === $user->id) {
|
||||
if ($authUser && $authUser->id === $user->id) {
|
||||
$adminRole = $this->roleRepository->findByIdentifier('admin');
|
||||
if ($adminRole && $user->roles->contains('id', $adminRole->id) && ! in_array($adminRole->id, $roleIds)) {
|
||||
// admin 역할을 가진 다른 사용자가 있는지 확인
|
||||
@@ -261,6 +301,12 @@ class UserService
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// 권한 상승 상한 위반은 그대로 전파해 컨트롤러가 403 으로 매핑하도록 한다
|
||||
// (일반 실패로 감싸면 422 로 잘못 내려간다).
|
||||
if ($e instanceof PermissionEscalationException) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'general' => [__('user.update_failed', ['error' => $e->getMessage()])],
|
||||
]);
|
||||
@@ -589,22 +635,6 @@ class UserService
|
||||
return $excludeUserUuid && $user->uuid === $excludeUserUuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 활성화 상태를 업데이트합니다.
|
||||
* 현재는 구현되지 않음 - 필요시 확장 가능
|
||||
*
|
||||
* @param User $user 대상 사용자 모델
|
||||
* @param bool $isActive 활성화 상태
|
||||
* @return User 사용자 모델
|
||||
*/
|
||||
public function updateUserStatus(User $user, bool $isActive): User
|
||||
{
|
||||
// 현재 User 모델에 is_active 필드가 없으므로 필요시 추가
|
||||
// $this->userRepository->update($user, ['is_active' => $isActive]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 활동 로그를 조회합니다.
|
||||
*
|
||||
@@ -640,6 +670,9 @@ class UserService
|
||||
*/
|
||||
public function unlockAccount(User $user): User
|
||||
{
|
||||
// 등급 상한 가드: 비-슈퍼관리자 액터는 슈퍼 관리자 계정을 조작할 수 없다(정합성).
|
||||
UserGradeGuard::assertActorMayModify($user);
|
||||
|
||||
HookManager::doAction('core.user.before_unlock', $user);
|
||||
|
||||
$this->userRepository->resetLoginAttempts($user);
|
||||
@@ -653,19 +686,6 @@ class UserService
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 마지막 로그인 시간을 현재 시간으로 업데이트합니다.
|
||||
*
|
||||
* @param User $user 대상 사용자 모델
|
||||
* @return User 업데이트된 사용자 모델
|
||||
*/
|
||||
public function updateLastLogin(User $user): User
|
||||
{
|
||||
$this->userRepository->update($user, ['last_login_at' => now()]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 언어 설정을 업데이트합니다.
|
||||
*
|
||||
@@ -698,14 +718,38 @@ class UserService
|
||||
|
||||
$statusEnum = UserStatus::from($status);
|
||||
|
||||
// 정적 라우트(`PATCH users/bulk-status`)는 라우트 모델이 없어 PermissionMiddleware 의
|
||||
// 스코프 검사가 통째로 건너뛰어진다. 따라서 상세 경로(`PUT users/{user}`)가 미들웨어로
|
||||
// 강제하는 두 축을 서비스 계층에서 재적용한다 — 어느 한 축만 막으면 나머지가 우회로다.
|
||||
// 탈퇴 분기보다 먼저 적용해야 한다 — 뒤에 두면 탈퇴 경로가 스코프 검사를 건너뛰는
|
||||
// 우회로가 된다(KVE-1919).
|
||||
$targets = $this->userRepository->findManyByUuids($uuids);
|
||||
|
||||
// ① 등급 축: 비-슈퍼관리자 액터가 포함시킨 슈퍼 관리자 대상은 제외한다
|
||||
// (슈퍼 관리자 무력화 차단 — 슈퍼 세션 유지).
|
||||
$modifiable = UserGradeGuard::filterModifiable($targets);
|
||||
|
||||
// ② 스코프 축: 액터의 유효 스코프(self/role/글로벌) 밖 대상은 제외한다.
|
||||
// 판정은 상세 경로와 동일한 SSoT(PermissionHelper::checkScopeAccess)에 위임한다 —
|
||||
// 여기서 재구현하면 role 분기만 빠지는 식으로 두 경로의 강도가 갈린다.
|
||||
$modifiable = PermissionHelper::filterByScope($modifiable, 'core.users.update');
|
||||
|
||||
// 일괄 '탈퇴'는 건별 정식 탈퇴로 전환한다 — 상태 컬럼만 바꾸면 익명화와
|
||||
// before/after_withdraw 훅이 통째로 생략되어, 본인 탈퇴와 결과가 달라진다.
|
||||
// 위에서 등급·스코프로 걸러낸 대상에 한해서만 수행한다.
|
||||
if ($statusEnum === UserStatus::Withdrawn) {
|
||||
return $this->bulkWithdraw($uuids, $status);
|
||||
$modifiableUuids = array_map(static fn (User $u): string => $u->uuid, $modifiable);
|
||||
|
||||
return $this->bulkWithdraw($modifiableUuids, $status);
|
||||
}
|
||||
|
||||
// UUID → 정수 ID 변환 (내부 쿼리용)
|
||||
$userIds = $this->userRepository->getIdsByUuids($uuids);
|
||||
$userIds = array_map(static fn (User $u): int => $u->id, $modifiable);
|
||||
|
||||
if (empty($userIds)) {
|
||||
HookManager::doAction('sirsoft-core.user.after_bulk_update', $uuids, $status, 0);
|
||||
|
||||
return ['updated_count' => 0];
|
||||
}
|
||||
|
||||
// DB 트랜잭션으로 일괄 업데이트
|
||||
$updatedCount = DB::transaction(function () use ($userIds, $statusEnum) {
|
||||
|
||||
@@ -1138,7 +1138,8 @@ class ApiDocScaffolder
|
||||
// 종료 마커를 표의 끝 경계로 삼는데, 전자는 그 마커를 잘라내고 돌려준다.
|
||||
$merged .= $this->applyPreservedErrorTable(
|
||||
$withErrors,
|
||||
$this->exactGeneratedBlock($existing, $key)
|
||||
$this->exactGeneratedBlock($existing, $key),
|
||||
$section
|
||||
)."\n";
|
||||
}
|
||||
|
||||
@@ -1252,7 +1253,44 @@ class ApiDocScaffolder
|
||||
* @param string|null $previous 기존 문서의 같은 엔드포인트 생성 블록
|
||||
* @return string 에러 표가 보존된 섹션
|
||||
*/
|
||||
private function applyPreservedErrorTable(string $section, ?string $previous): string
|
||||
/**
|
||||
* 403 행의 요구 권한 식별자를 이번 재생성 산출값으로 갱신합니다.
|
||||
*
|
||||
* 에러 표 병합은 같은 상태코드에서 기존(사람) 행을 이기게 두는데, 403 의 권한 식별자는
|
||||
* 라우트 정의에서 파생된 사실이라 사람 서술과 같은 취급을 하면 안 된다. 두 행이 모두
|
||||
* 백틱 식별자를 가질 때만 그 부분을 치환하고, 나머지 문구(사람이 덧붙인 도메인 조건)는
|
||||
* 건드리지 않는다. 식별자가 없는 형태(관리자 게이트만 걸린 라우트)는 갱신 대상이 아니다.
|
||||
*
|
||||
* @param string $preserved 병합 결과로 살아남은 기존 403 행
|
||||
* @param string $generated 이번 재생성이 만든 403 행
|
||||
* @return string 식별자만 갱신된 403 행
|
||||
*/
|
||||
private function refreshPermissionIdentifier(string $preserved, string $generated): string
|
||||
{
|
||||
if (! preg_match('/`([^`]+)`/', $generated, $new)) {
|
||||
return $preserved;
|
||||
}
|
||||
|
||||
if (! preg_match('/`([^`]+)`/', $preserved, $old)) {
|
||||
return $preserved;
|
||||
}
|
||||
|
||||
if ($old[1] === $new[1]) {
|
||||
return $preserved;
|
||||
}
|
||||
|
||||
$needle = '`'.$old[1].'`';
|
||||
$pos = strpos($preserved, $needle);
|
||||
|
||||
if ($pos === false) {
|
||||
return $preserved;
|
||||
}
|
||||
|
||||
// preg_replace 는 대체 문자열의 `$`·`\` 를 역참조로 해석하므로 쓰지 않는다.
|
||||
return substr_replace($preserved, '`'.$new[1].'`', $pos, strlen($needle));
|
||||
}
|
||||
|
||||
private function applyPreservedErrorTable(string $section, ?string $previous, ?string $generated = null): string
|
||||
{
|
||||
if ($previous === null) {
|
||||
return $section;
|
||||
@@ -1285,12 +1323,28 @@ class ApiDocScaffolder
|
||||
|
||||
// 상태코드 키로 병합. `+` 는 왼쪽 우선이므로 기존 행을 먼저 둬서, 같은 상태코드면
|
||||
// 사람이 쓴 구체적 조건이 자동 문구를 이긴다. 자동 추론에만 있는 상태코드는 새로 편입된다.
|
||||
$merged = $previousRows + $this->errorTableRows($section);
|
||||
$currentRows = $this->errorTableRows($section);
|
||||
$merged = $previousRows + $currentRows;
|
||||
|
||||
if ($merged === []) {
|
||||
return $section;
|
||||
}
|
||||
|
||||
// 403 행의 권한 식별자만은 예외다 — 그것은 사람 서술이 아니라 라우트에서 파생된
|
||||
// 사실이라, 위 병합 규칙을 그대로 두면 라우트의 요구 권한을 바꿔도 옛 식별자가
|
||||
// 영구히 남아 문서가 조용히 틀린 권한을 안내한다. 사람이 보강한 조건 문구는 그대로
|
||||
// 두고 백틱 식별자만 갱신한다.
|
||||
//
|
||||
// 대조 원본은 반드시 **이번 회차가 생성한 원본 섹션**이어야 한다. 여기 들어오는
|
||||
// $section 은 restoreTableDescriptions 를 이미 거쳐 403 행의 설명 셀이 기존 문서
|
||||
// 값으로 되돌아가 있으므로(에러 표도 상태코드를 행 키로 갖는 표라 그 복원 대상에
|
||||
// 걸린다), 그것을 기준으로 삼으면 갱신이 언제나 no-op 이 된다.
|
||||
$generatedRows = $generated === null ? $currentRows : $this->errorTableRows($generated);
|
||||
|
||||
if (isset($merged['403'], $generatedRows['403'])) {
|
||||
$merged['403'] = $this->refreshPermissionIdentifier($merged['403'], $generatedRows['403']);
|
||||
}
|
||||
|
||||
ksort($merged, SORT_NUMERIC);
|
||||
|
||||
$table = "| 상태코드 | 의미 | 발생 조건 |\n| --- | --- | --- |\n".implode("\n", $merged);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Contracts\Repositories\PermissionRepositoryInterface;
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Exceptions\PermissionEscalationException;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* 권한 상승(escalation) 상한 가드 (SSoT)
|
||||
*
|
||||
* 비-슈퍼관리자 액터가 "자신이 보유하지 않았거나 자신의 범위(scope)보다 넓은" 권한을
|
||||
* 부여하는 것을 차단합니다(KVE-2026-1919). 권한을 직접 역할에 부여하는 경로(RoleService)와
|
||||
* 역할 자체를 사용자에게 붙여 그 역할의 권한을 통째로 넘기는 경로(UserService)가 **동일한
|
||||
* 상한 규칙**을 공유하도록, 판정을 한 지점에 모읍니다. 한 경로만 막으면 다른 경로가 우회로가
|
||||
* 됩니다(역할 부여는 곧 그 역할의 전 권한 부여이므로 권한 부여와 같은 상한을 받아야 합니다).
|
||||
*/
|
||||
class PermissionEscalationGuard
|
||||
{
|
||||
/**
|
||||
* @param PermissionRepositoryInterface $permissionRepository 권한 조회
|
||||
* @param RoleRepositoryInterface $roleRepository 역할 조회
|
||||
*/
|
||||
public function __construct(
|
||||
private PermissionRepositoryInterface $permissionRepository,
|
||||
private RoleRepositoryInterface $roleRepository
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 부여하려는 권한이 액터의 상한(보유 + 범위)을 넘지 않는지 확인합니다.
|
||||
*
|
||||
* 슈퍼 관리자와 내부/Artisan 경로는 상한 검사 없이 통과합니다. 비-슈퍼관리자
|
||||
* 액터는 자신이 보유한 권한만, 그리고 자신의 effective scope 보다 넓지 않은
|
||||
* 범위로만 부여할 수 있습니다(권한 상승 차단).
|
||||
*
|
||||
* @param array<int, array{id?: int, scope_type?: string|null}> $permissions 부여 권한 배열
|
||||
*
|
||||
* @throws PermissionEscalationException 상한 위반 시
|
||||
*/
|
||||
public function assertGrantWithinActorCeiling(array $permissions): void
|
||||
{
|
||||
$actor = Auth::user();
|
||||
|
||||
// 인증 액터 부재 = 내부/Artisan 신뢰 경로 → 상한 미적용
|
||||
if (! $actor instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 슈퍼 관리자는 상한 없음
|
||||
if ($actor->isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (empty($permissions)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 부여 대상 권한 ID → 식별자 매핑
|
||||
$ids = array_values(array_filter(array_map(
|
||||
static fn ($p) => $p['id'] ?? null,
|
||||
$permissions
|
||||
)));
|
||||
$identifierById = $this->permissionRepository->getByIds($ids)
|
||||
->keyBy('id')
|
||||
->map(static fn ($permission) => $permission->identifier);
|
||||
|
||||
foreach ($permissions as $permission) {
|
||||
$id = $permission['id'] ?? null;
|
||||
$identifier = $id !== null ? ($identifierById[$id] ?? null) : null;
|
||||
|
||||
// 식별자를 해석할 수 없는 권한은 안전하게 거부
|
||||
if ($identifier === null) {
|
||||
throw new PermissionEscalationException;
|
||||
}
|
||||
|
||||
// 액터가 보유하지 않은 권한은 부여 불가
|
||||
if (! $actor->hasPermission($identifier)) {
|
||||
throw new PermissionEscalationException;
|
||||
}
|
||||
|
||||
// 부여 범위가 액터의 effective scope 보다 넓으면 불가
|
||||
$requestedScope = $permission['scope_type'] ?? null;
|
||||
$actorScope = $actor->getEffectiveScopeForPermission($identifier);
|
||||
|
||||
if ($this->scopeRank($requestedScope) > $this->scopeRank($actorScope)) {
|
||||
throw new PermissionEscalationException;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자에게 부여하려는 역할들이 액터의 상한을 넘지 않는지 확인합니다.
|
||||
*
|
||||
* 역할을 붙이는 것은 그 역할이 담은 권한 전부를 부여하는 것과 같으므로, 각 역할의
|
||||
* 권한을 그 pivot scope 와 함께 펼쳐 권한 부여 상한(assertGrantWithinActorCeiling)을
|
||||
* 그대로 적용합니다. 호출측은 **이번 조작으로 변경되는(추가·제거) 역할만** 전달해야 합니다 —
|
||||
* 기존 유지 역할은 변경이 아니므로 제외합니다. 제거 방향도 같은 상한을 받는 이유는, 상위
|
||||
* 역할을 박탈하는 하향 조작 역시 액터가 권한을 갖지 못한 역할 구성에 대한 조작이기 때문입니다.
|
||||
*
|
||||
* @param array<int, int> $roleIds 이번 조작으로 변경되는(추가·제거) 역할 ID 목록
|
||||
*
|
||||
* @throws PermissionEscalationException 상한 위반 시
|
||||
*/
|
||||
public function assertRoleAssignmentWithinActorCeiling(array $roleIds): void
|
||||
{
|
||||
$actor = Auth::user();
|
||||
|
||||
if (! $actor instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($actor->isSuperAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roleIds = array_values(array_filter($roleIds, static fn ($id) => $id !== null));
|
||||
|
||||
if (empty($roleIds)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 시스템 baseline 역할('user')은 상한에서 면제한다.
|
||||
//
|
||||
// 'user' 는 모든 회원이 갖는 기본 역할로, core.permissions.update 가 없는 액터의
|
||||
// 생성 경로가 상한 검사 없이 자동 배정하는 바로 그 역할이다(UserService::createUser).
|
||||
// 그 역할의 권한은 알림 self-service·본인인증 등 회원 baseline 뿐이라 액터가
|
||||
// 그것을 "부여" 해도 권한 상승 벡터가 되지 않는다. baseline 을 검사에 넣으면
|
||||
// core.permissions.update 를 가진(=더 권한 있는) 액터가 baseline 을 명시 지정했을 때만
|
||||
// 403 이 되어, 권한 낮은 액터의 auto-assign 경로와 비대칭으로 정상 회원 생성/수정이
|
||||
// 깨진다. 비-baseline 역할은 여전히 전량 상한 검사를 받는다.
|
||||
$baselineRoleId = $this->roleRepository->findByIdentifier('user')?->id;
|
||||
|
||||
// 부여 역할들의 권한을 [{id, scope_type}] 로 펼친다
|
||||
$permissions = [];
|
||||
foreach ($roleIds as $roleId) {
|
||||
if ($baselineRoleId !== null && (int) $roleId === (int) $baselineRoleId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$role = $this->roleRepository->findById((int) $roleId);
|
||||
|
||||
// 존재하지 않는 역할은 안전하게 거부
|
||||
if ($role === null) {
|
||||
throw new PermissionEscalationException;
|
||||
}
|
||||
|
||||
foreach ($role->permissions as $permission) {
|
||||
$permissions[] = [
|
||||
'id' => $permission->id,
|
||||
'scope_type' => $permission->pivot->scope_type ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertGrantWithinActorCeiling($permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* scope_type 의 넓이 순위를 반환합니다 (클수록 넓음).
|
||||
*
|
||||
* null(전체) > 'role'(소유역할) > 'self'(본인) 순으로, User::getEffectiveScopeForPermission
|
||||
* 의 union 우선순위와 동일한 서열을 사용합니다.
|
||||
*
|
||||
* @param string|null $scope 범위 문자열
|
||||
* @return int 넓이 순위 (2=전체, 1=role, 0=self)
|
||||
*/
|
||||
private function scopeRank(?string $scope): int
|
||||
{
|
||||
return match ($scope) {
|
||||
null => 2,
|
||||
'role' => 1,
|
||||
default => 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 신뢰하는 외부 스크립트 호스트 집계 (KVE-2026-1915 신뢰 출처 허용목록)
|
||||
*
|
||||
* 레이아웃 `scripts[].src` 는 기본적으로 same-origin path-only 만 허용한다(원격 코드 로드
|
||||
* 차단). 그러나 CKEditor5(cdn.ckeditor.com)·Daum 우편번호(t1.daumcdn.net)처럼 외부 CDN
|
||||
* 스크립트를 정당하게 로드하는 번들 확장이 있다. 그 확장이 manifest 의
|
||||
* `trusted_script_hosts` 로 자기 호스트를 **선언**하고, 코어가 활성 확장 전수에서 이 목록을
|
||||
* 집계한다. 런타임 스크립트 로더(TemplateApp)·저장측 검증(SafeLayoutExpressions)·정적 검사
|
||||
* (audit)가 모두 이 집계 결과만 신뢰 호스트로 허용한다.
|
||||
*
|
||||
* 신뢰 경계: 편집기가 저장하는 레이아웃(저권한 액터)에는 외부 스크립트를 허용하지 않는
|
||||
* 것이 기본이고, 여기서 허용되는 것은 **확장이 코드로 선언한 호스트**뿐이다.
|
||||
*/
|
||||
class TrustedScriptHosts
|
||||
{
|
||||
/**
|
||||
* 확장이 동적으로 신뢰 호스트를 추가할 수 있는 필터 훅 이름.
|
||||
*/
|
||||
public const FILTER_HOOK = 'core.layout.trusted_script_hosts';
|
||||
|
||||
/**
|
||||
* 활성 모듈·플러그인·템플릿이 선언한 신뢰 호스트 전체를 집계합니다.
|
||||
*
|
||||
* @return array<int, string> 중복 제거된 호스트명 목록 (소문자)
|
||||
*/
|
||||
public static function hosts(): array
|
||||
{
|
||||
$hosts = [];
|
||||
|
||||
try {
|
||||
foreach (app(ModuleManager::class)->getActiveModules() as $module) {
|
||||
if (method_exists($module, 'getTrustedScriptHosts')) {
|
||||
$hosts = array_merge($hosts, $module->getTrustedScriptHosts());
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('TrustedScriptHosts: 모듈 집계 실패 - '.$e->getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
foreach (app(PluginManager::class)->getActivePlugins() as $plugin) {
|
||||
if (method_exists($plugin, 'getTrustedScriptHosts')) {
|
||||
$hosts = array_merge($hosts, $plugin->getTrustedScriptHosts());
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('TrustedScriptHosts: 플러그인 집계 실패 - '.$e->getMessage());
|
||||
}
|
||||
|
||||
// 템플릿은 모듈/플러그인과 달리 PHP 확장 클래스가 없고 manifest 배열로 다뤄지므로,
|
||||
// 활성 템플릿의 template.json 에서 직접 읽는다. 타입별 활성 템플릿은 각각 하나뿐이다.
|
||||
try {
|
||||
$templateManager = app(TemplateManager::class);
|
||||
|
||||
foreach (['admin', 'user'] as $type) {
|
||||
$template = $templateManager->getActiveTemplate($type);
|
||||
|
||||
if (! is_array($template) || ! isset($template['trusted_script_hosts'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$declared = $template['trusted_script_hosts'];
|
||||
|
||||
if (! is_array($declared)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts = array_merge($hosts, $declared);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('TrustedScriptHosts: 템플릿 집계 실패 - '.$e->getMessage());
|
||||
}
|
||||
|
||||
// 확장이 훅으로 동적 추가할 수 있는 경로 (manifest 외 경로)
|
||||
$hosts = HookManager::applyFilters(self::FILTER_HOOK, $hosts);
|
||||
|
||||
if (! is_array($hosts)) {
|
||||
$hosts = [];
|
||||
}
|
||||
|
||||
// 정규화: 문자열·비어있지 않음·소문자·중복 제거
|
||||
$normalized = [];
|
||||
foreach ($hosts as $host) {
|
||||
if (! is_string($host)) {
|
||||
continue;
|
||||
}
|
||||
$host = strtolower(trim($host));
|
||||
if ($host !== '') {
|
||||
$normalized[$host] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 에서 호스트명을 추출합니다.
|
||||
*
|
||||
* `//host/path`(protocol-relative)·`https://host/path`(scheme 포함) 모두 처리합니다.
|
||||
* same-origin 경로(`/path`)는 호스트가 없으므로 null 을 반환합니다.
|
||||
*
|
||||
* @param string $url 검사 대상 URL
|
||||
* @return string|null 소문자 호스트명 (없으면 null)
|
||||
*/
|
||||
public static function hostOf(string $url): ?string
|
||||
{
|
||||
$host = parse_url(self::normalizeForOriginCheck(trim($url)), PHP_URL_HOST);
|
||||
|
||||
return is_string($host) && $host !== '' ? strtolower($host) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* origin 판정 전에 URL 을 브라우저 URL 파서와 동일하게 정규화합니다.
|
||||
*
|
||||
* 브라우저(WHATWG URL)는 파싱 전에 ASCII tab·LF·CR 을 제거하고, special scheme
|
||||
* (http/https)에서 백슬래시를 슬래시와 동등하게 처리합니다. 이 정규화 없이 판정하면
|
||||
* 같은 문자열을 계층마다 다른 출처로 읽습니다:
|
||||
*
|
||||
* - `https://evil.com\@cdn.ckeditor.com/x.js` — 정규화 없이는 호스트가
|
||||
* `cdn.ckeditor.com`(userinfo 해석)이지만 브라우저는 `evil.com` 에서 로드합니다.
|
||||
* - `/\/cdn.ckeditor.com/x.js` — 문자열상 path 지만 브라우저는 authority 로 읽습니다.
|
||||
*
|
||||
* 정규화 후 판정하면 경로 중간의 백슬래시·탭(`/js/a\b.js`)은 authority 를 만들지
|
||||
* 않으므로 그대로 통과합니다(과차단 없음).
|
||||
*
|
||||
* 이 메서드가 origin 판정 정규화의 SSoT 입니다 — 저장측 규칙
|
||||
* (`App\Rules\SafeLayoutExpressions`)이 위임하고, 클라이언트
|
||||
* (`TemplateApp.normalizeScriptSrcForOriginCheck`)·정적 검사
|
||||
* (`layout-scripts-src-same-origin`)가 동형 구현을 갖습니다. 한 계층만 바꾸면
|
||||
* 그 계층만 다른 출처를 보게 되며, 예외도 경고도 없이 판정만 갈립니다.
|
||||
*
|
||||
* @param string $url 원본 URL
|
||||
* @return string 정규화된 URL
|
||||
*/
|
||||
public static function normalizeForOriginCheck(string $url): string
|
||||
{
|
||||
// ASCII tab / LF / CR 제거 (브라우저 파서가 파싱 전에 제거하는 문자)
|
||||
$stripped = str_replace(["\t", "\n", "\r"], '', $url);
|
||||
|
||||
// 백슬래시를 슬래시로 (special scheme 에서 등가)
|
||||
$slashed = str_replace('\\', '/', $stripped);
|
||||
|
||||
// 선행 슬래시가 3개 이상이어도 브라우저는 authority 시작으로 접는다
|
||||
// (`///host/x` ≡ `//host/x`, `https:///host/x` ≡ `https://host/x`).
|
||||
// 접지 않으면 `/\/host/x` 가 정규화 후 `///host/x` 가 되어 parse_url 은
|
||||
// 호스트를 못 찾는데 브라우저는 host 에서 로드하는 갈림이 생긴다.
|
||||
// 경로 중간의 연속 슬래시(`/js//a.js`)는 브라우저도 경로로 두므로 건드리지 않는다.
|
||||
return preg_replace('#^([a-z][a-z0-9+.\-]*:)?/{2,}#i', '$1//', $slashed) ?? $slashed;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 의 호스트가 신뢰 목록에 있는지 판정합니다.
|
||||
*
|
||||
* @param string $url 검사 대상 URL
|
||||
* @param array<int, string>|null $hosts 신뢰 호스트 목록 (미지정 시 self::hosts())
|
||||
* @return bool 신뢰 호스트면 true (호스트 없는 same-origin 경로는 false)
|
||||
*/
|
||||
public static function isTrustedUrl(string $url, ?array $hosts = null): bool
|
||||
{
|
||||
$host = self::hostOf($url);
|
||||
|
||||
if ($host === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hosts ??= self::hosts();
|
||||
|
||||
return in_array($host, $hosts, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Exceptions\CannotModifySuperAdminException;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* 사용자 등급 상한(rank ceiling) 가드 (SSoT)
|
||||
*
|
||||
* 슈퍼 관리자 보호는 그동안 삭제/탈퇴 경로에만 있었고 수정·상태변경·권한부여
|
||||
* 경로에는 없어 비대칭이었습니다(KVE-2026-1919). 이 가드는 "비-슈퍼관리자
|
||||
* 액터는 슈퍼 관리자를 수정할 수 없다"는 규칙을 단일 지점에서 강제해 모든
|
||||
* 쓰기 경로가 동일한 상한을 공유하도록 합니다.
|
||||
*
|
||||
* 인증된 액터가 없는 경우(Artisan, 내부 시더/호출)는 신뢰 경로로 간주해
|
||||
* 가드를 적용하지 않습니다. HTTP 관리 경로는 인증·권한 미들웨어를 통과하므로
|
||||
* 이 지점에서는 항상 액터가 존재합니다.
|
||||
*/
|
||||
class UserGradeGuard
|
||||
{
|
||||
/**
|
||||
* 액터가 대상 사용자를 수정할 수 있는지 판정합니다.
|
||||
*
|
||||
* @param User $target 수정 대상 사용자
|
||||
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
|
||||
* @return bool 수정 가능 여부
|
||||
*/
|
||||
public static function mayModify(User $target, ?User $actor = null): bool
|
||||
{
|
||||
$actor ??= Auth::user();
|
||||
|
||||
// 인증 액터 부재 = 내부/Artisan 신뢰 경로 → 가드 미적용
|
||||
if (! $actor instanceof User) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 대상이 슈퍼 관리자가 아니면 등급 상한과 무관
|
||||
if (! $target->isSuperAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 슈퍼 관리자 대상은 슈퍼 관리자 액터만 수정 가능
|
||||
return $actor->isSuperAdmin();
|
||||
}
|
||||
|
||||
/**
|
||||
* 액터가 대상을 수정할 수 없으면 예외를 던집니다.
|
||||
*
|
||||
* @param User $target 수정 대상 사용자
|
||||
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
|
||||
*
|
||||
* @throws CannotModifySuperAdminException 상한 위반 시
|
||||
*/
|
||||
public static function assertActorMayModify(User $target, ?User $actor = null): void
|
||||
{
|
||||
if (! self::mayModify($target, $actor)) {
|
||||
throw new CannotModifySuperAdminException;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 액터가 수정 가능한 대상만 남긴 배열을 반환합니다(일괄 작업용).
|
||||
*
|
||||
* @param iterable<User> $targets 대상 사용자 목록
|
||||
* @param User|null $actor 행위자(미지정 시 현재 인증 사용자)
|
||||
* @return array<User> 수정 가능한 대상 목록
|
||||
*/
|
||||
public static function filterModifiable(iterable $targets, ?User $actor = null): array
|
||||
{
|
||||
$actor ??= Auth::user();
|
||||
|
||||
$allowed = [];
|
||||
foreach ($targets as $target) {
|
||||
if (self::mayModify($target, $actor)) {
|
||||
$allowed[] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
return $allowed;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user