Files
Gnuboard7/tests/Feature/Api/Auth/RegisterPolicyDrivenSignupTest.php
T
HeuJung d17ea28da5 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
2026-07-30 07:52:24 +09:00

322 lines
12 KiB
PHP

<?php
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;
use App\Models\User;
use Database\Seeders\IdentityPolicySeeder;
use Database\Seeders\RolePermissionSeeder;
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;
/**
* 회원가입 흐름 IdentityPolicy 기반 정책 통합 Feature 테스트.
*
* 정책 키:
* - core.auth.signup_before_submit (Mode B): route scope, verification_token 검증
* - core.auth.signup_after_create (Mode C): hook scope, after_register 시 challenge 발행 + PendingVerification
*/
class RegisterPolicyDrivenSignupTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Notification::fake();
// 기존 훅 큐 job 의 Carbon 직렬화 문제로 테스트가 터지는 것을 방지
Queue::fake();
// PermissionMiddleware 가 IDV 라우트에 권한 가드 적용 — guest/user 역할 권한 sync 필수
$this->seed(RolePermissionSeeder::class);
Role::firstOrCreate(['identifier' => 'user'], ['name' => ['ko' => '사용자', 'en' => 'User']]);
// 기본 정책 시드 (모두 enabled=false 상태)
$this->seed(IdentityPolicySeeder::class);
}
/**
* 정책 미활성 상태 — 일반 가입 흐름. Active 사용자 생성, IDV challenge 미발행.
*/
public function test_no_signup_policy_creates_active_user(): void
{
$response = $this->postJson('/api/auth/register', [
'name' => '테스트',
'email' => 'a@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', [
'email' => 'a@example.com',
'status' => UserStatus::Active->value,
]);
$this->assertDatabaseMissing('identity_verification_logs', ['purpose' => 'signup']);
}
/**
* signup_before_submit 정책 enabled — 토큰 미제출 시 EnforceIdentityPolicy 미들웨어가
* 428 (IdentityVerificationRequiredException) 으로 차단합니다.
*/
public function test_signup_before_submit_policy_blocks_without_token(): void
{
$this->enablePolicy('core.auth.signup_before_submit');
$response = $this->postJson('/api/auth/register', [
'name' => '테스트',
'email' => 'b@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
]);
$response->assertStatus(428);
$this->assertDatabaseMissing('users', ['email' => 'b@example.com']);
}
/**
* signup_before_submit 정책 enabled + 유효한 verification_token — Active 가입 성공.
*/
public function test_signup_before_submit_policy_succeeds_with_valid_token(): void
{
$this->enablePolicy('core.auth.signup_before_submit');
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
'user_id' => null,
'target_hash' => hash('sha256', 'b2@example.com'),
'status' => IdentityVerificationStatus::Verified->value,
'verification_token' => $token,
'verified_at' => now(),
'expires_at' => now()->addMinutes(15),
]);
$response = $this->postJson('/api/auth/register', [
'name' => '테스트',
'email' => 'b2@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
'verification_token' => $token,
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', [
'email' => 'b2@example.com',
'status' => UserStatus::Active->value,
]);
}
/**
* 회귀 — verify 직후 retry 가 발생할 때 verification_token 만으로 통과해야 함.
*
* 과거 EnforceIdentityPolicy 미들웨어가 verification_token 을 무시하고 grace_minutes 윈도우만
* 검사했기 때문에, grace_minutes=0 (signup 정책 기본값) + verified_at < now() 인 일반적인 retry 에서는
* 무한 428 루프가 발생했음. 이 테스트는 verified_at 을 의도적으로 2초 전으로 두어 second-boundary 우연
* 일치를 회피하고, 미들웨어가 token 을 직접 인식하는지 검증한다.
*/
public function test_signup_before_submit_token_bypasses_middleware_after_grace_window(): void
{
$this->enablePolicy('core.auth.signup_before_submit');
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
'user_id' => null,
'target_hash' => hash('sha256', 'b3@example.com'),
'status' => IdentityVerificationStatus::Verified->value,
'verification_token' => $token,
// grace_minutes=0 윈도우 밖으로 의도적으로 밀어두어 token bypass 만이 통과 경로가 되도록 함
'verified_at' => now()->subSeconds(2),
'expires_at' => now()->addMinutes(15),
]);
$response = $this->postJson('/api/auth/register?verification_token='.$token, [
'name' => '테스트',
'email' => 'b3@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
'verification_token' => $token,
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', [
'email' => 'b3@example.com',
'status' => UserStatus::Active->value,
]);
}
/**
* 회귀 — 미들웨어 단계에서 target hijacking 차단.
*
* A 가 자기 이메일(a@example.com)로 인증받은 token 을 훔쳐 B 의 이메일(b4@example.com)로
* 가입 시도하면 미들웨어가 target_hash 불일치를 감지하여 428 로 차단해야 함.
* 다운스트림 listener (AssertIdentityVerifiedBeforeRegister) 도 같은 검사를 하지만,
* listener 가 없는 다른 정책 라우트에 대비한 안전망이 미들웨어에 함께 있어야 함.
*/
public function test_token_with_mismatched_target_hash_is_blocked_by_middleware(): void
{
$this->enablePolicy('core.auth.signup_before_submit');
$token = 'test-idv-token-'.bin2hex(random_bytes(8));
IdentityVerificationLog::create([
'id' => (string) Str::uuid(),
'provider_id' => 'g7:core.mail',
'purpose' => 'signup',
'channel' => 'email',
'user_id' => null,
// 토큰은 a@example.com 으로 인증됨
'target_hash' => hash('sha256', 'a@example.com'),
'status' => IdentityVerificationStatus::Verified->value,
'verification_token' => $token,
'verified_at' => now()->subSeconds(2),
'expires_at' => now()->addMinutes(15),
]);
// B 의 이메일로 토큰 hijack 시도
$response = $this->postJson('/api/auth/register?verification_token='.$token, [
'name' => '공격자',
'email' => 'b4@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
'verification_token' => $token,
]);
$response->assertStatus(428);
$this->assertDatabaseMissing('users', ['email' => 'b4@example.com']);
}
/**
* signup_after_create 정책 enabled — PendingVerification 생성 + challenge 발행.
*/
public function test_signup_after_create_policy_creates_pending_user(): void
{
$this->enablePolicy('core.auth.signup_after_create');
$response = $this->postJson('/api/auth/register', [
'name' => '테스트',
'email' => 'c@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
]);
$response->assertStatus(201);
$this->assertDatabaseHas('users', [
'email' => 'c@example.com',
'status' => UserStatus::PendingVerification->value,
]);
$this->assertDatabaseHas('identity_verification_logs', [
'purpose' => 'signup',
'origin_identifier' => 'core.auth.after_register',
]);
}
/**
* signup_after_create 정책 enabled — verify 후 Active 전환.
*/
public function test_signup_after_create_policy_verify_activates_user(): void
{
$this->enablePolicy('core.auth.signup_after_create');
// 1) 가입 (pending 상태)
$this->postJson('/api/auth/register', [
'name' => '테스트',
'email' => 'c2@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'agree_terms' => true,
'agree_privacy' => true,
])->assertStatus(201);
$user = User::where('email', 'c2@example.com')->first();
$this->assertSame(UserStatus::PendingVerification->value, $user->status);
/** @var IdentityVerificationLogRepositoryInterface $repo */
$repo = $this->app->make(IdentityVerificationLogRepositoryInterface::class);
$log = IdentityVerificationLog::where('user_id', $user->id)
->where('purpose', 'signup')
->first();
$this->assertNotNull($log);
$repo->updateById($log->id, [
'metadata' => ['code_hash' => Hash::make('123456')],
'status' => IdentityVerificationStatus::Sent->value,
]);
$this->postJson("/api/identity/challenges/{$log->id}/verify", ['code' => '123456'])
->assertStatus(200);
$user->refresh();
$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 로 토글합니다.
*/
private function enablePolicy(string $key): void
{
IdentityPolicy::where('key', $key)->update(['enabled' => true]);
}
}