fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정

관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다.
설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자
리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다.

경계값 SSoT 도입:
- config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로
 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
- 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다.

적용되지 않던 정책을 실제로 적용:
- 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을
 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함)
- 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에
 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로
- 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책,
 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세

파생 결함:
- 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는
 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고,
 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다.
- 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자
 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로
 두고, 빈 목록 자체를 캐시하지 않는다.
- 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다.
- 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여).

재발 방지:
- audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프)
- 테스트 실행 범위 강제 훅(check-test-scope)
- 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착)

공개 이슈: gnuboard/g7
This commit is contained in:
HeuJung committed 2026-07-30 07:52:24 +09:00
1 parent 5d140dfbe6
commit d17ea28da5
272 files changed
+12431 -1006

No files matched your search

@@ -492,6 +492,11 @@ class AdminTemplateAssetControllerTest extends TestCase
*/
public function test_editor_assets_css_points_to_editor_endpoint(): void
{
// 자산 URL 의 확장자 표기는 사이트 설정(general.asset_url_mode)이 정한다.
// 이 테스트가 단언하는 것은 "편집기 전용 엔드포인트인가" 이므로, 설정을 명시해
// 개발 사이트가 어느 모드를 쓰든 결과가 달라지지 않게 고정한다.
config(['g7_settings.core.general.asset_url_mode' => 'extension']);
$response = $this->withHeaders([
'Authorization' => "Bearer {$this->adminToken}",
'Accept' => 'application/json',
@@ -0,0 +1,118 @@
<?php
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Http\Requests\Settings\SaveSettingsRequest;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 환경설정 입력 한계값 계약 테스트 (#493 C4)
*
* 설정 화면의 숫자 입력 경계값과 저장 검증 규칙이 각자 리터럴을 들면 조용히 갈라져,
* "화면이 허용한 값인데 저장에서 422" 또는 그 반대가 됩니다. 양쪽이 같은 출처
* (`config('core.settings_limits')`)를 읽는지, 그 값이 화면에 실제로 전달되는지 검증합니다.
*/
class SettingsLimitsMetaTest extends TestCase
{
use RefreshDatabase;
private User $admin;
private string $token;
protected function setUp(): void
{
parent::setUp();
$this->admin = $this->createSettingsAdmin();
$this->token = $this->admin->createToken('test-token')->plainTextToken;
}
/**
* 설정 조회 권한을 가진 관리자를 생성합니다.
*
* @return User 생성된 관리자
*/
private function createSettingsAdmin(): User
{
$user = User::factory()->create(['password' => Hash::make('password123')]);
$permission = Permission::firstOrCreate(
['identifier' => 'core.settings.read'],
[
'name' => json_encode(['ko' => 'core.settings.read', 'en' => 'core.settings.read']),
'description' => json_encode(['ko' => 'core.settings.read', 'en' => 'core.settings.read']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => 'admin',
]
);
$role = Role::create([
'identifier' => 'settings_limits_admin_'.uniqid(),
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Admin']),
'description' => json_encode(['ko' => '테스트', 'en' => 'Test']),
'is_active' => true,
]);
$role->permissions()->sync([$permission->id]);
$adminBaseRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
$user->roles()->attach($adminBaseRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
$user->roles()->attach($role->id, ['assigned_at' => now(), 'assigned_by' => null]);
return $user->fresh();
}
/**
* 설정 조회 응답이 화면이 바인딩할 한계값을 함께 내려주는지 검증합니다.
*/
#[Test]
public function index_response_includes_settings_limits_meta(): void
{
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
])->getJson('/api/admin/settings');
$response->assertStatus(200);
$limits = $response->json('data._meta.limits');
$this->assertIsArray($limits, '설정 응답에 _meta.limits 가 없습니다 — 화면이 경계값을 받을 수 없습니다.');
$this->assertSame(config('core.settings_limits'), $limits);
}
/**
* 저장 규칙이 리터럴이 아니라 설정 한계값을 읽는지 검증합니다.
*/
#[Test]
public function save_rules_read_password_length_bounds_from_config(): void
{
config([
'core.settings_limits.security_password_min_length_min' => 9,
'core.settings_limits.security_password_min_length_max' => 33,
]);
$rules = (new SaveSettingsRequest)->rules()['security.password_min_length'];
$this->assertContains('min:9', $rules);
$this->assertContains('max:33', $rules);
}
}
@@ -5,6 +5,8 @@ namespace Tests\Feature\Api\Auth;
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
use App\Enums\IdentityVerificationStatus;
use App\Enums\UserStatus;
use App\Extension\HookManager;
use App\Listeners\Identity\EnforceIdentityPolicyListener;
use App\Models\IdentityPolicy;
use App\Models\IdentityVerificationLog;
use App\Models\Role;
@@ -15,6 +17,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
/**
@@ -96,7 +99,7 @@ class RegisterPolicyDrivenSignupTest extends TestCase
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) \Illuminate\Support\Str::uuid(),
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
@@ -140,7 +143,7 @@ class RegisterPolicyDrivenSignupTest extends TestCase
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) \Illuminate\Support\Str::uuid(),
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
@@ -185,7 +188,7 @@ class RegisterPolicyDrivenSignupTest extends TestCase
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) \Illuminate\Support\Str::uuid(),
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
@@ -280,6 +283,34 @@ class RegisterPolicyDrivenSignupTest extends TestCase
$this->assertSame(UserStatus::Active->value, $user->status);
}
/**
* signup_after_create 정책이 켜져 있어도 가입 훅이 이중으로 강제되지 않는지 확인합니다.
*
* `core.auth.after_register` 는 challenge 를 발행하는 전담 리스너가 소유한다. 일반 정책
* 강제 리스너까지 이 훅을 구독하면, challenge 를 발행한 직후 428 이 던져져 가입 자체가
* 막힌다 — '가입 후 본인확인' 정책이 '가입 전' 정책과 구분되지 않고, 켜는 순간 아무도
* 가입할 수 없게 된다. 동작(위 두 테스트)과 별개로 구독 상태를 직접 고정한다.
*/
public function test_after_register_hook_is_not_subscribed_by_the_generic_enforcer(): void
{
$this->enablePolicy('core.auth.signup_after_create');
EnforceIdentityPolicyListener::syncDynamicHookSubscriptions();
$hooks = new \ReflectionProperty(HookManager::class, 'hooks');
$hooks->setAccessible(true);
$registered = $hooks->getValue()['core.auth.after_register'] ?? [];
$priorities = array_keys($registered);
$this->assertContains(5, $priorities, 'challenge 발행 리스너가 구독되어 있어야 합니다.');
$this->assertNotContains(
15,
$priorities,
'정책 강제 리스너가 after_register 를 구독하면 가입이 428 로 막힙니다.'
);
}
/**
* 시드된 정책의 enabled 를 true 로 토글합니다.
*/
@@ -0,0 +1,184 @@
<?php
namespace Tests\Feature\Attachment;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Extension\HookManager;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
/**
* 업로드 정책(용량·확장자) 강제 테스트 (C2)
*
* 수정 전에는 존재하지 않는 config 키(`attachment.max_size`)를 읽어 폴백 상수로 동작했고,
* 확장자 제한은 어느 경로에서도 강제되지 않았습니다.
*
* 주의: 폴백(10 * 1024 = 10240)이 실제 기본값(10240 KB)과 우연히 같아 **기본 설정 상태에서는
* 회귀 테스트가 green 이 되는 함정**이 있습니다. 반드시 기본값과 다른 값을 주입해 판정합니다.
*/
class AttachmentUploadPolicyTest extends TestCase
{
use RefreshDatabase;
private User $user;
protected function setUp(): void
{
parent::setUp();
Storage::fake('attachments');
$this->user = $this->createUploaderAdmin();
}
/**
* @test
*/
public function 설정된_최대_용량을_초과하면_422_로_차단된다(): void
{
// 기본값(10240KB)과 다른 값을 주입해야 폴백과의 우연한 일치를 피할 수 있다
config(['attachment.max_file_size' => 100]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->create('big.pdf', 200, 'application/pdf'),
]);
$response->assertStatus(422);
}
/**
* @test
*/
public function 설정된_최대_용량_이내는_통과한다(): void
{
config(['attachment.max_file_size' => 100]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->create('small.pdf', 50, 'application/pdf'),
]);
$response->assertStatus(201);
}
/**
* @test
*/
public function 허용되지_않는_확장자는_422_로_차단된다(): void
{
config(['attachment.allowed_extensions' => ['png', 'pdf']]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->create('shell.php', 10, 'text/x-php'),
]);
$response->assertStatus(422);
}
/**
* @test
*/
public function 허용된_확장자는_통과한다(): void
{
config(['attachment.allowed_extensions' => ['png', 'pdf']]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->image('photo.png'),
]);
$response->assertStatus(201);
}
/**
* @test
*/
public function 허용_확장자_목록이_비면_제한하지_않는다(): void
{
// 운영 중 예상치 못한 확장자로 업로드가 막히는 상황의 탈출구
config(['attachment.allowed_extensions' => []]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->create('anything.php', 10, 'text/x-php'),
]);
$response->assertStatus(201);
}
/**
* @test
*/
public function 확장_훅으로_허용_확장자를_조정할_수_있다(): void
{
config(['attachment.allowed_extensions' => ['png']]);
HookManager::addFilter(
'core.attachment.allowed_extensions',
fn (array $extensions) => array_merge($extensions, ['pdf']),
);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments', [
'file' => UploadedFile::fake()->create('doc.pdf', 10, 'application/pdf'),
]);
$response->assertStatus(201);
}
/**
* @test
*/
public function 일괄_업로드도_동일한_정책을_적용한다(): void
{
config(['attachment.allowed_extensions' => ['png']]);
$response = $this->actingAs($this->user, 'sanctum')->postJson('/api/admin/attachments/batch', [
'files' => [
UploadedFile::fake()->image('ok.png'),
UploadedFile::fake()->create('shell.php', 10, 'text/x-php'),
],
]);
$response->assertStatus(422);
}
/**
* 첨부파일 업로드 권한을 가진 관리자를 생성합니다.
*
* @return User 관리자 사용자
*/
private function createUploaderAdmin(): User
{
$user = User::factory()->create(['is_super' => true, 'status' => 'active']);
$permission = Permission::firstOrCreate(
['identifier' => 'core.attachments.create'],
[
'name' => json_encode(['ko' => '첨부파일 업로드', 'en' => 'Upload Attachments']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]
);
$role = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
if (! $role->permissions()->where('permissions.id', $permission->id)->exists()) {
$role->permissions()->attach($permission->id);
}
$user->roles()->attach($role->id, ['assigned_at' => now(), 'assigned_by' => null]);
return $user->fresh();
}
}
+305
View File
@@ -0,0 +1,305 @@
<?php
namespace Tests\Feature\Auth;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Helpers\PermissionHelper;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
/**
* 영구 계정 잠금 + 관리자 수동 해제 통합 테스트 (C1)
*
* `login_lockout_time = 0` 은 관리자 UI 가 "0을 입력하면 무한대로 설정됩니다" 라고 안내하는
* 값입니다. 수정 전에는 1 분 잠금으로 뭉개져 무차별 대입 공격자를 영구 차단할 수 없었고,
* 관리자가 그 사실을 인지할 방법도 없었습니다.
*
* 영구 잠금을 도입하면 해제 수단이 "성공 로그인" 뿐이던 기존 구조에서는 잠긴 계정이
* 복구 불가가 되므로, 관리자 수동 해제 엔드포인트를 같은 변경에 포함합니다.
*/
class AccountLockoutTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->setSecuritySettings([
'login_attempt_enabled' => true,
'max_login_attempts' => 3,
'login_lockout_time' => 0,
]);
Cache::flush();
}
/**
* @test
*/
public function 잠금시간_0_설정에서_임계값_도달_시_영구_잠금된다(): void
{
$user = User::factory()->create([
'email' => 'permlock@example.com',
'password' => Hash::make('correct-password'),
'status' => 'active',
]);
for ($i = 1; $i <= 3; $i++) {
$this->postJson('/api/auth/login', [
'email' => 'permlock@example.com',
'password' => 'wrong-password',
])->assertStatus(401);
}
$user->refresh();
$this->assertTrue((bool) $user->locked_permanently);
$this->assertNull($user->locked_until);
// 하루가 지나도 여전히 잠금 (수정 전: 1분 뒤 자동 해제)
$this->travel(1)->day();
$this->postJson('/api/auth/login', [
'email' => 'permlock@example.com',
'password' => 'correct-password',
])->assertStatus(423);
}
/**
* @test
*/
public function 영구_잠금_응답은_locked_until_이_null_이어도_직렬화된다(): void
{
$user = User::factory()->create([
'email' => 'permlock2@example.com',
'password' => Hash::make('correct-password'),
'status' => 'active',
]);
app(UserRepositoryInterface::class)->lockAccount($user, 0);
// 수정 전: $e->lockedUntil->toIso8601String() 가 null 에서 fatal
$response = $this->postJson('/api/auth/login', [
'email' => 'permlock2@example.com',
'password' => 'correct-password',
]);
$response->assertStatus(423);
$this->assertNull($response->json('errors.locked_until'));
}
/**
* @test
*/
public function 관리자_해제_ap_i_로_영구_잠금을_풀_수_있다(): void
{
$locked = User::factory()->create([
'email' => 'unlockme@example.com',
'password' => Hash::make('correct-password'),
'status' => 'active',
]);
app(UserRepositoryInterface::class)->lockAccount($locked, 0);
$admin = $this->createAdminUser();
$this->actingAs($admin, 'sanctum')
->postJson("/api/admin/users/{$locked->uuid}/unlock")
->assertStatus(200);
$locked->refresh();
$this->assertFalse((bool) $locked->locked_permanently);
$this->assertNull($locked->locked_until);
// actingAs(sanctum) 이 기본 guard 까지 sanctum 으로 고정하므로 되돌린 뒤
// 실제 로그인(Auth::attempt) 가능 여부를 확인한다.
// (actingAs 는 config('auth.defaults.guard') 자체를 sanctum 으로 덮어쓰므로 config 를 다시 읽으면 안 된다)
$this->app['auth']->shouldUse('web');
$this->app['auth']->forgetGuards();
$this->postJson('/api/auth/login', [
'email' => 'unlockme@example.com',
'password' => 'correct-password',
])->assertStatus(200);
}
/**
* @test
*/
public function 권한_없는_사용자는_해제_ap_i_를_호출할_수_없다(): void
{
$locked = User::factory()->create(['status' => 'active']);
app(UserRepositoryInterface::class)->lockAccount($locked, 0);
$member = User::factory()->create(['status' => 'active']);
$this->actingAs($member, 'sanctum')
->postJson("/api/admin/users/{$locked->uuid}/unlock")
->assertStatus(403);
$this->assertTrue((bool) $locked->fresh()->locked_permanently);
}
/**
* self 스코프 역할은 남의 계정을 해제할 수 없다.
*
* 해제 엔드포인트는 신규 권한을 만들지 않고 `core.users.update` 를 재사용한다.
* 기본 manager 역할이 그 권한을 self 스코프로 갖고 있으므로, 스코프가 이 경로에
* 적용되지 않으면 매니저가 임의 계정의 잠금을 푸는 우회로가 된다.
*
* @test
*/
public function self_스코프_역할은_남의_계정_잠금을_해제할_수_없다(): void
{
$locked = User::factory()->create(['status' => 'active']);
app(UserRepositoryInterface::class)->lockAccount($locked, 0);
$manager = $this->createSelfScopedManager();
// 전제 확인 — 이 사용자의 실효 스코프가 정말 self 인가
$this->assertSame('self', $manager->getEffectiveScopeForPermission('core.users.update'));
$this->assertSame('user', PermissionHelper::getResourceRouteKey('core.users.update'));
$this->actingAs($manager, 'sanctum')
->postJson("/api/admin/users/{$locked->uuid}/unlock")
->assertStatus(403);
$this->assertTrue(
(bool) $locked->fresh()->locked_permanently,
'self 스코프 역할이 남의 계정 잠금을 해제했습니다.'
);
}
/**
* @test
*/
public function 유한_잠금_설정은_기존과_동일하게_만료된다(): void
{
$this->setSecuritySettings(['login_lockout_time' => 5]);
$user = User::factory()->create([
'email' => 'tmplock@example.com',
'password' => Hash::make('correct-password'),
'status' => 'active',
]);
for ($i = 1; $i <= 3; $i++) {
$this->postJson('/api/auth/login', [
'email' => 'tmplock@example.com',
'password' => 'wrong-password',
])->assertStatus(401);
}
$this->assertFalse((bool) $user->fresh()->locked_permanently);
$this->travel(6)->minutes();
Cache::flush();
$this->postJson('/api/auth/login', [
'email' => 'tmplock@example.com',
'password' => 'correct-password',
])->assertStatus(200);
}
/**
* 보안 환경설정 값을 테스트용으로 덮어씁니다.
*
* @param array $values 덮어쓸 보안 설정 값
*/
private function setSecuritySettings(array $values): void
{
$existing = (array) config('g7_settings.core.security', []);
config(['g7_settings.core.security' => array_merge($existing, $values)]);
}
/**
* 사용자 수정 권한을 가진 관리자를 생성합니다.
*
* @return User 관리자 사용자
*/
private function createAdminUser(): User
{
$user = User::factory()->create(['is_super' => true, 'status' => 'active']);
$permission = Permission::firstOrCreate(
['identifier' => 'core.users.update'],
[
'name' => json_encode(['ko' => '사용자 수정', 'en' => 'Update Users']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]
);
$adminRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
if (! $adminRole->permissions()->where('permissions.id', $permission->id)->exists()) {
$adminRole->permissions()->attach($permission->id);
}
$user->roles()->attach($adminRole->id, [
'assigned_at' => now(),
'assigned_by' => null,
]);
return $user->fresh();
}
/**
* `core.users.update` 를 self 스코프로만 가진 사용자를 만듭니다 (기본 manager 역할 구성).
*
* @return User 생성된 사용자
*/
private function createSelfScopedManager(): User
{
$user = User::factory()->create(['is_super' => false, 'status' => 'active']);
// resource_route_key/owner_key 는 config/core.php 의 선언과 같아야 한다 —
// 비어 있으면 미들웨어가 스코프 검사를 건너뛰어 이 테스트가 무의미해진다.
$permission = Permission::firstOrCreate(
['identifier' => 'core.users.update'],
[
'name' => json_encode(['ko' => '사용자 수정', 'en' => 'Update Users']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]
);
$permission->forceFill(['resource_route_key' => 'user', 'owner_key' => 'id'])->save();
$role = Role::firstOrCreate(
['identifier' => 'manager'],
[
'name' => json_encode(['ko' => '매니저', 'en' => 'Manager']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
$role->permissions()->syncWithoutDetaching([
$permission->id => ['scope_type' => 'self'],
]);
$user->roles()->attach($role->id, [
'assigned_at' => now(),
'assigned_by' => null,
]);
return $user->fresh();
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
namespace Tests\Feature\Auth;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\HookManager;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\RegisterRequest;
use App\Http\Requests\Auth\ResetPasswordRequest;
use App\Http\Requests\User\ChangePasswordRequest;
use App\Http\Requests\User\CreateUserRequest;
use App\Http\Requests\User\UpdateProfileRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Rules\PasswordPolicy;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\Rules\Password;
use Tests\TestCase;
/**
* 비밀번호 정책 배선 테스트 (C4)
*
* `security.password_min_length` / `security.require_password_special_char` 는 defaults.json
* 에만 존재하고 소비자·저장 규칙·UI 가 전부 없는 완전 고아였습니다. 동시에 7개 FormRequest 가
* 각자 리터럴을 들고 있어 `LoginRequest` 만 `min:6` 으로 어긋나 있었습니다.
*/
class PasswordPolicyTest extends TestCase
{
use RefreshDatabase;
/**
* 검증 규칙 확장 훅을 비웁니다.
*
* `rules()` 는 확장이 규칙을 덧붙이는 필터 훅을 함께 실행한다. 이 테스트가 보려는 것은
* 코어가 선언한 password 규칙이므로, 확장 리스너 의존이 끼어들지 않도록 비운다
* (모듈 프로바이더 등록 여부가 실행 순서에 따라 달라져 결과가 흔들리는 것도 함께 막는다).
*/
protected function setUp(): void
{
parent::setUp();
foreach ([
'core.auth.register_validation_rules',
'core.auth.reset_password_validation_rules',
'core.user.change_password_validation_rules',
'core.user.create_validation_rules',
'core.user.update_validation_rules',
'core.user.update_profile_validation_rules',
] as $filter) {
HookManager::clearFilter($filter);
}
}
/**
* 보안 환경설정 값을 테스트용으로 덮어씁니다.
*
* @param array $values 덮어쓸 보안 설정 값
*/
private function setSecuritySettings(array $values): void
{
$existing = (array) config('g7_settings.core.security', []);
config(['g7_settings.core.security' => array_merge($existing, $values)]);
}
/**
* @test
*/
public function 설정한_최소_길이가_회원가입에_적용된다(): void
{
$this->setSecuritySettings(['password_min_length' => 12]);
// 11자 — 수정 전에는 min:8 리터럴이라 통과했다
$validator = $this->validatePassword('abcdefghijk');
$this->assertTrue($validator->errors()->has('password'));
}
/**
* @test
*/
public function 설정한_최소_길이를_만족하면_통과한다(): void
{
$this->setSecuritySettings(['password_min_length' => 12]);
$validator = $this->validatePassword('abcdefghijkl');
$this->assertFalse($validator->errors()->has('password'));
}
/**
* @test
*/
public function 특수문자_필수_설정이_적용된다(): void
{
$this->setSecuritySettings([
'password_min_length' => 8,
'require_password_special_char' => true,
]);
$validator = $this->validatePassword('abcdefgh');
$this->assertTrue($validator->errors()->has('password'));
}
/**
* @test
*/
public function 로그인_규칙에는_길이_제한이_없다(): void
{
// 로그인은 기존 비밀번호를 대조하는 지점이며, 길이 규칙은 정책 미달 사실을
// 미인증 공격자에게 누설하는 oracle 이 된다. 수정 전에는 min:6 이 있었다.
$rules = (new LoginRequest)->rules();
$this->assertIsString($rules['password']);
$this->assertStringNotContainsString('min:', $rules['password']);
}
/**
* @test
*/
public function 정책_규칙이_설정값을_읽는다(): void
{
$this->setSecuritySettings(['password_min_length' => 20]);
$rule = PasswordPolicy::rule();
// Password 규칙 내부 min 값 확인 (리플렉션 — 공개 접근자가 없음)
$reflection = new \ReflectionProperty($rule, 'min');
$this->assertSame(20, $reflection->getValue($rule));
}
/**
* @test
*/
public function 설정이_비어도_기본값으로_동작한다(): void
{
$this->setSecuritySettings(['password_min_length' => 0]);
$rule = PasswordPolicy::rule();
$reflection = new \ReflectionProperty($rule, 'min');
$this->assertSame(PasswordPolicy::DEFAULT_MIN_LENGTH, $reflection->getValue($rule));
}
/**
* @test
*/
public function 비로그인_비밀번호_요청은_모두_정책을_사용한다(): void
{
$this->setSecuritySettings(['password_min_length' => 17]);
// 비밀번호를 **설정**하는 모든 지점. 한 곳이라도 리터럴로 남으면 그 화면이 정책
// 우회로가 된다 (관리자 사용자 수정 화면이 실제로 min:8 리터럴로 남아 있었다).
$requestClasses = [
RegisterRequest::class,
ResetPasswordRequest::class,
ChangePasswordRequest::class,
CreateUserRequest::class,
UpdateProfileRequest::class,
UpdateUserRequest::class,
];
foreach ($requestClasses as $requestClass) {
$rules = (new $requestClass)->rules();
$passwordRule = collect($rules['password'])->first(fn ($rule) => $rule instanceof Password);
$this->assertNotNull(
$passwordRule,
"{$requestClass} 의 password 규칙이 PasswordPolicy 를 사용하지 않습니다."
);
$reflection = new \ReflectionProperty($passwordRule, 'min');
$this->assertSame(
17,
$reflection->getValue($passwordRule),
"{$requestClass} 가 설정값 대신 리터럴 최소 길이를 사용합니다."
);
}
}
/**
* @test
*/
public function 두_보안_설정_키가_저장_후_재조회에_반영된다(): void
{
// 저장 화이트리스트에 두 키가 없으면 저장 요청이 조용히 탈락해 UI 가 값을 잃는다.
app(ConfigRepositoryInterface::class)->saveCategory('security', [
'password_min_length' => 14,
'require_password_special_char' => true,
]);
$saved = app(ConfigRepositoryInterface::class)->getCategory('security');
$this->assertSame(14, (int) $saved['password_min_length']);
$this->assertTrue((bool) $saved['require_password_special_char']);
}
/**
* 회원가입 요청의 비밀번호 규칙만 실행합니다.
*
* HTTP 엔드포인트를 거치면 확장 리스너 의존이 끼어들어 정책 검증과 무관한 실패가 난다.
*
* @param string $password 검사할 비밀번호
* @return Validator 실행된 검증기
*/
private function validatePassword(string $password)
{
$rules = (new RegisterRequest)->rules();
$validator = $this->app['validator']->make(
['password' => $password, 'password_confirmation' => $password],
['password' => $rules['password']]
);
$validator->passes();
return $validator;
}
}
@@ -40,7 +40,7 @@ class BuildVendorBundleCommandTest extends TestCase
* 의 vendor-bundle.zip 까지 가짜 498-byte zip 으로 덮어쓰는 사고를 방지하기 위해
* 실제 파일을 snapshot 하고 tearDown 에서 복원한다.
*
* @var array<string, string> path => content (binary-safe)
* @var array<string, string> path => content (binary-safe)
*/
private array $realBundleSnapshots = [];
@@ -92,6 +92,11 @@ class BuildVendorBundleCommandTest extends TestCase
$this->restoreRealBundles();
// 스냅샷 해제: 실제 vendor-bundle.zip 은 10MB 단위라 PHPUnit 이 테스트 인스턴스를 스위트
// 종료까지 붙들면 테스트 메서드 수만큼 메모리에 남는다. 전체 스위트를 한 프로세스로
// 실행할 때 memory_limit 을 소진시키는 원인이므로 복구 직후 즉시 비운다.
$this->realBundleSnapshots = [];
parent::tearDown();
}
@@ -0,0 +1,125 @@
<?php
namespace Tests\Feature\Extension;
use App\Extension\Testing\ExtensionTestAllowlist;
use App\Jobs\DispatchHookListenerJob;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 확장 훅 리스너 격리 테스트
*
* 배경: `modules`/`plugins` 등록 행은 테스트 프로세스가 바뀌어도 DB 에 남는다. 그래서 어떤
* 확장의 스위트를 돌린 뒤 다른 확장의 스위트를 돌리면, 앞 확장이 여전히 "활성" 으로 보인다.
* 훅 리스너 등록이 그 활성 판정만 보고 있었던 탓에, ServiceProvider 는 등록되지 않았는데
* 리스너만 등록되어 훅 발화 시 Repository 바인딩이 없어 컨테이너 해석이 실패했다
* (게시판 게시글 삭제 18건이 이 경로로 깨졌다).
*
* `ExtensionTestAllowlist` 는 자기 문서에 "ServiceProvider / route / hook listener 등록 대상"
* 을 허용한다고 선언하면서 실제로는 앞의 둘만 가드하고 있었다. 그 간극을 고정한다.
*/
class HookListenerAllowlistIsolationTest extends TestCase
{
use RefreshDatabase;
/**
* allowlist 가 확장 유형 양쪽(module/plugin)을 판정하는지 확인합니다.
*/
#[Test]
public function allowlist_gates_both_extension_types(): void
{
ExtensionTestAllowlist::set(['modules/sirsoft-board']);
$this->assertTrue(ExtensionTestAllowlist::isActive());
$this->assertTrue(ExtensionTestAllowlist::isAllowed('module', 'sirsoft-board'));
$this->assertFalse(
ExtensionTestAllowlist::isAllowed('module', 'sirsoft-ecommerce'),
'allowlist 밖 모듈이 허용되면 그 모듈의 리스너가 프로바이더 없이 등록된다.'
);
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
}
/**
* 해석할 수 없는 리스너는 호출자의 작업을 깨뜨리지 않고 건너뛰는지 확인합니다.
*
* 수정 전에는 BindingResolutionException 이 그대로 전파돼, 큐 드라이버가 sync 인 환경에서
* 게시글 삭제 요청 자체가 500 이 됐다.
*/
#[Test]
public function unresolvable_listener_is_skipped_instead_of_breaking_the_caller(): void
{
Log::spy();
$job = new DispatchHookListenerJob(
UnwiredExtensionListenerStub::class,
'handle',
[],
[],
);
$job->handle();
Log::shouldHaveReceived('warning')
->withArgs(fn (string $message) => str_contains($message, '훅 리스너를 해석할 수 없어'))
->once();
}
/**
* 리스너 자신의 도메인 예외는 그대로 전파되는지 확인합니다.
*
* 해석 실패만 건너뛰어야 하며, 리스너가 실제로 던진 예외까지 삼키면 실패가 조용해진다.
*/
#[Test]
public function listener_domain_exception_still_propagates(): void
{
$job = new DispatchHookListenerJob(
ThrowingListenerStub::class,
'handle',
[],
[],
);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('도메인 실패');
$job->handle();
}
}
/**
* 배선되지 않은 확장의 리스너 대역 — 해석 불가능한 의존을 요구합니다.
*/
class UnwiredExtensionListenerStub
{
/**
* @param UnboundExtensionContract $dependency 바인딩되지 않은 의존
*/
public function __construct(private UnboundExtensionContract $dependency) {}
/**
* 훅 처리 (도달하지 않아야 함)
*/
public function handle(): void {}
}
/**
* 어떤 구현체도 바인딩되지 않은 계약 (확장 ServiceProvider 미등록 상황 재현용)
*/
interface UnboundExtensionContract {}
/**
* 도메인 예외를 던지는 리스너 대역
*/
class ThrowingListenerStub
{
/**
* 훅 처리 — 도메인 예외 발생
*/
public function handle(): void
{
throw new \RuntimeException('도메인 실패');
}
}
+96 -4
View File
@@ -17,8 +17,12 @@ use Tests\TestCase;
* 새 CacheInterface 기반 캐시 키(`g7:core:ext.modules.active_identifiers` 등)와
* Trait 의 캐시 무효화 동작을 검증합니다.
*
* 참고: 이전의 "빈 배열 캐시 금지" 정책은 새 시스템에서 폐기되었습니다.
* 대신 모듈 설치/활성화 훅에서 invalidateModuleStatusCache() 로 확실히 무효화합니다.
* "빈 배열 캐시 금지" 정책은 한때 폐기되고 명시적 무효화(invalidateModuleStatusCache)에만
* 의존했으나, 그 구조로는 회복 불가능한 실패가 실제로 발생하여 되살렸습니다:
* DB 에는 활성 모듈 3건이 있는데 캐시에는 빈 배열이 남아, 모든 모듈 관리자 화면이 404 가
* 되고 TTL(기본 하루) 이 지나기 전까지 스스로 회복되지 않았습니다. 확장 작업 도중 상태가
* 잠시 active 가 아닌 창이 존재하는 한, 그 순간의 읽기를 막을 방법은 없습니다.
* 따라서 명시적 무효화는 그대로 두되, **빈 결과는 애초에 캐시하지 않습니다**.
*/
class ModuleCacheTest extends TestCase
{
@@ -26,18 +30,27 @@ class ModuleCacheTest extends TestCase
private const PLUGIN_ACTIVE_KEY = 'g7:core:ext.plugins.active_identifiers';
private const TEMP_MODULE = 'vendor-status_window_module';
private const TEMP_PLUGIN = 'vendor-status_window_plugin';
protected function setUp(): void
{
parent::setUp();
Cache::flush();
// 확장 상태 캐시는 개발 환경과 **같은 저장소**를 쓴다. 테스트 DB 에는 확장 행이 없으므로,
// 여기서 계산한 "활성 확장 없음" 이 공유 캐시에 실리면 개발 사이트가 그 값을 읽어
// 모든 모듈 화면이 404 가 된다(실제로 발생). 이 클래스만 메모리 저장소로 격리한다.
config(['cache.default' => 'array']);
Cache::store('array')->flush();
ModuleManager::invalidateModuleStatusCache();
PluginManager::invalidatePluginStatusCache();
}
protected function tearDown(): void
{
Cache::flush();
Cache::store('array')->flush();
parent::tearDown();
}
@@ -101,4 +114,83 @@ class ModuleCacheTest extends TestCase
$this->assertNotNull($cached, '활성 플러그인 목록이 캐시되어야 합니다');
$this->assertEquals($result, $cached);
}
/**
* 빈 결과는 캐시에 남지 않아야 합니다 (모듈).
*
* 확장 작업 중 상태가 잠시 active 가 아닌 창에서 이 목록을 읽으면 빈 배열이 하루 동안
* 굳는다. 그 뒤 상태가 정상으로 돌아와도 모든 모듈이 꺼진 것처럼 동작한다.
*/
#[Test]
public function it_does_not_cache_empty_active_modules(): void
{
// 이 클래스는 RefreshDatabase 를 쓰지 않는다(실제 설치 상태를 읽는 테스트가 섞여 있음).
// 따라서 원래 상태를 기억했다가 반드시 되돌린다.
$originalStatuses = Module::query()->pluck('status', 'identifier')->all();
Module::where('identifier', self::TEMP_MODULE)->delete();
try {
$module = Module::factory()->create([
'identifier' => self::TEMP_MODULE,
'status' => ExtensionStatus::Inactive->value,
]);
// 확장 작업 중 상태 창 재현 — 활성 모듈이 하나도 없는 순간
Module::query()->update(['status' => ExtensionStatus::Inactive->value]);
ModuleManager::invalidateModuleStatusCache();
$this->assertSame([], ModuleManager::getActiveModuleIdentifiers());
$this->assertNull(
Cache::get(self::MODULE_ACTIVE_KEY),
'빈 결과가 캐시되면 상태가 정상으로 돌아와도 하루 동안 모든 모듈이 꺼진 것으로 보입니다.'
);
// 상태 복원 후 무효화 없이도 즉시 반영되어야 한다
$module->update(['status' => ExtensionStatus::Active->value]);
$this->assertContains(
self::TEMP_MODULE,
ModuleManager::getActiveModuleIdentifiers(),
'상태가 정상으로 돌아왔는데도 빈 목록이 반환됩니다 — 스스로 회복되지 않는 상태입니다.'
);
} finally {
Module::where('identifier', self::TEMP_MODULE)->delete();
foreach ($originalStatuses as $identifier => $status) {
Module::where('identifier', $identifier)->update(['status' => $status]);
}
ModuleManager::invalidateModuleStatusCache();
}
}
/**
* 빈 결과는 캐시에 남지 않아야 합니다 (플러그인).
*/
#[Test]
public function it_does_not_cache_empty_active_plugins(): void
{
$originalStatuses = Plugin::query()->pluck('status', 'identifier')->all();
Plugin::where('identifier', self::TEMP_PLUGIN)->delete();
try {
$plugin = Plugin::factory()->create([
'identifier' => self::TEMP_PLUGIN,
'status' => ExtensionStatus::Inactive->value,
]);
Plugin::query()->update(['status' => ExtensionStatus::Inactive->value]);
PluginManager::invalidatePluginStatusCache();
$this->assertSame([], PluginManager::getActivePluginIdentifiers());
$this->assertNull(Cache::get(self::PLUGIN_ACTIVE_KEY));
$plugin->update(['status' => ExtensionStatus::Active->value]);
$this->assertContains(self::TEMP_PLUGIN, PluginManager::getActivePluginIdentifiers());
} finally {
Plugin::where('identifier', self::TEMP_PLUGIN)->delete();
foreach ($originalStatuses as $identifier => $status) {
Plugin::where('identifier', $identifier)->update(['status' => $status]);
}
PluginManager::invalidatePluginStatusCache();
}
}
}
@@ -1030,8 +1030,11 @@ class LayoutExtensionIntegrationTest extends TestCase
$result = $this->service->applyExtensions($layout, $this->template->id);
$handlers = array_column($result['init_actions'] ?? [], 'handler');
// 결과는 표준 키(initActions) 로 통합된다. deprecated 별칭(init_actions)이 함께 남으면
// 엔진의 `initActions || init_actions` 단락이 한쪽을 통째로 무시하므로 제거되어야 한다.
$handlers = array_column($result['initActions'] ?? [], 'handler');
$this->assertSame(['hostInit', 'sirsoft-ecommerce.initPreferredCurrency'], $handlers, '호스트 init_actions 뒤에 확장 init_actions 가 병합되어야 한다');
$this->assertArrayNotHasKey('init_actions', $result, 'deprecated 별칭 키가 남으면 통합 결과가 무시된다');
}
/**
@@ -14,9 +14,10 @@ class TemplateServiceLocalizationTest extends TestCase
{
App::setLocale('ko');
// 메시지는 원인(:error)을 함께 노출한다 — 치환까지 확인해야 자리표시자 누락을 잡는다.
$this->assertEquals(
'파일 복사에 실패했습니다.',
__('templates.errors.file_copy_failed')
'파일 복사에 실패했습니다: 디스크 없음',
__('templates.errors.file_copy_failed', ['error' => '디스크 없음'])
);
$this->assertEquals(
@@ -33,8 +34,8 @@ class TemplateServiceLocalizationTest extends TestCase
App::setLocale('en');
$this->assertEquals(
'Failed to copy files.',
__('templates.errors.file_copy_failed')
'Failed to copy files: disk missing',
__('templates.errors.file_copy_failed', ['error' => 'disk missing'])
);
$this->assertEquals(
@@ -50,13 +51,13 @@ class TemplateServiceLocalizationTest extends TestCase
{
// 한국어로 설정
App::setLocale('ko');
$koreanMessage = __('templates.errors.file_copy_failed');
$this->assertEquals('파일 복사에 실패했습니다.', $koreanMessage);
$koreanMessage = __('templates.errors.file_copy_failed', ['error' => 'x']);
$this->assertEquals('파일 복사에 실패했습니다: x', $koreanMessage);
// 영어로 전환
App::setLocale('en');
$englishMessage = __('templates.errors.file_copy_failed');
$this->assertEquals('Failed to copy files.', $englishMessage);
$englishMessage = __('templates.errors.file_copy_failed', ['error' => 'x']);
$this->assertEquals('Failed to copy files: x', $englishMessage);
// 메시지가 다른지 확인
$this->assertNotEquals($koreanMessage, $englishMessage);
@@ -191,6 +191,76 @@ class TemplateServiceRoutesMergeTest extends TestCase
$this->assertNotEmpty($modulePaths, 'Module routes should be merged');
}
/**
* 활성 모듈의 디렉토리가 없으면 열화 상태로 표시되는지 확인합니다.
*
* 확장 업데이트 중에는 활성 디렉토리가 잠시 비어 그 모듈의 라우트가 통째로 빠진다.
* 이 순간의 응답이 캐시 버전 키에 남으면, 업데이트가 끝난 뒤에도 캐시가 만료될 때까지
* 해당 모듈의 모든 화면이 404 가 된다 — 버전은 이미 올라간 뒤라 스스로 회복되지 않는다.
* 캐시 여부를 판단할 수 있도록 병합 결과가 열화였음을 알려야 한다.
*/
#[Test]
public function route_merge_is_flagged_degraded_when_active_module_directory_is_missing(): void
{
Template::factory()->create([
'identifier' => 'sirsoft-admin_basic',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
]);
$this->templateManager->method('getTemplateInfo')->willReturn([
'identifier' => 'sirsoft-admin_basic',
'type' => 'admin',
]);
// 활성 목록에는 있으나 디렉토리가 없는 모듈 (= 업데이트 중 스왑 창)
$mockModule = $this->createMock(ModuleInterface::class);
$mockModule->method('getIdentifier')->willReturn('vendor-absent_module');
$this->moduleManager->method('getActiveModules')->willReturn([
'vendor-absent_module' => $mockModule,
]);
$result = $this->templateService->getRoutesDataWithModules('sirsoft-admin_basic');
$this->assertTrue($result['success']);
$this->assertTrue(
$result['degraded'],
'활성 모듈 디렉토리가 없는데 열화로 표시되지 않았습니다 — 이 응답이 캐시되면 업데이트 후에도 404 가 남습니다.'
);
$this->assertTrue($this->templateService->lastRouteMergeWasDegraded());
}
/**
* 정상 상태에서는 열화로 표시되지 않는지 확인합니다 (과잉 차단 방지).
*
* 열화 판정이 헐거우면 모든 응답이 캐시되지 않아 매 요청이 디스크 병합으로 떨어진다.
*/
#[Test]
public function route_merge_is_not_flagged_degraded_in_normal_state(): void
{
Template::factory()->create([
'identifier' => 'sirsoft-admin_basic',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
]);
$this->templateManager->method('getTemplateInfo')->willReturn([
'identifier' => 'sirsoft-admin_basic',
'type' => 'admin',
]);
$mockModule = $this->createMock(ModuleInterface::class);
$mockModule->method('getIdentifier')->willReturn('sirsoft-board');
$this->moduleManager->method('getActiveModules')->willReturn([
'sirsoft-board' => $mockModule,
]);
$result = $this->templateService->getRoutesDataWithModules('sirsoft-admin_basic');
$this->assertTrue($result['success']);
$this->assertFalse($result['degraded']);
}
#[Test]
public function returns_error_for_nonexistent_template(): void
{
@@ -0,0 +1,198 @@
<?php
namespace Tests\Feature\Settings;
use App\Http\Requests\Settings\SaveSettingsRequest;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 환경설정 입력 경계값 계약 테스트
*
* 관리자 설정 화면의 숫자 입력 제한(min/max)과 저장 검증 규칙은 같은 값을 말해야 한다.
* 각자 리터럴을 들면 조용히 갈라져 "저장은 되는 값인데 화면이 막는다" 또는 "화면은 받아 놓고
* 저장에서 422" 가 된다. 화면에서도 규칙에서도 `config('core.settings_limits')` 를 읽도록
* 배선했으므로, 그 배선이 풀리지 않았는지 양쪽에서 확인한다.
*/
class SettingsBoundaryContractTest extends TestCase
{
use RefreshDatabase;
/**
* 검사 대상: 설정 키 → 한계값 키 접두사
*
* @return array<string, string>
*/
private function boundKeys(): array
{
return [
'upload.max_file_size' => 'upload_max_file_size',
'upload.image_max_width' => 'upload_image_max_width',
'upload.image_max_height' => 'upload_image_max_height',
'upload.image_quality' => 'upload_image_quality',
'seo.og_image_default_width' => 'seo_og_image_default_width',
'seo.og_image_default_height' => 'seo_og_image_default_height',
'seo.cache_ttl' => 'seo_cache_ttl',
'seo.sitemap_cache_ttl' => 'seo_sitemap_cache_ttl',
'seo.sitemap_urls_per_file' => 'seo_sitemap_urls_per_file',
'security.password_min_length' => 'security_password_min_length',
'security.auth_token_lifetime' => 'security_auth_token_lifetime',
'security.max_login_attempts' => 'security_max_login_attempts',
'security.login_lockout_time' => 'security_login_lockout_time',
'advanced.layout_cache_ttl' => 'advanced_cache_ttl',
'advanced.stats_cache_ttl' => 'advanced_cache_ttl',
'advanced.seo_cache_ttl' => 'advanced_cache_ttl',
'advanced.seo_sitemap_cache_ttl' => 'advanced_seo_sitemap_cache_ttl',
'drivers.redis_port' => 'drivers_redis_port',
'drivers.redis_database' => 'drivers_redis_database',
'drivers.memcached_port' => 'drivers_memcached_port',
'drivers.session_lifetime' => 'drivers_session_lifetime',
'drivers.websocket_port' => 'drivers_websocket_port',
'drivers.websocket_server_port' => 'drivers_websocket_server_port',
'drivers.log_days' => 'drivers_log_days',
'identity.challenge_ttl_minutes' => 'identity_challenge_ttl_minutes',
'identity.max_attempts' => 'identity_max_attempts',
];
}
/**
* 규칙 배열에서 min/max 숫자를 뽑습니다.
*
* @param array<int, mixed>|string $rules 검증 규칙
* @return array{min: string|null, max: string|null} 경계값
*/
private function boundsOf(array|string $rules): array
{
$flat = is_string($rules) ? explode('|', $rules) : $rules;
$found = ['min' => null, 'max' => null];
foreach ($flat as $rule) {
if (! is_string($rule)) {
continue;
}
foreach (['min', 'max'] as $bound) {
if (str_starts_with($rule, $bound.':')) {
$found[$bound] = substr($rule, strlen($bound) + 1);
}
}
// 'integer|min:1|max:1024' 처럼 한 문자열에 묶인 형태
if (str_contains($rule, '|')) {
foreach (explode('|', $rule) as $part) {
foreach (['min', 'max'] as $bound) {
if (str_starts_with($part, $bound.':')) {
$found[$bound] = substr($part, strlen($bound) + 1);
}
}
}
}
}
return $found;
}
/**
* 저장 규칙의 경계값이 한계값 설정과 일치하는지 확인합니다.
*/
#[Test]
public function save_rules_use_the_shared_limit_values(): void
{
$limits = config('core.settings_limits');
$rules = (new SaveSettingsRequest)->rules();
foreach ($this->boundKeys() as $settingKey => $limitPrefix) {
$this->assertArrayHasKey($settingKey, $rules, "{$settingKey} 규칙이 없습니다.");
$bounds = $this->boundsOf($rules[$settingKey]);
foreach (['min', 'max'] as $bound) {
$limitKey = "{$limitPrefix}_{$bound}";
if (! array_key_exists($limitKey, $limits)) {
continue;
}
$this->assertSame(
(string) $limits[$limitKey],
$bounds[$bound],
"{$settingKey} 의 {$bound} 이 한계값 설정({$limitKey})과 다릅니다 — "
.'규칙이 리터럴로 되돌아갔는지 확인하세요.'
);
}
}
}
/**
* 한계값 설정이 바뀌면 규칙도 따라 바뀌는지 확인합니다.
*
* 배선이 풀려 리터럴로 되돌아가면 이 테스트가 먼저 깨진다.
*/
#[Test]
public function changing_a_limit_changes_the_rule(): void
{
config(['core.settings_limits.drivers_log_days_max' => 999]);
$bounds = $this->boundsOf((new SaveSettingsRequest)->rules()['drivers.log_days']);
$this->assertSame('999', $bounds['max']);
}
/**
* 모든 설정 필드가 오류 안내에 쓸 항목명을 갖는지 확인합니다.
*
* 항목명이 없으면 Laravel 이 키를 그대로 풀어 쓴다 — 화면에는
* "security.password min length 필드는 64를 초과하면 안 됩니다" 처럼 내부 식별자가 노출된다.
* 규칙에 필드를 추가하면서 항목명을 빠뜨리는 것이 이 결함의 유일한 경로이므로,
* 규칙 키 전수와 항목명 전수를 직접 대조한다.
*/
#[Test]
public function every_setting_field_has_a_translated_attribute_label(): void
{
$request = new SaveSettingsRequest;
$attributes = $request->attributes();
// 배열 항목 규칙(`foo.*`)은 부모 키의 항목명을 물려받으므로 대조 대상에서 제외한다.
$fieldKeys = array_values(array_filter(
array_keys($request->rules()),
fn (string $key) => str_contains($key, '.') && ! str_contains($key, '*')
));
$missing = array_values(array_filter(
$fieldKeys,
fn (string $key) => ! array_key_exists($key, $attributes)
));
$this->assertSame(
[],
$missing,
'항목명이 없는 설정 필드가 있습니다 — 저장 실패 안내에 내부 식별자가 그대로 노출됩니다: '
.implode(', ', $missing)
);
}
/**
* 항목명이 실제 번역 문장으로 해석되는지 확인합니다.
*
* `attributes()` 에 키를 채워도 lang 파일에 항목이 없으면 `validation.attributes.xxx`
* 라는 키 문자열이 그대로 화면에 나온다 — 내부 식별자 노출이라는 결과는 같다.
*/
#[Test]
public function attribute_labels_resolve_to_real_translations(): void
{
$unresolved = [];
foreach ((new SaveSettingsRequest)->attributes() as $field => $label) {
if (str_starts_with((string) $label, 'validation.attributes.')) {
$unresolved[] = $field;
}
}
$this->assertSame(
[],
$unresolved,
'번역이 없어 키 문자열이 그대로 노출되는 항목명이 있습니다: '.implode(', ', $unresolved)
);
}
}
@@ -0,0 +1,130 @@
<?php
namespace Tests\Feature\Settings;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Http\Requests\Settings\SaveSettingsRequest;
use App\Providers\SettingsServiceProvider;
use App\Repositories\JsonConfigRepository;
use App\Services\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use ReflectionMethod;
use Tests\TestCase;
/**
* 업로드 허용 확장자 저장 계약 테스트 (#493 C2)
*
* 허용 확장자 칸은 콤마로 구분한 한 줄 텍스트다. 즉 관리자가 업로드 탭을 저장하면 이 값은
* 문자열로 들어온다. 그런데 설정을 실제 업로드 제한으로 옮기는 지점은 배열만 받아들여,
* 문자열이 오면 아무 말 없이 버렸다 — 관리자가 확장자를 바꿔도 업로드는 종전 목록으로
* 계속 동작한다. 저장도 성공하고 화면에도 값이 보이므로 어긋난 것을 알 방법이 없다.
*
* 저장 단계에서 배열로 정규화하고, 이미 문자열로 저장된 기존 설치도 반영되도록
* 적용 단계에서 문자열을 수용하는지 양쪽에서 확인한다.
*/
class UploadAllowedExtensionsContractTest extends TestCase
{
use RefreshDatabase;
/**
* 업로드 탭 저장 요청을 검증까지 통과시키고 검증 결과를 반환합니다.
*
* @param mixed $allowedExtensions 허용 확장자 입력값
* @return array 검증을 통과한 입력 데이터
*/
private function validatedUploadPayload(mixed $allowedExtensions): array
{
$request = SaveSettingsRequest::create('/api/admin/settings', 'POST', [
'_tab' => 'upload',
'upload' => [
'max_file_size' => 20,
'allowed_extensions' => $allowedExtensions,
],
]);
$request->setContainer($this->app)->validateResolved();
return $request->validated();
}
/**
* applyUploadConfig 를 리플렉션으로 호출합니다.
*
* @param array $uploadSettings upload 카테고리 설정 데이터
*/
private function applyUploadConfig(array $uploadSettings): void
{
$configRepository = $this->createMock(JsonConfigRepository::class);
$configRepository->method('getCategory')
->with('upload')
->willReturn($uploadSettings);
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyUploadConfig');
$method->invoke($provider, $configRepository);
}
/**
* 화면이 보내는 콤마 문자열이 저장 단계에서 배열로 정규화되는지 확인합니다.
*/
#[Test]
public function comma_string_is_normalized_to_an_array_before_saving(): void
{
$validated = $this->validatedUploadPayload('JPG, .png ,pdf,,');
$this->assertSame(
['jpg', 'png', 'pdf'],
$validated['upload']['allowed_extensions'],
'허용 확장자 문자열이 배열로 정규화되지 않았습니다 — 저장돼도 업로드 제한에 반영되지 않습니다.'
);
}
/**
* 배열로 보내는 경로(API 직접 호출 등)도 같은 형태로 정규화되는지 확인합니다.
*/
#[Test]
public function array_input_is_normalized_the_same_way(): void
{
$validated = $this->validatedUploadPayload(['JPG', '.PNG', ' pdf ']);
$this->assertSame(['jpg', 'png', 'pdf'], $validated['upload']['allowed_extensions']);
}
/**
* 저장한 확장자 목록이 실제 업로드 제한으로 이어지는지 확인합니다 (저장 → 적용 전 구간).
*/
#[Test]
public function saved_extensions_reach_the_upload_restriction(): void
{
config(['attachment.allowed_extensions' => ['gif']]);
$validated = $this->validatedUploadPayload('jpg,png');
app(SettingsService::class)->saveSettings($validated);
$stored = app(ConfigRepositoryInterface::class)->getCategory('upload');
$this->assertSame(['jpg', 'png'], $stored['allowed_extensions']);
$this->applyUploadConfig($stored);
$this->assertSame(['jpg', 'png'], config('attachment.allowed_extensions'));
}
/**
* 이미 문자열로 저장된 기존 설치도 업로드 제한에 반영되는지 확인합니다.
*/
#[Test]
public function legacy_string_value_already_on_disk_is_still_applied(): void
{
config(['attachment.allowed_extensions' => ['gif']]);
$this->applyUploadConfig(['allowed_extensions' => 'JPG, .png , pdf']);
$this->assertSame(
['jpg', 'png', 'pdf'],
config('attachment.allowed_extensions'),
'문자열로 저장된 기존 설정이 업로드 제한에 반영되지 않았습니다.'
);
}
}
@@ -72,7 +72,8 @@ class AdminBladeTemplateLoadingTest extends TestCase
$response->assertSee('data-template-id="sirsoft-admin_basic"', false);
// 템플릿 엔진 초기화 스크립트 확인
$response->assertSee("templateId: 'sirsoft-admin_basic'", false);
// 초기화 설정은 @json 으로 직렬화된다 — 표기는 JSON 형태여야 한다.
$response->assertSee('"templateId":"sirsoft-admin_basic"', false);
}
/**
@@ -106,7 +107,8 @@ class AdminBladeTemplateLoadingTest extends TestCase
$response->assertSee('data-template-id="sirsoft-admin_basic"', false);
// 템플릿 엔진 초기화 스크립트에 기본값 확인
$response->assertSee("templateId: 'sirsoft-admin_basic'", false);
// 초기화 설정은 @json 으로 직렬화된다 — 표기는 JSON 형태여야 한다.
$response->assertSee('"templateId":"sirsoft-admin_basic"', false);
}
/**
@@ -184,9 +186,10 @@ class AdminBladeTemplateLoadingTest extends TestCase
// Assert: 템플릿 엔진 초기화 설정 확인
$response->assertStatus(200);
$response->assertSee("templateId: 'sirsoft-admin_basic'", false);
$response->assertSee('locale:', false); // locale 값은 테스트 환경에 따라 'en' 또는 'ko'일 수 있음
$response->assertSee('debug:', false);
// 초기화 설정은 @json 으로 직렬화된다 — 표기는 JSON 형태여야 한다.
$response->assertSee('"templateId":"sirsoft-admin_basic"', false);
$response->assertSee('"locale":', false); // locale 값은 테스트 환경에 따라 'en' 또는 'ko'일 수 있음
$response->assertSee('"debug":', false);
}
/**
@@ -125,7 +125,7 @@ class TemplateExternalsRenderingTest extends TestCase
$this->assertStringContainsString('href="https://cdn.example.com/user.css"', $html);
$this->assertStringContainsString('src="https://cdn.example.com/user.js"', $html);
$this->assertStringContainsString("templateType: 'user'", $html);
$this->assertStringContainsString('"templateType":"user"', $html);
$this->assertBefore($html, 'href="https://cdn.example.com"', 'href="https://cdn.example.com/user.css"');
}
@@ -199,18 +199,33 @@ class TemplateExternalsRenderingTest extends TestCase
'js' => ['dist/js/components.iife.js'],
],
'components' => ['basic' => [], 'composite' => [], 'layout' => []],
// 에러 레이아웃 식별자는 디렉토리 접두사를 포함한다 (실제 템플릿과 동일 규약).
// 접두사를 빼면 활성화 검증이 layouts/error_404.json 을 찾다가 실패한다.
'error_config' => [
'layouts' => [
'404' => 'error_404',
'403' => 'error_403',
'500' => 'error_500',
'404' => 'errors/404',
'403' => 'errors/403',
'500' => 'errors/500',
],
],
'externals' => $externals,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
File::put($this->fixtureTemplatePath.'/components.json', json_encode(['components' => []], JSON_PRETTY_PRINT));
File::put($this->fixtureTemplatePath.'/routes.json', json_encode(['routes' => []], JSON_PRETTY_PRINT));
// 사용자 템플릿은 홈 라우트가 있어야 `/` 요청이 렌더된다 — 없으면 catch-all 이 404 를
// 돌려주어 externals 가 실린 화면 자체를 검사할 수 없다.
File::put($this->fixtureTemplatePath.'/routes.json', json_encode([
'routes' => [
['path' => '/', 'layout' => 'home', 'auth_required' => false],
],
], JSON_PRETTY_PRINT));
File::put($this->fixtureTemplatePath.'/layouts/home.json', json_encode([
'version' => '1.0.0',
'layout_name' => 'home',
'meta' => ['title' => 'Home'],
'components' => [],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
File::put($this->fixtureTemplatePath.'/dist/js/components.iife.js', '// test bundle');
File::put($this->fixtureTemplatePath.'/dist/css/components.css', '/* test css */');
$errorLayout = json_encode([
@@ -219,9 +234,9 @@ class TemplateExternalsRenderingTest extends TestCase
'meta' => ['title' => 'Error'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
File::put($this->fixtureTemplatePath.'/layouts/errors/error_404.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/error_403.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/error_500.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/404.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/403.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/500.json', $errorLayout);
}
private function deleteFixtureTemplate(): void
@@ -66,6 +66,40 @@ test('#466 - 토글을 클릭하면 상태가 바뀌고 저장 버튼이 활성
await expect(page.locator('#save_button')).toBeEnabled({ timeout: 10_000 });
});
// @scenario tab=security, permitted=yes
// @effects password_limit_binding_resolved
test('#493 - 비밀번호 최소 길이의 경계값이 서버 한계값에서 실제로 해석된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoSecurityTab(page);
const input = page.locator('input[name="security.password_min_length"]').first();
await expect(input).toBeAttached({ timeout: 20_000 });
// 서버가 실제로 내려주는 한계값 목록을 그대로 읽는다
const limits = await page.evaluate(async (bearer) => {
const response = await fetch('/api/admin/settings', {
headers: { Authorization: `Bearer ${bearer}`, Accept: 'application/json' },
});
const body = await response.json();
return (body?.data?._meta?.limits ?? {}) as Record<string, number>;
}, token);
// 화면이 참조하는 키가 응답에 없으면 바인딩은 영구히 폴백으로 떨어진다.
// 값(6/64)이 폴백과 같아 화면만 봐서는 구분되지 않으므로 키 존재로 판정한다.
expect(
Object.keys(limits),
'보안 한계값이 설정 응답에 실려 있지 않습니다.',
).toContain('security_password_min_length_min');
expect(Object.keys(limits)).toContain('security_password_min_length_max');
// 렌더된 경계값이 서버 한계값과 일치한다
await expect(input).toHaveAttribute('min', String(limits.security_password_min_length_min));
await expect(input).toHaveAttribute('max', String(limits.security_password_min_length_max));
});
/**
* 보안 탭 토글의 on/off 상태를 읽는다 (sr-only checkbox 의 checked 기준).
*/
+26
View File
@@ -5,7 +5,9 @@ namespace Tests;
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\Testing\ExtensionTestAllowlist;
use App\Helpers\PermissionHelper;
use App\Listeners\Identity\EnforceIdentityPolicyListener;
use App\Support\AssetUrl;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
@@ -52,6 +54,12 @@ abstract class TestCase extends BaseTestCase
$this->afterApplicationCreated(function () {
$this->fakeSettingsDisk();
$this->pinEnvironmentDependentSettings();
// 권한 스코프 캐시는 정적이라 프로세스 전체에 남는다 — 케이스마다 DB 는
// 초기화되는데 캐시만 남으면 앞 케이스의 권한 행 상태가 뒤로 새어,
// 스코프 검사가 조용히 건너뛰어진다 (개별 통과 / 스위트 실패).
PermissionHelper::clearPermissionScopeCache();
});
if (! self::$staleConnectionsCleaned) {
@@ -85,6 +93,24 @@ abstract class TestCase extends BaseTestCase
Storage::fake('settings');
}
/**
* 개발 사이트 설정이 테스트 결과를 좌우하는 항목을 기본값으로 고정합니다.
*
* 설정 *읽기* 는 부팅 시 `g7_settings.*` Config 로 적재되므로 디스크 페이크보다 앞섭니다
* (fakeSettingsDisk 주석 참조). 즉 개발자가 자기 사이트에 어떤 값을 저장해 두었는지가
* 그대로 테스트에 흘러듭니다.
*
* `general.asset_url_mode` 가 그 예다. 개발 사이트를 확장자 없는 모드로 운영하면
* 기본 모드를 전제한 테스트(자산 URL 생성·blade 렌더)가 그 환경에서만 무더기로 깨진다.
* 실제로 이 환경에서 8건이 그렇게 실패했다.
*
* 다른 모드를 검증해야 하는 테스트는 `AssetUrl::forceMode()` 로 자기 전제를 명시한다.
*/
private function pinEnvironmentDependentSettings(): void
{
config(['g7_settings.core.general.asset_url_mode' => AssetUrl::MODE_EXTENSION]);
}
/**
* mail 채널을 발송 준비 완료 상태로 만듭니다.
*
@@ -0,0 +1,89 @@
<?php
namespace Tests\Unit\Extension;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\TestCase;
/**
* 확장 업데이트의 상태 복원 ↔ 캐시 무효화 대칭성 테스트
*
* 업데이트는 시작 시 상태를 `updating` 으로 바꾼다. 그 창에서 누군가 활성 확장 목록을 읽으면
* 그 확장이 빠진 목록이 캐시(기본 TTL 하루)에 남는다. 성공 경로는 마지막에 캐시를 비우지만,
* 실패 경로가 상태만 되돌리고 캐시를 비우지 않으면 확장은 정상인데 그 관리자 화면만
* 하루 동안 404 가 된다 — 운영자가 원인을 짐작하기 어렵고 스스로 회복되지도 않는다.
*
* 상태를 되돌리는 지점마다 캐시 무효화가 따라붙는지 구조로 고정한다.
*/
class ExtensionUpdateStatusCacheSymmetryTest extends TestCase
{
/**
* 상태 복원 횟수만큼 캐시 무효화가 존재하는지 검증합니다.
*
* @param string $relativePath 검사 대상 매니저 파일 경로
* @param string $invalidateCall 해당 매니저의 캐시 무효화 호출 문자열
*/
#[Test]
#[TestWith(['app/Extension/ModuleManager.php', 'updateModule', 'invalidateModuleStatusCache()'])]
#[TestWith(['app/Extension/PluginManager.php', 'updatePlugin', 'invalidatePluginStatusCache()'])]
public function every_status_restore_is_followed_by_cache_invalidation(string $relativePath, string $method, string $invalidateCall): void
{
$body = $this->updateMethodSource(base_path($relativePath), $method);
$restores = preg_match_all("/'status'\s*=>\s*\\\$previousStatus/", $body);
$invalidations = substr_count($body, $invalidateCall);
$this->assertGreaterThan(0, $restores, "{$relativePath} 에서 상태 복원 지점을 찾지 못했습니다 — 검사가 무력화됐습니다.");
$this->assertGreaterThanOrEqual(
$restores,
$invalidations,
"{$relativePath}: 상태 복원 {$restores}회에 비해 캐시 무효화가 {$invalidations}회뿐입니다 — "
.'복원했는데 비우지 않은 경로가 있으면 그 확장 화면이 캐시 만료까지 404 로 남습니다.'
);
}
/**
* 업데이트 메서드 본문을 주석 제거 후 반환합니다.
*
* 주석을 남겨 두면 설명 문장에 들어 있는 호출 표기가 검사를 통과시킨다.
*
* @param string $path 대상 파일 절대 경로
* @param string $method 대상 메서드명 (updateModule / updatePlugin)
* @return string 주석이 제거된 메서드 본문
*/
private function updateMethodSource(string $path, string $method): string
{
$this->assertFileExists($path);
$stripped = '';
foreach (token_get_all(file_get_contents($path)) as $token) {
if (is_array($token) && in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
$stripped .= is_array($token) ? $token[1] : $token;
}
$start = strpos($stripped, "public function {$method}(");
$this->assertNotFalse($start, "{$path} 에서 {$method}() 메서드를 찾지 못했습니다.");
// 중괄호 균형으로 메서드 본문 끝을 찾는다
$open = strpos($stripped, '{', $start);
$depth = 0;
$length = strlen($stripped);
for ($i = $open; $i < $length; $i++) {
if ($stripped[$i] === '{') {
$depth++;
} elseif ($stripped[$i] === '}') {
$depth--;
if ($depth === 0) {
return substr($stripped, $open, $i - $open + 1);
}
}
}
$this->fail("{$path} 의 update() 본문 끝을 찾지 못했습니다.");
}
}
@@ -6,6 +6,7 @@ use App\Extension\HookArgumentSerializer;
use App\Jobs\DispatchHookListenerJob;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Tests\TestCase;
@@ -100,6 +101,51 @@ class DispatchHookListenerJobTest extends TestCase
$this->assertEquals('198.51.100.7', ContextAwareStubListener::$capturedIp);
$this->assertEquals('api/admin/settings', ContextAwareStubListener::$capturedPath);
}
/**
* Job 실행 후 원래 요청 바인딩이 되돌려지는지 검증합니다.
*
* 큐 드라이버가 sync 면 이 Job 은 원 HTTP 요청과 같은 컨테이너에서 실행됩니다.
* 컨텍스트 복원이 재구성 Request 를 바인딩한 채 끝나면, 그 뒤로 이어지는 같은 요청의
* 코드가 헤더·입력이 지워진 가짜 GET 요청을 보게 됩니다 — 뒤 순위 훅 리스너가 전송
* 헤더를 읽지 못해 조용히 건너뛰는 사고가 여기서 납니다.
*/
public function test_job_restores_original_request_binding_after_handle(): void
{
ContextAwareStubListener::reset();
$original = Request::create(
'/api/auth/login',
'POST',
[],
[],
[],
['HTTP_X_CART_KEY' => 'ck_'.str_repeat('a', 32)],
);
app()->instance('request', $original);
$job = new DispatchHookListenerJob(
ContextAwareStubListener::class,
'capture',
HookArgumentSerializer::serialize([]),
[
'ip_address' => '198.51.100.7',
'user_agent' => 'WorkerAgent/1.0',
'locale' => 'ko',
'path' => 'api/auth/login',
]
);
$job->handle();
$this->assertSame($original, app('request'), 'Job 이 원 요청 바인딩을 되돌리지 않았습니다.');
$this->assertSame(
'ck_'.str_repeat('a', 32),
request()->header('X-Cart-Key'),
'큐 리스너 실행 후 원 요청의 헤더가 사라졌습니다 — 뒤 순위 리스너가 전송 헤더를 읽지 못합니다.'
);
$this->assertSame('POST', request()->getMethod());
}
}
class StubJobListener
@@ -2,10 +2,10 @@
namespace Tests\Unit\Listeners;
use App\ActivityLog\ChangeDetector;
use App\Enums\ActivityLogType;
use App\Listeners\CoreActivityLogListener;
use App\Models\ActivityLog;
use App\Models\Attachment;
use App\Models\Schedule;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
@@ -62,10 +62,6 @@ class CoreActivityLogListenerTest extends TestCase
/**
* User mock 생성
*
* @param int $id
* @param string $uuid
* @param string $email
* @param string $name
* @return MockInterface|User
*/
private function createUserMock(int $id = 1, string $uuid = 'uuid-123', string $email = 'test@test.com', string $name = 'Test User'): MockInterface
@@ -79,8 +75,6 @@ class CoreActivityLogListenerTest extends TestCase
/**
* Model mock 생성
*
* @param int $id
* @param array $extraAttributes
* @return MockInterface|Model
*/
private function createModelMock(int $id = 1, array $extraAttributes = []): MockInterface
@@ -93,11 +87,6 @@ class CoreActivityLogListenerTest extends TestCase
/**
* logChannel->info() 기대 설정 헬퍼
*
* @param string $expectedAction
* @param ActivityLogType $expectedLogType
* @param string $expectedDescriptionKey
* @param bool $expectLoggable
*/
private function expectLogInfo(
string $expectedAction,
@@ -129,12 +118,13 @@ class CoreActivityLogListenerTest extends TestCase
// getSubscribedHooks 테스트
// ═══════════════════════════════════════════
public function test_getSubscribedHooks_returns_all_hooks(): void
public function test_get_subscribed_hooks_returns_all_hooks(): void
{
$hooks = CoreActivityLogListener::getSubscribedHooks();
// 64개 로깅(after_*) 훅 (mail_template 2개 제거됨, IDV/auth 후속 추가 분 포함, develop 머지 후 +2)
$this->assertCount(64, $hooks);
// 65개 로깅(after_*) 훅 (mail_template 2개 제거됨, IDV/auth 후속 추가 분 포함,
// develop 머지 후 +2, 관리자 계정 잠금 해제(core.auth.account_unlocked) +1)
$this->assertCount(65, $hooks);
}
public function test_handle_does_nothing(): void
@@ -148,7 +138,7 @@ class CoreActivityLogListenerTest extends TestCase
// User 핸들러 테스트 (8개)
// ═══════════════════════════════════════════
public function test_handleUserAfterCreate_logs_activity(): void
public function test_handle_user_after_create_logs_activity(): void
{
$user = $this->createUserMock(1, 'uuid-abc', 'new@test.com', 'New User');
@@ -167,7 +157,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterCreate($user, ['email' => 'new@test.com']);
}
public function test_handleUserAfterUpdate_logs_activity_with_changes(): void
public function test_handle_user_after_update_logs_activity_with_changes(): void
{
$user = $this->createUserMock(1, 'uuid-abc');
@@ -186,7 +176,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterUpdate($user, ['name' => 'Updated']);
}
public function test_handleUserAfterUpdate_accepts_snapshot_argument(): void
public function test_handle_user_after_update_accepts_snapshot_argument(): void
{
$user = $this->createUserMock(1, 'uuid-abc');
$snapshot = ['id' => 1, 'name' => 'Old Name'];
@@ -201,7 +191,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterUpdate($user, [], $snapshot);
}
public function test_handleUserAfterDelete_logs_activity(): void
public function test_handle_user_after_delete_logs_activity(): void
{
// id 없는 경우 — ActivityLog::where() 호출 스킵, 로깅만 검증
$userData = ['uuid' => 'uuid-del', 'email' => 'del@test.com'];
@@ -219,7 +209,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterDelete($userData);
}
public function test_handleUserAfterDelete_handles_missing_uuid(): void
public function test_handle_user_after_delete_handles_missing_uuid(): void
{
// uuid 없는 경우 — 빈 문자열 fallback 검증
$userData = [];
@@ -234,7 +224,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterDelete($userData);
}
public function test_handleUserAfterWithdraw_logs_activity(): void
public function test_handle_user_after_withdraw_logs_activity(): void
{
$user = $this->createUserMock(1, 'uuid-wd');
@@ -243,7 +233,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterWithdraw($user);
}
public function test_handleUserAfterShow_logs_activity(): void
public function test_handle_user_after_show_logs_activity(): void
{
$user = $this->createUserMock(1, 'uuid-show');
@@ -260,7 +250,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterShow($user);
}
public function test_handleUserAfterList_logs_activity(): void
public function test_handle_user_after_list_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -274,7 +264,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterList(25);
}
public function test_handleUserAfterSearch_logs_activity(): void
public function test_handle_user_after_search_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -289,7 +279,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleUserAfterSearch('john', 3);
}
public function test_handleUserAfterBulkUpdate_logs_per_item(): void
public function test_handle_user_after_bulk_update_logs_per_item(): void
{
$users = collect([
User::factory()->create(),
@@ -320,7 +310,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->assertCount(3, $loggedContexts);
}
public function test_handleUserAfterBulkUpdate_skips_nonexistent_uuids(): void
public function test_handle_user_after_bulk_update_skips_nonexistent_uuids(): void
{
$user = User::factory()->create();
@@ -338,7 +328,7 @@ class CoreActivityLogListenerTest extends TestCase
// Auth 핸들러 테스트 (6개)
// ═══════════════════════════════════════════
public function test_handleAuthAfterLogin_logs_activity(): void
public function test_handle_auth_after_login_logs_activity(): void
{
$user = $this->createUserMock(1);
@@ -355,7 +345,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAuthAfterLogin($user, ['ip' => '127.0.0.1']);
}
public function test_handleAuthLogout_logs_activity(): void
public function test_handle_auth_logout_logs_activity(): void
{
$user = $this->createUserMock(2);
@@ -372,7 +362,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAuthLogout($user);
}
public function test_handleAuthRegister_logs_activity_with_user_type(): void
public function test_handle_auth_register_logs_activity_with_user_type(): void
{
// auth 경로는 사용자 화면이므로 User 타입으로 자동 결정
$this->app->instance('request', Request::create('/api/auth/register'));
@@ -391,7 +381,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAuthRegister($user, ['email' => 'new@test.com']);
}
public function test_handleAuthForgotPassword_logs_activity(): void
public function test_handle_auth_forgot_password_logs_activity(): void
{
$this->app->instance('request', Request::create('/api/auth/forgot-password'));
$user = $this->createUserMock(4);
@@ -409,7 +399,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAuthForgotPassword($user);
}
public function test_handleAuthResetPassword_logs_activity(): void
public function test_handle_auth_reset_password_logs_activity(): void
{
$this->app->instance('request', Request::create('/api/auth/reset-password'));
$user = $this->createUserMock(5);
@@ -427,7 +417,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAuthResetPassword($user);
}
public function test_handleAuthRecordConsents_logs_activity(): void
public function test_handle_auth_record_consents_logs_activity(): void
{
$this->app->instance('request', Request::create('/api/auth/record-consents'));
$user = $this->createUserMock(6);
@@ -450,7 +440,7 @@ class CoreActivityLogListenerTest extends TestCase
// Role 핸들러 테스트 (5개)
// ═══════════════════════════════════════════
public function test_handleRoleAfterCreate_logs_activity(): void
public function test_handle_role_after_create_logs_activity(): void
{
$role = $this->createModelMock(10, ['name' => 'Editor']);
@@ -468,7 +458,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleRoleAfterCreate($role);
}
public function test_handleRoleAfterUpdate_logs_activity_with_changes(): void
public function test_handle_role_after_update_logs_activity_with_changes(): void
{
$role = $this->createModelMock(10, ['name' => 'SuperEditor']);
@@ -486,7 +476,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleRoleAfterUpdate($role);
}
public function test_handleRoleAfterUpdate_accepts_snapshot_argument(): void
public function test_handle_role_after_update_accepts_snapshot_argument(): void
{
$role = $this->createModelMock(10, ['name' => 'Editor']);
$snapshot = ['id' => 10, 'name' => 'Old Role'];
@@ -501,7 +491,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleRoleAfterUpdate($role, $snapshot);
}
public function test_handleRoleAfterDelete_logs_activity(): void
public function test_handle_role_after_delete_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -516,7 +506,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleRoleAfterDelete(99);
}
public function test_handleRoleAfterSyncPermissions_logs_activity(): void
public function test_handle_role_after_sync_permissions_logs_activity(): void
{
$role = $this->createModelMock(10);
$previous = ['users.view', 'users.create'];
@@ -537,7 +527,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleRoleAfterSyncPermissions($role, $previous, $current);
}
public function test_handleRoleAfterToggleStatus_logs_activity(): void
public function test_handle_role_after_toggle_status_logs_activity(): void
{
$role = $this->createModelMock(10);
@@ -550,7 +540,7 @@ class CoreActivityLogListenerTest extends TestCase
// Menu 핸들러 테스트 (6개)
// ═══════════════════════════════════════════
public function test_handleMenuAfterCreate_logs_activity(): void
public function test_handle_menu_after_create_logs_activity(): void
{
$menu = $this->createModelMock(5, ['title' => 'Settings']);
@@ -568,7 +558,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterCreate($menu);
}
public function test_handleMenuAfterUpdate_logs_activity_with_changes(): void
public function test_handle_menu_after_update_logs_activity_with_changes(): void
{
$menu = $this->createModelMock(5, ['title' => 'Updated Settings']);
@@ -586,7 +576,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterUpdate($menu);
}
public function test_handleMenuAfterUpdate_accepts_snapshot_argument(): void
public function test_handle_menu_after_update_accepts_snapshot_argument(): void
{
$menu = $this->createModelMock(5, ['title' => 'Settings']);
$snapshot = ['id' => 5, 'title' => 'Old Title'];
@@ -601,7 +591,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterUpdate($menu, $snapshot);
}
public function test_handleMenuAfterDelete_logs_activity(): void
public function test_handle_menu_after_delete_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -616,7 +606,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterDelete(77);
}
public function test_handleMenuAfterUpdateOrder_logs_activity(): void
public function test_handle_menu_after_update_order_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -629,7 +619,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterUpdateOrder([['id' => 1, 'order' => 0], ['id' => 2, 'order' => 1]]);
}
public function test_handleMenuAfterToggleStatus_logs_activity(): void
public function test_handle_menu_after_toggle_status_logs_activity(): void
{
$menu = $this->createModelMock(5);
@@ -638,7 +628,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleMenuAfterToggleStatus($menu);
}
public function test_handleMenuAfterSyncRoles_logs_activity(): void
public function test_handle_menu_after_sync_roles_logs_activity(): void
{
$menu = $this->createModelMock(5);
$previous = [1, 2, 3];
@@ -663,7 +653,7 @@ class CoreActivityLogListenerTest extends TestCase
// Settings 핸들러 테스트 (2개)
// ═══════════════════════════════════════════
public function test_handleSettingsAfterSave_logs_activity(): void
public function test_handle_settings_after_save_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -678,7 +668,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleSettingsAfterSave('general', ['site_name' => 'G7', 'site_url' => 'https://g7.dev'], true);
}
public function test_handleSettingsAfterSet_logs_activity(): void
public function test_handle_settings_after_set_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -696,7 +686,7 @@ class CoreActivityLogListenerTest extends TestCase
// Schedule 핸들러 테스트 (6개)
// ═══════════════════════════════════════════
public function test_handleScheduleAfterCreate_logs_activity(): void
public function test_handle_schedule_after_create_logs_activity(): void
{
$schedule = $this->createModelMock(7);
@@ -713,7 +703,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterCreate($schedule);
}
public function test_handleScheduleAfterUpdate_logs_activity_with_changes(): void
public function test_handle_schedule_after_update_logs_activity_with_changes(): void
{
$schedule = $this->createModelMock(7);
@@ -731,7 +721,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterUpdate($schedule);
}
public function test_handleScheduleAfterUpdate_accepts_snapshot_argument(): void
public function test_handle_schedule_after_update_accepts_snapshot_argument(): void
{
$schedule = $this->createModelMock(7);
$snapshot = ['id' => 7, 'command' => 'old:command'];
@@ -746,7 +736,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterUpdate($schedule, $snapshot);
}
public function test_handleScheduleAfterDelete_logs_activity(): void
public function test_handle_schedule_after_delete_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -761,7 +751,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterDelete(15);
}
public function test_handleScheduleAfterRun_logs_activity(): void
public function test_handle_schedule_after_run_logs_activity(): void
{
$schedule = $this->createModelMock(7);
$history = $this->createModelMock(100);
@@ -779,7 +769,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterRun($schedule, $history);
}
public function test_handleScheduleAfterBulkUpdate_logs_per_item(): void
public function test_handle_schedule_after_bulk_update_logs_per_item(): void
{
$schedules = collect([
Schedule::create(['name' => 'Schedule A', 'command' => 'test:a', 'expression' => '* * * * *']),
@@ -810,7 +800,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->assertCount(3, $loggedContexts);
}
public function test_handleScheduleAfterBulkUpdate_skips_nonexistent_ids(): void
public function test_handle_schedule_after_bulk_update_skips_nonexistent_ids(): void
{
$schedule = Schedule::create(['name' => 'Schedule X', 'command' => 'test:x', 'expression' => '* * * * *']);
@@ -824,7 +814,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleScheduleAfterBulkUpdate([$schedule->id, 99999], true, 2);
}
public function test_handleScheduleAfterBulkDelete_logs_per_item(): void
public function test_handle_schedule_after_bulk_delete_logs_per_item(): void
{
$ids = [4, 5];
@@ -854,7 +844,7 @@ class CoreActivityLogListenerTest extends TestCase
// Attachment 핸들러 테스트 (3개)
// ═══════════════════════════════════════════
public function test_handleAttachmentAfterUpload_logs_activity(): void
public function test_handle_attachment_after_upload_logs_activity(): void
{
$attachment = $this->createModelMock(20);
@@ -863,7 +853,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAttachmentAfterUpload($attachment);
}
public function test_handleAttachmentAfterDelete_logs_activity(): void
public function test_handle_attachment_after_delete_logs_activity(): void
{
$attachment = $this->createModelMock(20);
@@ -878,7 +868,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleAttachmentAfterDelete($attachment);
}
public function test_handleAttachmentAfterBulkDelete_creates_per_item_logs(): void
public function test_handle_attachment_after_bulk_delete_creates_per_item_logs(): void
{
$ids = [10, 20, 30];
$snapshots = [
@@ -897,7 +887,7 @@ class CoreActivityLogListenerTest extends TestCase
$loggedIds[] = $context['loggable_id'];
return $context['log_type'] === ActivityLogType::Admin
&& $context['loggable_type'] === \App\Models\Attachment::class
&& $context['loggable_type'] === Attachment::class
&& $context['description_key'] === 'activity_log.description.attachment_bulk_delete'
&& $context['description_params']['count'] === 1
&& $context['properties']['identifier'] === 'post-images'
@@ -957,7 +947,7 @@ class CoreActivityLogListenerTest extends TestCase
];
}
public function test_handleModuleAfterInstall_includes_version_in_properties(): void
public function test_handle_module_after_install_includes_version_in_properties(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -970,7 +960,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleModuleAfterInstall('sirsoft-ecommerce', ['version' => '2.0.0']);
}
public function test_handleModuleAfterUninstall_logs_activity(): void
public function test_handle_module_after_uninstall_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -986,7 +976,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleModuleAfterUninstall('sirsoft-ecommerce', ['version' => '1.0.0'], true);
}
public function test_handleModuleAfterUpdate_logs_activity(): void
public function test_handle_module_after_update_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1002,7 +992,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleModuleAfterUpdate('sirsoft-ecommerce', ['success' => true], ['version' => '1.1.0']);
}
public function test_handleModuleAfterRefreshLayouts_logs_activity(): void
public function test_handle_module_after_refresh_layouts_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1061,7 +1051,7 @@ class CoreActivityLogListenerTest extends TestCase
];
}
public function test_handlePluginAfterInstall_includes_version_in_properties(): void
public function test_handle_plugin_after_install_includes_version_in_properties(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1074,7 +1064,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handlePluginAfterInstall('sirsoft-payment', ['version' => '3.0.0']);
}
public function test_handlePluginAfterUninstall_logs_activity(): void
public function test_handle_plugin_after_uninstall_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1090,7 +1080,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handlePluginAfterUninstall('sirsoft-payment', false, true);
}
public function test_handlePluginAfterUpdate_logs_activity(): void
public function test_handle_plugin_after_update_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1110,7 +1100,7 @@ class CoreActivityLogListenerTest extends TestCase
// Template 핸들러 테스트 (6개)
// ═══════════════════════════════════════════
public function test_handleTemplateAfterInstall_logs_activity(): void
public function test_handle_template_after_install_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1126,7 +1116,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterInstall('sirsoft-admin_basic', ['version' => '1.0.0']);
}
public function test_handleTemplateAfterActivate_logs_activity(): void
public function test_handle_template_after_activate_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1140,7 +1130,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterActivate(['identifier' => 'sirsoft-admin_basic']);
}
public function test_handleTemplateAfterActivate_handles_missing_identifier(): void
public function test_handle_template_after_activate_handles_missing_identifier(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1152,7 +1142,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterActivate([]);
}
public function test_handleTemplateAfterDeactivate_logs_activity(): void
public function test_handle_template_after_deactivate_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1166,7 +1156,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterDeactivate('sirsoft-basic');
}
public function test_handleTemplateAfterUninstall_logs_activity(): void
public function test_handle_template_after_uninstall_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1182,7 +1172,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterUninstall('sirsoft-admin_basic', ['version' => '1.0.0'], true);
}
public function test_handleTemplateAfterVersionUpdate_logs_activity(): void
public function test_handle_template_after_version_update_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1198,7 +1188,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleTemplateAfterVersionUpdate('sirsoft-admin_basic', ['success' => true], ['version' => '2.0.0']);
}
public function test_handleTemplateAfterRefreshLayouts_logs_activity(): void
public function test_handle_template_after_refresh_layouts_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1216,7 +1206,7 @@ class CoreActivityLogListenerTest extends TestCase
// Layout 핸들러 테스트 (2개)
// ═══════════════════════════════════════════
public function test_handleLayoutAfterUpdate_logs_activity(): void
public function test_handle_layout_after_update_logs_activity(): void
{
$layout = $this->createModelMock(50);
@@ -1233,7 +1223,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleLayoutAfterUpdate($layout, 1, 'admin/users/index', ['content' => '{}']);
}
public function test_handleLayoutAfterVersionRestore_logs_activity(): void
public function test_handle_layout_after_version_restore_logs_activity(): void
{
$newVersion = $this->createModelMock(51);
@@ -1254,7 +1244,7 @@ class CoreActivityLogListenerTest extends TestCase
// Module Settings 핸들러 테스트 (2개)
// ═══════════════════════════════════════════
public function test_handleModuleSettingsAfterSave_logs_activity(): void
public function test_handle_module_settings_after_save_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1270,7 +1260,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handleModuleSettingsAfterSave('sirsoft-ecommerce', ['currency' => 'KRW', 'tax_rate' => 10], true);
}
public function test_handleModuleSettingsAfterReset_logs_activity(): void
public function test_handle_module_settings_after_reset_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1288,7 +1278,7 @@ class CoreActivityLogListenerTest extends TestCase
// Plugin Settings 핸들러 테스트 (2개)
// ═══════════════════════════════════════════
public function test_handlePluginSettingsAfterSave_logs_activity(): void
public function test_handle_plugin_settings_after_save_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1304,7 +1294,7 @@ class CoreActivityLogListenerTest extends TestCase
$this->listener->handlePluginSettingsAfterSave('sirsoft-payment', ['api_key' => 'xxx', 'sandbox' => true], true);
}
public function test_handlePluginSettingsAfterReset_logs_activity(): void
public function test_handle_plugin_settings_after_reset_logs_activity(): void
{
$this->logChannel->shouldReceive('info')
->once()
@@ -1322,7 +1312,7 @@ class CoreActivityLogListenerTest extends TestCase
// 에러 처리 테스트
// ═══════════════════════════════════════════
public function test_logActivity_catches_exception_and_logs_error(): void
public function test_log_activity_catches_exception_and_logs_error(): void
{
$user = $this->createUserMock(1, 'uuid-err');
@@ -0,0 +1,91 @@
<?php
namespace Tests\Unit\Providers;
use App\Providers\SettingsServiceProvider;
use App\Repositories\JsonConfigRepository;
use ReflectionMethod;
use Tests\TestCase;
/**
* SettingsServiceProvider 업로드 설정 테스트 (C2)
*
* 관리자 환경설정 `upload.*`(MB) 를 `config/attachment.*`(KB) 로 옮기는 단일 변환 지점이
* 실제로 동작하는지 검증합니다.
*
* 수정 전에는 존재하지 않는 키(`max_size`)를 읽어 어떤 설정도 반영되지 않았고,
* 소비자가 없는 `g7.upload.max_size` 로 써 두 번째 SSoT 를 만들고 있었습니다.
*/
class SettingsUploadConfigTest extends TestCase
{
/**
* applyUploadConfig 를 리플렉션으로 호출합니다.
*
* @param array $uploadSettings upload 카테고리 설정 데이터
*/
private function callApplyUploadConfig(array $uploadSettings): void
{
$configRepository = $this->createMock(JsonConfigRepository::class);
$configRepository->method('getCategory')
->with('upload')
->willReturn($uploadSettings);
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyUploadConfig');
$method->invoke($provider, $configRepository);
}
/**
* 관리자 설정 MB 가 KB 로 변환되어 attachment config 에 반영되는지 테스트합니다.
*/
public function test_max_file_size_mb_is_converted_to_kb(): void
{
$this->callApplyUploadConfig(['max_file_size' => 20]);
$this->assertSame(20480, config('attachment.max_file_size'));
}
/**
* 소비자가 없는 dead key 를 더 이상 쓰지 않는지 테스트합니다.
*/
public function test_dead_g7_upload_key_is_not_written(): void
{
$this->callApplyUploadConfig(['max_file_size' => 20]);
$this->assertNull(config('g7.upload.max_size'));
}
/**
* 허용 확장자가 소문자로 정규화되어 반영되는지 테스트합니다.
*/
public function test_allowed_extensions_are_normalized(): void
{
$this->callApplyUploadConfig(['allowed_extensions' => ['JPG', '.PNG', 'pdf']]);
$this->assertSame(['jpg', 'png', 'pdf'], config('attachment.allowed_extensions'));
}
/**
* 빈 배열(제한 없음)도 그대로 반영되는지 테스트합니다.
*/
public function test_empty_allowed_extensions_is_applied_as_no_restriction(): void
{
config(['attachment.allowed_extensions' => ['png']]);
$this->callApplyUploadConfig(['allowed_extensions' => []]);
$this->assertSame([], config('attachment.allowed_extensions'));
}
/**
* 설정이 비어 있으면 기본값을 건드리지 않는지 테스트합니다.
*/
public function test_empty_settings_keep_defaults(): void
{
config(['attachment.max_file_size' => 10240]);
$this->callApplyUploadConfig([]);
$this->assertSame(10240, config('attachment.max_file_size'));
}
}
@@ -0,0 +1,102 @@
<?php
namespace Tests\Unit\Repositories;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* 계정 잠금 Repository 단위 테스트 (C1)
*
* 보안 환경설정의 `login_lockout_time = 0` 은 관리자 UI 가 "무한대" 로 안내하는 값입니다.
* 수정 전에는 `max(1, $minutes)` 로 0 이 1 분으로 승격되어 영구 잠금이 1 분 뒤 자동 해제됐습니다.
*/
class UserRepositoryAccountLockTest extends TestCase
{
use RefreshDatabase;
private function repository(): UserRepositoryInterface
{
return app(UserRepositoryInterface::class);
}
/**
* @test
*/
public function 잠금시간_0_은_영구_잠금으로_기록된다(): void
{
$user = User::factory()->create();
$lockedUntil = $this->repository()->lockAccount($user, 0);
$user->refresh();
// 영구 잠금은 해제 시각이 없다 (NULL = 잠금 없음 규약과 컬럼으로 분리)
$this->assertNull($lockedUntil);
$this->assertNull($user->locked_until);
$this->assertTrue((bool) $user->locked_permanently);
$this->assertTrue($this->repository()->isLocked($user));
}
/**
* @test
*/
public function 영구_잠금은_시간이_지나도_해제되지_않는다(): void
{
$user = User::factory()->create();
$this->repository()->lockAccount($user, 0);
$this->travel(10)->years();
$this->assertTrue($this->repository()->isLocked($user->fresh()));
}
/**
* @test
*/
public function 로그인_시도_초기화는_영구_잠금도_해제한다(): void
{
$user = User::factory()->create();
$this->repository()->lockAccount($user, 0);
$this->repository()->resetLoginAttempts($user->fresh());
$user->refresh();
$this->assertFalse((bool) $user->locked_permanently);
$this->assertNull($user->locked_until);
$this->assertFalse($this->repository()->isLocked($user));
}
/**
* @test
*/
public function 유한_잠금은_기존과_동일하게_동작한다(): void
{
$user = User::factory()->create();
$lockedUntil = $this->repository()->lockAccount($user, 5);
$this->assertNotNull($lockedUntil);
$this->assertFalse((bool) $user->fresh()->locked_permanently);
$this->assertTrue($this->repository()->isLocked($user->fresh()));
$this->travel(6)->minutes();
$this->assertFalse($this->repository()->isLocked($user->fresh()));
}
/**
* @test
*/
public function 음수_잠금시간도_영구_잠금으로_처리된다(): void
{
$user = User::factory()->create();
$this->repository()->lockAccount($user, -10);
$this->assertTrue((bool) $user->fresh()->locked_permanently);
$this->assertTrue($this->repository()->isLocked($user->fresh()));
}
}
@@ -177,6 +177,11 @@ class ExtensionBundleServiceTest extends TestCase
public function test_dev_rewrites_source_mapping_url_to_asset_serving_path(): void
{
// 자산 URL 표기(경로형 vs `?file=` 쿼리형)는 사이트 설정이 정한다. 이 테스트가 보려는
// 것은 "개발 환경에서 소스맵 URL 이 에셋 서빙 주소로 재작성되는가" 이므로, 개발 사이트가
// 어느 모드를 쓰든 결과가 달라지지 않도록 경로형으로 고정한다.
config(['g7_settings.core.general.asset_url_mode' => 'extension']);
// 기본 testing 환경 = 비프로덕션 → dev rewrite 경로
$a = $this->writeFixture('a.js', "(function(){})()\n//# sourceMappingURL=a.js.map");
@@ -0,0 +1,118 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\IdentityVerification\Providers\MailIdentityProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use ReflectionMethod;
use Tests\TestCase;
/**
* IDV 인증코드 길이 경계 테스트 (C3)
*
* 스키마가 경계를 선언하지 않아 서비스가 자체 상수(4~10)로 조용히 클램프했습니다.
* 관리자가 12를 설정하면 화면은 12로 보이는데 실제로는 10자리 코드가 발급됐습니다.
*/
class MailIdentityProviderCodeLengthTest extends TestCase
{
use RefreshDatabase;
/**
* 프로바이더 인스턴스를 반환합니다.
*
* @return MailIdentityProvider 프로바이더
*/
private function provider(): MailIdentityProvider
{
return app(MailIdentityProvider::class);
}
/**
* 스키마가 경계를 선언하는지 테스트합니다.
*
* 관리자 화면은 스키마를 그대로 노출하므로, 경계 선언이 곧 UI 계약이 된다.
*
* @scenario provider=mail, code_length=schema_declaration
*
* @effects schema_declares_min_max_boundaries
*/
public function test_schema_declares_code_length_boundaries(): void
{
$schema = $this->provider()->getSettingsSchema();
// 수정 전: min/max 키 자체가 없었다
$this->assertArrayHasKey('min', $schema['code_length']);
$this->assertArrayHasKey('max', $schema['code_length']);
$this->assertSame(MailIdentityProvider::MIN_CODE_LENGTH, $schema['code_length']['min']);
$this->assertSame(MailIdentityProvider::MAX_CODE_LENGTH, $schema['code_length']['max']);
$this->assertSame(MailIdentityProvider::DEFAULT_CODE_LENGTH, $schema['code_length']['default']);
}
/**
* 경계 내 길이는 그대로 적용되는지 테스트합니다.
*
* @scenario provider=mail, code_length=within_bounds
*
* @effects configured_length_applied_verbatim
*/
public function test_code_length_within_bounds_is_applied(): void
{
$method = new ReflectionMethod(MailIdentityProvider::class, 'generateNumericCode');
$this->assertSame(8, strlen($method->invoke($this->provider(), 8)));
$this->assertSame(4, strlen($method->invoke($this->provider(), 4)));
$this->assertSame(10, strlen($method->invoke($this->provider(), 10)));
}
/**
* 경계를 벗어나면 조용한 클램프 대신 기본값 폴백 + 경고 로그를 남기는지 테스트합니다.
*
* @scenario provider=mail, code_length=above_max
*
* @effects out_of_range_falls_back_to_default_with_warning
*/
public function test_out_of_range_falls_back_to_default_with_warning(): void
{
Log::spy();
$method = new ReflectionMethod(MailIdentityProvider::class, 'generateNumericCode');
// 수정 전: 12 → 10 으로 조용히 클램프
$code = $method->invoke($this->provider(), 12);
$this->assertSame(MailIdentityProvider::DEFAULT_CODE_LENGTH, strlen($code));
Log::shouldHaveReceived('warning')->once();
}
/**
* 하한 미만도 동일하게 폴백하는지 테스트합니다.
*
* @scenario provider=mail, code_length=below_min
*
* @effects out_of_range_falls_back_to_default_with_warning
*/
public function test_below_minimum_falls_back_to_default(): void
{
$method = new ReflectionMethod(MailIdentityProvider::class, 'generateNumericCode');
$this->assertSame(
MailIdentityProvider::DEFAULT_CODE_LENGTH,
strlen($method->invoke($this->provider(), 2))
);
}
/**
* 생성된 코드가 숫자로만 구성되는지 테스트합니다.
*
* @scenario provider=mail, code_length=within_bounds
*
* @effects generated_code_is_numeric
*/
public function test_generated_code_is_numeric(): void
{
$method = new ReflectionMethod(MailIdentityProvider::class, 'generateNumericCode');
$this->assertMatchesRegularExpression('/^\d{6}$/', $method->invoke($this->provider(), 6));
}
}
+27 -2
View File
@@ -150,6 +150,32 @@ class ModuleServiceAssetTest extends TestCase
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/manifest.json';
file_put_contents($filePath, '{"version":3,"sources":[]}');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/manifest.json');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/json', $result['mimeType']);
}
/**
* 소스맵(.map)은 JSON 으로 타입 지정하지 않는다.
*
* 소스맵에는 원본 코드 전문(sourcesContent)이 담겨 있어, 서빙 허용 자체를 로컬 환경으로
* 한정하고 MIME 표에서도 제외했다(#471 / 공개 #72). 표에 되돌아오면 그 조치가 조용히
* 풀린 것이므로 명시적으로 고정한다.
*/
public function test_source_map_is_not_typed_as_json(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/module.iife.js.map';
file_put_contents($filePath, '{"version":3,"sources":[]}');
@@ -157,8 +183,7 @@ class ModuleServiceAssetTest extends TestCase
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/module.iife.js.map');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/json', $result['mimeType']);
$this->assertNotEquals('application/json', $result['mimeType']);
}
/**
@@ -30,8 +30,11 @@ class NotificationDefinitionServiceTest extends TestCase
*/
public function test_resolve_returns_active_definition(): void
{
// 코어 알림 정의(welcome 등)는 config/core.php 를 SSoT 로 부팅 시 DB 에 동기화되므로
// 같은 type 을 새로 만들면 중복이 된다. 이 테스트가 보려는 것은 resolve() 의 동작이라
// 코어가 선점하지 않는 전용 type 을 쓴다.
NotificationDefinition::create([
'type' => 'welcome',
'type' => 'active_resolve_target',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
@@ -43,12 +46,12 @@ class NotificationDefinitionServiceTest extends TestCase
'is_default' => true,
]);
$this->service->invalidateCache('welcome');
$this->service->invalidateCache('active_resolve_target');
$result = $this->service->resolve('welcome');
$result = $this->service->resolve('active_resolve_target');
$this->assertNotNull($result);
$this->assertEquals('welcome', $result->type);
$this->assertEquals('active_resolve_target', $result->type);
}
/**
@@ -111,8 +114,12 @@ class NotificationDefinitionServiceTest extends TestCase
$result = $this->service->getAllActive();
$this->assertCount(1, $result);
$this->assertEquals('active_one', $result->first()->type);
// 코어 알림 정의가 부팅 시 함께 동기화되므로 절대 개수로는 판정할 수 없다.
// 이 테스트의 주제는 "활성만 돌려주는가" 이므로 이 테스트가 만든 두 건으로 판정한다.
$types = $result->pluck('type');
$this->assertContains('active_one', $types);
$this->assertNotContains('inactive_one', $types);
}
/**
@@ -200,31 +200,37 @@ class NotificationTemplateServiceTest extends TestCase
*/
public function test_reset_to_default_restores_click_url_and_recipients(): void
{
$definition = NotificationDefinition::create([
'type' => 'welcome',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '회원가입 환영'],
'variables' => [],
'channels' => ['database'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
// welcome 은 코어 알림 정의라 config/core.php 를 SSoT 로 부팅 시 이미 동기화되어 있다.
// 이 테스트는 그 정의에 템플릿을 매달아 복원 동작을 보므로, 있으면 그대로 쓴다.
$definition = NotificationDefinition::firstOrCreate(
['type' => 'welcome'],
[
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '회원가입 환영'],
'variables' => [],
'channels' => ['database'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]
);
// 관리자가 click_url/recipients 를 임의 값으로 수정한 상태
$template = NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'database',
'subject' => ['ko' => '수정된 제목'],
'body' => ['ko' => '수정된 본문'],
'click_url' => '/custom-edited-url',
'recipients' => [['type' => 'admin']],
'is_active' => true,
'is_default' => false,
'user_overrides' => ['click_url' => true, 'recipients' => true],
]);
// 관리자가 click_url/recipients 를 임의 값으로 수정한 상태.
// 코어 템플릿이 이미 동기화되어 있으면 그 행을 수정본으로 만든다 (실제 시나리오와 동일).
$template = NotificationTemplate::updateOrCreate(
['definition_id' => $definition->id, 'channel' => 'database'],
[
'subject' => ['ko' => '수정된 제목'],
'body' => ['ko' => '수정된 본문'],
'click_url' => '/custom-edited-url',
'recipients' => [['type' => 'admin']],
'is_active' => true,
'is_default' => false,
'user_overrides' => ['click_url' => true, 'recipients' => true],
]
);
$defaultData = $this->service->getDefaultTemplateData('welcome', 'database');
$restored = $this->service->resetToDefault($template, $defaultData);
@@ -0,0 +1,60 @@
# audit:allow test-scenario-coverage reason: |
# cross product 자동 전개는 audit 실행 환경의 fallback YAML 파서가 nested axes 를 읽지 못해
# 검출되지 않는다(다른 번들 시나리오와 동일 한계). 본 변경은 백엔드 전용(업로드 검증·설정 변환)
# 이며 PHPUnit Feature/Unit 테스트가 축 조합을 커버하고 green 이다.
feature: 첨부파일 업로드 정책(용량·확장자) 강제 (C2)
description: |
관리자 환경설정의 업로드 정책이 실제 업로드 경로에서 강제되도록 한다.
배경:
- 두 업로드 FormRequest 가 존재하지 않는 config 키(`attachment.max_size`)를 읽어
폴백 상수로 동작했다. 폴백(10 * 1024)이 실제 기본값(10240 KB)과 우연히 같아
기본 설정 상태에서는 증상이 드러나지 않았다.
- `SettingsServiceProvider::applyUploadConfig()` 도 같은 오타 키를 읽어 관리자 설정이
어디에도 반영되지 않았고, 소비자 0건인 `g7.upload.max_size` 로 써 두 번째 SSoT 를 만들었다.
- 확장자 제한은 설정에만 존재하고 강제 지점이 0건이었다.
단위 규약:
- `config/attachment.*` = KB (Laravel `max:` 규칙과 동일 단위, 변환 없음)
- settings `upload.*` = MB (관리자 UI 단위)
- 변환은 `SettingsServiceProvider::applyUploadConfig()` 단 한 곳
axes:
entry_point: [single_upload, batch_upload]
size_state: [within_limit, over_limit]
extension_state: [allowed, disallowed]
allowed_list: [configured, empty, hook_extended]
saved_shape: [comma_string, array, legacy_string_on_disk]
exclusions:
- { allowed_list: empty, extension_state: disallowed, reason: "목록이 비면 확장자 제한 자체가 없음 (탈출구)" }
effects:
- over_limit_upload_returns_422
- within_limit_upload_succeeds
- disallowed_extension_returns_422
- allowed_extension_succeeds
- empty_allowed_list_disables_extension_restriction
- hook_can_extend_allowed_extensions
- batch_upload_applies_same_policy
- settings_mb_converted_to_kb_in_attachment_config
- dead_g7_upload_key_no_longer_written
- allowed_extensions_normalized_to_lowercase
- empty_settings_keep_config_defaults
- stored_filename_extension_derived_from_mime_not_client_filename
- comma_string_input_normalized_to_array_before_saving
- saved_extensions_reach_the_upload_restriction
- legacy_string_value_on_disk_is_still_applied
test_files:
- tests/Feature/Attachment/AttachmentUploadPolicyTest.php
- tests/Feature/Settings/UploadAllowedExtensionsContractTest.php
- tests/Unit/Providers/SettingsUploadConfigTest.php
rules_layer_coverage:
- rule: i18n-throw-hardcoded-korean
coverage: 확장자 거부 메시지는 lang/{ko,en}/attachment.php#validation.file_extension_invalid
- rule: service-direct-data-access
coverage: AttachmentService 는 Repository 위임 유지 (본 변경은 저장 확장자 산출만 수정)
+17 -1
View File
@@ -17,16 +17,23 @@ description: |
axes:
login_attempt_enabled: [true, false]
user_existence: [exists, not_exists]
lock_state: [none, active, expired]
lock_state: [none, active, expired, permanent]
lockout_minutes_setting: [positive, zero]
credential: [valid, invalid]
controller: [user, admin]
ip_pattern: [same, different]
unlock_path: [none, successful_login, admin_manual]
exclusions:
- { lock_state: active, credential: valid, reason: "잠금 상태에서는 자격 증명과 무관하게 423" }
- { lock_state: permanent, credential: valid, reason: "동일 — 영구 잠금도 자격 증명과 무관하게 423" }
- { user_existence: not_exists, lock_state: active, reason: "존재하지 않는 사용자는 잠금 불가" }
- { user_existence: not_exists, lock_state: expired, reason: "동일 사유" }
- { user_existence: not_exists, lock_state: permanent, reason: "동일 사유" }
- { login_attempt_enabled: false, lock_state: active, reason: "기능 OFF 시 사전 잠금 체크 자체 미수행" }
- { lockout_minutes_setting: positive, lock_state: permanent, reason: "양수 설정에서는 영구 잠금이 생성되지 않음" }
- { lockout_minutes_setting: zero, lock_state: expired, reason: "영구 잠금은 만료되지 않음" }
- { unlock_path: admin_manual, user_existence: not_exists, reason: "해제 대상이 없음" }
effects:
- failed_attempt_increments_counter
@@ -46,9 +53,18 @@ effects:
- activity_log_records_auth_account_locked_with_attempts_and_minutes_params
- per_ip_throttle_blocks_burst_attempts_with_429
- per_ip_throttle_uses_security_max_login_attempts_setting_x6_with_min_30_floor
- lockout_time_zero_creates_permanent_lock_not_one_minute
- permanent_lock_survives_arbitrary_time_passage
- permanent_lock_response_serializes_with_null_locked_until
- successful_login_reset_clears_permanent_lock_flag
- admin_manual_unlock_endpoint_clears_lock
- admin_manual_unlock_requires_users_update_permission
- finite_lockout_setting_keeps_previous_expiry_behavior
test_files:
- tests/Feature/Auth/LoginThrottleTest.php
- tests/Feature/Auth/AccountLockoutTest.php
- tests/Unit/Repositories/UserRepositoryAccountLockTest.php
rules_layer_coverage:
- rule: service-direct-data-access
+43
View File
@@ -0,0 +1,43 @@
# audit:allow test-scenario-coverage reason: |
# cross product 자동 전개는 audit 실행 환경의 fallback YAML 파서가 nested axes 를 읽지 못해
# 검출되지 않는다(다른 시나리오와 동일 한계). 본 변경은 백엔드 전용(스키마 경계 선언 +
# 폴백)이며 PHPUnit Unit 테스트가 경계 조합을 커버하고 green 이다.
feature: 본인인증 인증코드 길이 경계를 스키마가 선언 (C3)
description: |
메일 본인인증 Provider 의 `code_length` 경계를 설정 스키마가 선언하고,
서비스의 무명 클램프를 제거한다.
배경:
- 스키마가 경계를 선언하지 않아 서비스가 자체 상수로 `max(4, min(10, $length))` 방어했다.
설정에 12 를 넣으면 조용히 10 으로 뭉개져, 관리자는 12 자리로 설정했다고 믿지만
실제 발송 코드는 10 자리인 상태가 된다.
방침 (최소 범위):
- `getSettingsSchema()['code_length']` 에 `min`/`max` 를 넣어 **경계를 스키마가 선언**한다.
- 서비스의 클램프를 제거하고, 경계 위반 시 조용한 클램프 대신
**경고 로그 + 스키마 default(6) 폴백**. 런타임 인증 흐름 중단은 위험하므로 예외가 아니다.
- 관리자 API 가 스키마를 그대로 노출하므로 min/max 가 자동으로 UI 계약에 반영된다.
- 저장 검증 파이프라인 신설은 과잉 — `withConfig()` 쓰기 경로가 코어에 0건이다
(`coverage.json` 의 `extension-settings-schema-boundary-rules` 에 todo 로 기록).
axes:
provider: [mail]
code_length: [below_min, within_bounds, above_max, schema_declaration]
exclusions:
- { provider: mail, code_length: schema_declaration, reason: "선언 자체를 확인하는 축 — 코드 생성 조합과 교차하지 않음" }
effects:
- schema_declares_min_max_boundaries
- configured_length_applied_verbatim
- out_of_range_falls_back_to_default_with_warning
- generated_code_is_numeric
test_files:
- tests/Unit/Services/MailIdentityProviderCodeLengthTest.php
rules_layer_coverage:
- rule: service-config-value-clamp
coverage: 제거한 max(4, min(10, $length)) 형태가 재유입되면 이 룰이 검출한다
+61
View File
@@ -0,0 +1,61 @@
# audit:allow test-scenario-coverage reason: |
# cross product 자동 전개는 audit 실행 환경의 fallback YAML 파서가 nested axes 를 읽지 못해
# 검출되지 않는다(다른 시나리오와 동일 한계). 본 변경은 백엔드 검증 규칙 + 관리자 설정 화면이며
# PHPUnit Feature 테스트와 Vitest 레이아웃 테스트가 축 조합을 커버하고 green 이다.
feature: 비밀번호 정책 설정 강제 (C4)
description: |
관리자 보안 설정의 비밀번호 정책이 비밀번호를 받는 모든 경로에서 동일하게 적용되도록 한다.
배경:
- `security.password_min_length` · `security.password_require_special` 설정이 화면에는
있었지만 어떤 검증 규칙도 읽지 않는 고아 설정이었다.
- 비밀번호 길이 제한은 `LoginRequest` 에만 `min:6` 으로 하드코딩되어 있었다. 로그인은
기존 비밀번호를 대조하는 자리라 정책을 걸 자리가 아니고(정책 강화 시 기존 사용자가
로그인 불가), 정작 비밀번호를 **정하는** 경로에는 정책이 없었다.
적용 지점:
- 비밀번호를 새로 정하는 6개 경로가 `PasswordPolicy::rule()` 하나를 공유한다
(회원가입 · 비밀번호 재설정 · 비밀번호 변경 · 관리자 회원 생성 · 관리자 회원 수정 · 프로필 수정).
- 로그인은 길이 규칙을 갖지 않는다.
axes:
entry_point:
- register
- reset_password
- change_password
- admin_create_user
- admin_update_user
- update_profile
min_length_setting: [default, raised, lowered]
special_char_setting: [required, not_required]
input_state: [satisfies_policy, violates_length, violates_special]
exclusions:
- { special_char_setting: not_required, input_state: violates_special, reason: "특수문자 미요구 설정에서는 위반 상태가 성립하지 않음" }
effects:
- policy_rule_reads_min_length_from_settings
- policy_rule_reads_special_requirement_from_settings
- password_shorter_than_setting_is_rejected
- password_meeting_setting_is_accepted
- special_char_requirement_is_enforced_when_enabled
- login_request_has_no_length_rule
- all_password_setting_paths_share_one_rule
- empty_security_settings_fall_back_to_defaults
- saved_security_settings_are_visible_on_reload
- admin_screen_min_length_bounds_follow_settings_limits
test_files:
- tests/Feature/Auth/PasswordPolicyTest.php
- tests/Feature/Settings/SettingsBoundaryContractTest.php
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-settings-security-password-policy.test.ts
rules_layer_coverage:
- rule: formrequest-numeric-boundary-drift
coverage: 최소 길이 경계는 config('core.settings_limits.security_password_min_length_*') 단일 출처
- rule: layout-input-boundary-hardcoded
coverage: 보안 탭 입력 min/max 는 `_meta.limits` 바인딩 (리터럴 없음)
- rule: i18n-throw-hardcoded-korean
coverage: 정책 위반 메시지는 lang/{ko,en}/validation.php 의 password 키