fix(core,extensions): 보안 결함 3건과 이중저장소·레이아웃 중복키 결함군 폐쇄

KISA 제보 3건(KVE-2026-2010/2011/2018)과 그 동일 계열 형제 결함을 전수 조치하고,
그 과정에서 드러난 두 결함군을 함께 닫는다.

- 검증 시점과 연결 시점이 host 를 다르게 읽던 SSRF 통로를 정규화 SSoT 한 곳으로 모았다
- 세션을 여는 지점(2FA 완료·토큰 재발급)이 잠금 검사를 거치지 않아 계정 잠금이 우회됐다
- 인증도 서명도 없는 브라우저 리턴 콜백이 주문 상태를 바꾸던 통로를 4 PG 전부에서 닫고,
 소유권을 대조하는 close-report 를 토스에도 신설했다. 그 결과 정리 주체를 잃는
 결제창 미완료 주문은 만료 자동취소가 거둔다
- 저장소 A(_local)에만 쓰는 경로가 B 의 값을 조용히 덮던 회귀를 정본 writer 로 닫았다
 (engine-v1.63.5). 한 방향만 보던 정적 검사에 반대 방향 축과 양방향 계약 테스트를 더했다
- 레이아웃 JSON 의 같은 객체 중복 키가 앞선 선언을 오류 없이 삼키던 결함군을 닫았다
This commit is contained in:
HeuJung committed 2026-09-02 17:36:11 +09:00
1 parent d4439ea30a
commit 21fc114f37
137 files changed
+6470 -829

No files matched your search

@@ -332,6 +332,10 @@ class GatePermissionTest extends TestCase
// 역할에 권한 부여
$this->userRole->permissions()->attach($newPermission->id);
// 권한 판정은 인스턴스 단위로 한 번만 적재된다(요청당 반복 쿼리 방지). 같은 인스턴스에서
// 역할을 바꾼 직후 다시 판정하려면 운영 코드(역할 동기화 서비스)와 같이 캐시를 비운다.
$this->regularUser->flushPermissionCaches();
// 이제 권한 있음
$this->assertTrue(Gate::allows('test.new.permission'));
}
@@ -0,0 +1,326 @@
<?php
namespace Tests\Feature\Auth;
use App\Enums\UserStatus;
use App\Models\IdentityVerificationLog;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Database\Seeders\IdentityMessageDefinitionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Testing\TestResponse;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 2단계 인증 완료 지점의 계정 잠금 재검사 테스트.
*
* 계정 잠금은 비밀번호 확인 단계(`login`)에서만 검사되고 있었습니다. 그런데 2단계 인증이
* 켜져 있으면 `login` 은 토큰 대신 challenge 만 돌려주고, 실제 세션은 `login/two-factor`
* 가 발급합니다. 그 두 번째 지점에 잠금 검사가 없으면 **잠기기 전에 발급받은 challenge 를
* 잠긴 뒤에 완료**하는 것만으로 잠금이 통째로 우회됩니다.
*
* 게다가 로그인 완료 훅(`core.auth.after_login`)이 실패 횟수·잠금 시각을 초기화하므로,
* 우회에 성공하면 잠금 자체가 해제되어 흔적도 남지 않습니다.
*
* 불변조건: **세션(토큰)을 발급하는 모든 지점은 잠금을 재검사한다.**
*/
class TwoFactorAccountLockTest extends TestCase
{
use RefreshDatabase;
private const EMAIL = 'two-factor-lock@test.com';
private const PASSWORD = 'Passw0rd!2fa';
private User $user;
protected function setUp(): void
{
parent::setUp();
Mail::fake();
// 인증번호 메일 구성에 본인인증 메시지 정의가 필요하다. 없으면 challenge 가 발송
// 실패로 표시되어, 잠금 게이트가 아니라 시드 부재를 측정하게 된다.
$this->seed(IdentityMessageDefinitionSeeder::class);
$this->setSecuritySettings([
'two_factor_auth' => true,
'login_attempt_enabled' => true,
'max_login_attempts' => 3,
'login_lockout_time' => 30,
]);
Cache::flush();
$this->user = User::factory()->create([
'email' => self::EMAIL,
'password' => Hash::make(self::PASSWORD),
'status' => UserStatus::Active->value,
]);
}
/**
* 잠금 전에 발급된 2단계 인증 challenge 로는 잠긴 계정에 로그인할 수 없다.
*/
#[Test]
public function a_challenge_issued_before_the_lock_cannot_complete_login_after_the_lock(): void
{
// 1. 정상 비밀번호로 challenge 를 확보한다 (아직 잠기지 않은 상태).
$challengeId = $this->login()->json('data.challenge_id');
$this->assertNotEmpty($challengeId, '2단계 인증 challenge 가 발급되지 않았습니다.');
$code = $this->issuedCode($challengeId);
// 2. 임계값까지 실패시켜 계정을 잠근다.
$this->lockAccount();
// 3. 통제군 — 정상 로그인 경로는 잠금을 인지해 423 을 돌려준다.
$this->login()->assertStatus(423);
// 4. 잠금 전 challenge 로 2단계 인증을 완료하려 하면 같은 판정을 받아야 한다.
$response = $this->postJson('/api/auth/login/two-factor', [
'challenge_id' => $challengeId,
'code' => $code,
]);
$response->assertStatus(423);
$this->assertNull(
$response->json('data.token'),
'잠긴 계정에 토큰이 발급되면 계정 잠금이 통째로 우회됩니다.'
);
}
/**
* 우회 시도는 잠금 상태를 초기화하지 않는다.
*
* 로그인 완료 훅이 실패 횟수·잠금 시각을 리셋하므로, 우회가 성공하면 공격의 흔적까지
* 사라진다. 차단이 훅 이전에 일어나는지를 사후 상태로 확인한다.
*/
#[Test]
public function a_blocked_two_factor_attempt_does_not_reset_the_lock_state(): void
{
$challengeId = $this->login()->json('data.challenge_id');
$code = $this->issuedCode($challengeId);
$this->lockAccount();
$locked = $this->user->fresh();
$attemptsBefore = $locked->failed_login_attempts;
$lockedUntilBefore = $locked->locked_until;
$permanentBefore = $locked->locked_permanently;
$this->postJson('/api/auth/login/two-factor', [
'challenge_id' => $challengeId,
'code' => $code,
])->assertStatus(423);
$after = $this->user->fresh();
$this->assertSame($attemptsBefore, $after->failed_login_attempts, '실패 횟수가 초기화되었습니다.');
$this->assertEquals($lockedUntilBefore, $after->locked_until, '잠금 해제 시각이 변경되었습니다.');
$this->assertEquals($permanentBefore, $after->locked_permanently, '영구 잠금 플래그가 변경되었습니다.');
$this->assertSame(0, $after->tokens()->count(), '차단된 요청이 토큰을 남겼습니다.');
}
/**
* 423 응답은 정상 로그인 경로와 같은 계약(해제 시각·잔여 시간·영구 여부)을 따른다.
*
* 화면은 두 경로를 구분하지 않으므로, 한쪽만 다른 모양이면 안내가 깨진다.
*/
#[Test]
public function the_locked_response_matches_the_login_endpoint_contract(): void
{
$challengeId = $this->login()->json('data.challenge_id');
$code = $this->issuedCode($challengeId);
$this->lockAccount();
$loginResponse = $this->login()->assertStatus(423);
$twoFactorResponse = $this->postJson('/api/auth/login/two-factor', [
'challenge_id' => $challengeId,
'code' => $code,
])->assertStatus(423);
$this->assertSame(
array_keys((array) $loginResponse->json('errors')),
array_keys((array) $twoFactorResponse->json('errors')),
'두 경로의 423 응답 형태가 다릅니다.'
);
$this->assertFalse((bool) $twoFactorResponse->json('errors.permanent'));
$this->assertNotNull($twoFactorResponse->json('errors.locked_until'));
}
/**
* 잠기지 않은 계정의 2단계 인증은 그대로 완료된다 (정상 흐름 회귀 방지).
*/
#[Test]
public function an_unlocked_account_still_completes_two_factor_normally(): void
{
$challengeId = $this->login()->json('data.challenge_id');
$response = $this->postJson('/api/auth/login/two-factor', [
'challenge_id' => $challengeId,
'code' => $this->issuedCode($challengeId),
]);
$response->assertStatus(200);
$this->assertNotEmpty($response->json('data.token'), '정상 계정의 2단계 인증이 차단되었습니다.');
}
/**
* 잠금 검사 설정이 꺼져 있으면 2단계 인증도 잠금을 보지 않는다 (설정 계약 일치).
*/
#[Test]
public function the_lock_recheck_follows_the_login_attempt_setting(): void
{
$challengeId = $this->login()->json('data.challenge_id');
$code = $this->issuedCode($challengeId);
$this->lockAccount();
// 운영자가 잠금 기능을 끄면 정상 로그인이 통과하듯 2단계 인증도 통과해야 한다.
$this->setSecuritySettings(['login_attempt_enabled' => false]);
$this->postJson('/api/auth/login/two-factor', [
'challenge_id' => $challengeId,
'code' => $code,
])->assertStatus(200);
}
/**
* 잠긴 계정은 기존 세션으로도 토큰을 재발급받지 못한다.
*
* 형제 결함 — `refreshToken` 은 유효한 세션이 전제라 신규 로그인 우회는 아니지만,
* 관리자가 계정을 잠근 뒤에도 그 세션이 무기한 연장되면 잠금이 실효를 잃는다.
*/
#[Test]
public function a_locked_account_cannot_refresh_its_token(): void
{
$this->grantRefreshPermission();
$token = $this->user->createToken('test-token')->plainTextToken;
$this->lockAccount();
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/user/auth/refresh')
->assertStatus(423);
}
/**
* 잠기지 않은 계정의 토큰 재발급은 그대로 동작한다 (정상 흐름 회귀 방지).
*/
#[Test]
public function an_unlocked_account_can_still_refresh_its_token(): void
{
$this->grantRefreshPermission();
$token = $this->user->createToken('test-token')->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/user/auth/refresh');
$response->assertStatus(200);
$this->assertNotEmpty($response->json('data.token'));
}
/**
* 테스트 사용자에게 토큰 재발급 권한을 부여합니다.
*
* 재발급 라우트는 `permission:user,core.auth.refresh` 미들웨어를 거치므로, 권한이 없으면
* 잠금 게이트에 닿기 전에 403 이 되어 측정 대상이 바뀐다.
*/
private function grantRefreshPermission(): void
{
$permission = Permission::firstOrCreate(
['identifier' => 'core.auth.refresh'],
[
'name' => json_encode(['ko' => '토큰 재발급', 'en' => 'Refresh Token']),
'description' => json_encode(['ko' => '토큰 재발급', 'en' => 'Refresh Token']),
'extension_type' => 'core',
'extension_identifier' => 'core',
'type' => 'user',
]
);
$role = Role::create([
'identifier' => 'two_factor_lock_test_'.uniqid(),
'name' => json_encode(['ko' => '테스트', 'en' => 'Test']),
'is_active' => true,
]);
$role->permissions()->sync([$permission->id]);
$this->user->roles()->attach($role->id, ['assigned_at' => now()]);
$this->user = $this->user->fresh();
}
/**
* 비밀번호 확인 단계(1단계)를 수행합니다.
*
* @return TestResponse 로그인 응답
*/
private function login()
{
return $this->postJson('/api/auth/login', [
'email' => self::EMAIL,
'password' => self::PASSWORD,
]);
}
/**
* 임계값까지 로그인을 실패시켜 계정을 잠급니다.
*/
private function lockAccount(): void
{
for ($i = 0; $i < 3; $i++) {
$this->postJson('/api/auth/login', [
'email' => self::EMAIL,
'password' => 'wrong-password',
]);
}
$this->assertTrue(
$this->user->fresh()->locked_until !== null || (bool) $this->user->fresh()->locked_permanently,
'전제 조건 실패 — 계정이 잠기지 않았습니다.'
);
}
/**
* challenge 에 알려진 인증 코드를 심고 그 값을 돌려줍니다.
*
* 발급된 코드는 해시로만 저장되어 되읽을 수 없으므로, 기존 2단계 인증 테스트와 같은
* 방식으로 알려진 값의 해시를 심어 "코드가 맞을 때" 를 재현합니다.
*
* @param string $challengeId challenge UUID
* @return string 심어 둔 인증 코드
*/
private function issuedCode(string $challengeId): string
{
$code = '135790';
$log = IdentityVerificationLog::find($challengeId);
$metadata = $log->metadata ?? [];
$metadata['code_hash'] = Hash::make($code);
$log->metadata = $metadata;
$log->save();
return $code;
}
/**
* 코어 보안 설정을 덮어씁니다.
*
* @param array<string, mixed> $values 덮어쓸 설정 값
*/
private function setSecuritySettings(array $values): void
{
$existing = (array) config('g7_settings.core.security', []);
config(['g7_settings.core.security' => array_merge($existing, $values)]);
}
}
@@ -6,6 +6,7 @@ use App\Enums\ScheduleResultStatus;
use App\Enums\ScheduleType;
use App\Exceptions\LanguagePackOperationException;
use App\Models\Schedule;
use App\Rules\PublicOutboundUrl;
use App\Services\DriverConnectionTester;
use App\Services\LanguagePackService;
use App\Services\ScheduleService;
@@ -99,6 +100,52 @@ class OutboundRequestGuardTest extends TestCase
$this->assertUrlScheduleIsBlocked('http://example.com@169.254.169.254/latest/meta-data/');
}
/**
* FormRequest 게이트(`PublicOutboundUrl` Rule)도 같은 정규화를 거친다.
*
* 이 Rule 이 스케줄 생성·언어팩 URL 설치 등의 프론트도어다. 서비스 계층만 막고
* 여기가 열려 있으면 저장 자체는 성공해 위조 URL 이 설정에 남는다.
*
* @param string $url 내부망을 가리키는 URL
*/
#[DataProvider('internalUrlProvider')]
public function test_public_outbound_url_rule_blocks_internal_addresses(string $url): void
{
$validator = validator(
['endpoint' => $url],
['endpoint' => [new PublicOutboundUrl(['http', 'https'])]],
);
$this->assertTrue(
$validator->fails(),
"차단되어야 하는 URL 이 FormRequest 게이트를 통과함: {$url}"
);
}
/**
* 정규화가 정상 외부 URL 까지 막지는 않는다 (프론트도어 회귀 방지).
*/
public function test_public_outbound_url_rule_still_allows_public_urls(): void
{
$urls = [
'https://api.example.com/shipping/fee',
'https://api.example.com:8443/shipping/fee',
'https://github.com/owner/repo/releases/download/v1/pack.zip',
// 정당한 국제화 도메인은 정규화 후에도 통과해야 한다.
"https://\u{4F8B}\u{3048}.jp/shipping/fee",
'https://xn--r8jz45g.jp/shipping/fee',
];
foreach ($urls as $url) {
$validator = validator(
['endpoint' => $url],
['endpoint' => [new PublicOutboundUrl(['http', 'https'])]],
);
$this->assertFalse($validator->fails(), "정상 URL 이 차단됨: {$url}");
}
}
/**
* URL 스케줄 실행이 차단되고 요청이 전송되지 않았음을 단언합니다.
*
@@ -174,6 +221,17 @@ class OutboundRequestGuardTest extends TestCase
'localhost' => ['http://localhost/pack.zip'],
'사설 IP' => ['http://10.0.0.5/pack.zip'],
'userinfo 위장' => ['https://github.com@127.0.0.1/pack.zip'],
// 점 동등 유니코드 문자(U+3002·U+FF0E·U+FF61)와 전각 슬래시(U+FF0F)는
// 연결 계층의 UTS#46 정규화에서 ASCII 로 바뀐다. 게이트가 원문으로만 판정하면
// 검증 시점과 접속 시점의 host 가 달라져 내부망이 열린다.
'U+3002 로 감춘 localhost' => ["http://localhost\u{3002}/pack.zip"],
'U+FF0E 로 감춘 localhost' => ["http://localhost\u{FF0E}/pack.zip"],
'U+FF61 로 감춘 localhost' => ["http://localhost\u{FF61}/pack.zip"],
'U+3002 로 감춘 루프백 IP' => ["http://127\u{3002}0\u{3002}0\u{3002}1/pack.zip"],
'U+FF0E 로 감춘 메타데이터' => ["http://169\u{FF0E}254\u{FF0E}169\u{FF0E}254/latest/meta-data/"],
'전각 슬래시로 감춘 루프백' => ["http://127.0.0.1\u{FF0F}.example.com/pack.zip"],
'후행 점 localhost' => ['http://localhost./pack.zip'],
];
}
@@ -110,6 +110,159 @@ class OutboundUrlValidatorTest extends TestCase
$this->assertFalse(OutboundUrlValidator::isPublicHost(''));
}
/**
* 점(.) 동등 유니코드 문자로 위장한 내부 주소를 차단한다.
*
* 검증기가 ASCII 점만 구분자로 인식하면 `localhost。` 는 단일 라벨로 보여 공개
* 도메인으로 승인되지만, libcurl/libidn2 는 UTS#46 정규화로 `localhost` 에 연결한다.
* 검증 시점과 연결 시점의 호스트가 달라지는 이 간극이 SSRF 통로다.
*
* @param string $url 검증 대상 URL
* @param string $reason 차단 사유 (실패 메시지용)
*/
#[Test]
#[DataProvider('idnInternalUrlProvider')]
public function it_blocks_unicode_dot_variants_that_resolve_to_internal_hosts(string $url, string $reason): void
{
$this->assertFalse(
OutboundUrlValidator::isPublicHttpUrl($url, ['schemes' => ['http', 'https']]),
"차단되어야 하는 URL 이 통과함 ({$reason}): {$url}"
);
}
/**
* 정규화가 정당한 국제화 도메인(IDN)까지 막지는 않는다.
*
* @param string $url 검증 대상 URL
*/
#[Test]
#[DataProvider('legitimateIdnUrlProvider')]
public function it_still_allows_legitimate_internationalized_domains(string $url): void
{
$this->assertTrue(
OutboundUrlValidator::isPublicHttpUrl($url, ['schemes' => ['http', 'https']]),
"정당한 IDN URL 이 차단됨: {$url}"
);
}
/**
* 화이트리스트 비교도 정규화된 host 로 수행한다.
*
* 유니코드 점으로 화이트리스트 host 뒤에 라벨을 덧붙이는 우회(`kssa.inicis.com。evil.example`)
* 는 차단하고, 정규화 후 완전 일치하는 표기는 허용한다.
*/
#[Test]
public function it_normalizes_hosts_before_whitelist_comparison(): void
{
$this->assertFalse(
OutboundUrlValidator::isHostAllowed("https://kssa.inicis.com\u{3002}attacker.example/", self::HOSTS),
'유니코드 점으로 라벨을 덧붙인 host 가 통과함'
);
$this->assertTrue(
OutboundUrlValidator::isHostAllowed("https://kssa.inicis.com\u{3002}", self::HOSTS),
'정규화 후 화이트리스트와 일치하는 host 가 차단됨'
);
}
/**
* `normalizeHost()` 는 정규화된 A-label host 를 돌려주고, 변환 불가 입력은 null 을 돌려준다.
*
* 이 메서드가 정규화의 SSoT 다 — 검증기 밖 소비자(PG 콜백 URL 접미사 대조 등)가
* 같은 규칙을 재사용해야 판정이 갈리지 않는다.
*/
#[Test]
public function it_exposes_host_normalization_as_a_reusable_primitive(): void
{
$this->assertSame('localhost', OutboundUrlValidator::normalizeHost("localhost\u{3002}"));
$this->assertSame('localhost', OutboundUrlValidator::normalizeHost("LOCALHOST\u{FF0E}"));
$this->assertSame('127.0.0.1', OutboundUrlValidator::normalizeHost("127\u{3002}0\u{3002}0\u{3002}1"));
$this->assertSame('example.com', OutboundUrlValidator::normalizeHost('example.com.'));
$this->assertSame('xn--r8jz45g.jp', OutboundUrlValidator::normalizeHost("\u{4F8B}\u{3048}.jp"));
$this->assertSame('api.nicepay.co.kr', OutboundUrlValidator::normalizeHost('API.NicePay.co.kr'));
$this->assertNull(OutboundUrlValidator::normalizeHost(''));
$this->assertNull(OutboundUrlValidator::normalizeHost(' '));
// 정규화 결과가 host 로 성립하지 않으면(구분자 잔존) 판정 불가 → null.
$this->assertNull(OutboundUrlValidator::normalizeHost("127.0.0.1\u{FF0F}.example.com"));
$this->assertNull(OutboundUrlValidator::normalizeHost('evil.com/.example.com'));
$this->assertNull(OutboundUrlValidator::normalizeHost('ex ample.com'));
$this->assertNull(OutboundUrlValidator::normalizeHost('ex@mple.com'));
$this->assertNull(OutboundUrlValidator::normalizeHost('a%2e.example.com'));
}
/**
* 화이트리스트 접미사 대조도 정규화된 host 로만 성립한다.
*
* 결제 게이트웨이 URL 을 도메인 접미사로 대조하는 소비자가 원문 host 를 그대로 쓰면
* `evil.example/.gateway.example` 이 접미사 검사를 통과하는데, 연결 계층은
* `evil.example` 에 접속한다. 정규화가 이 간극을 없앤다.
*/
#[Test]
public function it_rejects_hosts_whose_normalized_form_hides_a_different_target(): void
{
$host = parse_url("https://evil.example\u{FF0F}.gateway.example/pay", PHP_URL_HOST);
// 원문은 접미사 대조를 통과한다 — 이것이 정규화 없는 대조가 위험한 이유다.
$this->assertTrue(str_ends_with((string) $host, '.gateway.example'));
// 정규화하면 판정 불가로 거부되어 그 통로가 닫힌다.
$this->assertNull(OutboundUrlValidator::normalizeHost((string) $host));
}
/**
* 유니코드 점 변종으로 내부 주소를 가리키는 URL 목록.
*
* @return array<string, array{string, string}>
*/
public static function idnInternalUrlProvider(): array
{
return [
'U+3002 표의문자 마침표 localhost' => ["http://localhost\u{3002}/", 'IDNA 정규화 시 localhost'],
'U+FF0E 전각 마침표 localhost' => ["http://localhost\u{FF0E}/", 'IDNA 정규화 시 localhost'],
'U+FF61 반각 표의문자 마침표 localhost' => ["http://localhost\u{FF61}/", 'IDNA 정규화 시 localhost'],
'대문자 혼용 U+3002' => ["http://LOCALHOST\u{3002}/", '대소문자 무관 localhost'],
'포트 포함 U+3002' => ["http://localhost\u{3002}:9200/_cat/indices", 'IDNA 정규화 시 localhost'],
'U+3002 로 표기한 루프백 IP' => ["http://127\u{3002}0\u{3002}0\u{3002}1/", 'IDNA 정규화 시 127.0.0.1'],
'U+FF0E 로 표기한 메타데이터 IP' => ["http://169\u{FF0E}254\u{FF0E}169\u{FF0E}254/latest/meta-data/", '링크로컬 메타데이터'],
'U+3002 로 표기한 사설 IP' => ["http://192\u{3002}168\u{3002}1\u{3002}1/router", '사설 IP'],
'U+3002 내부 도메인 접미사' => ["http://vault\u{3002}internal/v1/secret", '.internal 내부 도메인'],
'U+FF0E .local 접미사' => ["http://printer\u{FF0E}local/", '.local 내부 도메인'],
'후행 점 localhost' => ['http://localhost./', '완전한 DNS 이름 표기의 localhost'],
'후행 유니코드 점 localhost' => ["http://localhost\u{3002}\u{3002}/", '연속 점 표기의 localhost'],
// U+FF0F FULLWIDTH SOLIDUS 는 UTS#46 에서 ASCII `/` 로 매핑된다.
// parse_url 은 이를 경로 구분자로 보지 않아 host 에 통째로 남기지만,
// 연결 계층은 정규화 후 첫 `/` 앞까지만 host 로 읽는다 — 접미사 대조를
// 통과시키면서 실제로는 앞쪽 주소에 연결하는 우회 통로다.
'전각 슬래시로 감춘 루프백' => ["http://127.0.0.1\u{FF0F}.example.com/", '정규화 시 host 는 127.0.0.1'],
'전각 슬래시로 감춘 localhost' => ["http://localhost\u{FF0F}.example.com/", '정규화 시 host 는 localhost'],
'전각 슬래시로 감춘 메타데이터' => ["http://169.254.169.254\u{FF0F}x.example.com/", '정규화 시 host 는 169.254.169.254'],
'전각 슬래시로 감춘 사설 IP' => ["http://10.0.0.5\u{FF0F}api.example.com/", '정규화 시 host 는 10.0.0.5'],
'전각 역슬래시로 감춘 루프백' => ["http://127.0.0.1\u{FF3C}.example.com/", '정규화 시 구분자가 앞선다'],
'전각 물음표로 감춘 루프백' => ["http://127.0.0.1\u{FF1F}.example.com/", '정규화 시 쿼리 구분자가 앞선다'],
'전각 콜론으로 감춘 루프백' => ["http://127.0.0.1\u{FF1A}80.example.com/", '정규화 시 포트 구분자가 앞선다'],
'전각 골뱅이로 감춘 userinfo' => ["http://example.com\u{FF20}127.0.0.1/", '정규화 시 userinfo 구분자가 앞선다'],
];
}
/**
* 정규화 후에도 통과해야 하는 정당한 국제화 도메인 목록.
*
* @return array<string, array{string}>
*/
public static function legitimateIdnUrlProvider(): array
{
return [
'한글 도메인' => ["https://\u{D55C}\u{AE00}.\u{D55C}\u{AD6D}/"],
'일본어 도메인' => ["https://\u{4F8B}\u{3048}.jp/"],
'이미 punycode 인 도메인' => ['https://xn--r8jz45g.jp/'],
'유니코드 점을 쓴 정당한 공개 도메인' => ["https://api\u{3002}example\u{3002}com/v1/quote"],
'후행 점 있는 공개 도메인' => ['https://api.example.com./v1/quote'],
'독일어 움라우트 도메인' => ["https://b\u{FC}cher.example/"],
];
}
/**
* 화이트리스트 통과 URL 목록.
*
@@ -165,6 +318,11 @@ class OutboundUrlValidatorTest extends TestCase
'http 공개 도메인' => ['http://api.example.co.kr/fee'],
'비표준 포트' => ['https://api.example.com:8443/fee'],
'공인 IP' => ['https://8.8.8.8/'],
// IP 리터럴은 IDNA 라벨 구조가 없다. 정규화의 호스트명 문자 집합 검사에 IPv6 의
// ':' 가 걸리면 공개 IPv6 가 통째로 차단되고, 사설/예약 대역 판정 코드는 도달
// 불가가 된다 — 루프백 차단 케이스만으로는 그 회귀가 드러나지 않는다.
'공인 IPv6' => ['https://[2001:4860:4860::8888]/'],
'공인 IPv6 + 포트' => ['https://[2606:4700:4700::1111]:443/v1'],
'서브도메인' => ['https://shipping.api.example.com/v1/quote'],
];
}
+22
View File
@@ -15,6 +15,7 @@ description: |
만 담당.
axes:
session_issue_path: [password_login, two_factor_complete, token_refresh]
login_attempt_enabled: [true, false]
user_existence: [exists, not_exists]
lock_state: [none, active, expired, permanent]
@@ -35,6 +36,11 @@ exclusions:
- { lockout_minutes_setting: zero, lock_state: expired, reason: "영구 잠금은 만료되지 않음" }
- { unlock_path: admin_manual, user_existence: not_exists, reason: "해제 대상이 없음" }
- { session_issue_path: two_factor_complete, user_existence: not_exists, reason: "challenge 는 이미 확인된 사용자에게만 발급된다 — 미존재 사용자로는 이 지점에 도달하지 못한다" }
- { session_issue_path: token_refresh, user_existence: not_exists, reason: "토큰 재발급은 유효한 세션이 전제 — 미존재 사용자 분기가 없다" }
- { session_issue_path: token_refresh, credential: invalid, reason: "재발급은 자격 증명을 다시 받지 않는다" }
- { session_issue_path: two_factor_complete, unlock_path: admin_manual, reason: "관리자 수동 해제는 잠금 해제 경로 — 2FA 완료 지점의 재검사 축과 교차하지 않는다" }
- { session_issue_path: token_refresh, unlock_path: admin_manual, reason: "동일" }
effects:
- failed_attempt_increments_counter
- counter_reaches_threshold_triggers_lock
@@ -61,10 +67,26 @@ effects:
- admin_manual_unlock_requires_users_update_permission
- finite_lockout_setting_keeps_previous_expiry_behavior
# 세션 발급 지점의 잠금 재검사 — 비밀번호 확인만이 아니라 토큰을 내주는 모든 지점
- lock_recheck_runs_at_every_session_issuing_path
- lock_check_logic_is_a_single_shared_helper_not_a_copy
- two_factor_complete_rechecks_lock_before_auth_login
- challenge_issued_before_lock_cannot_complete_after_lock
- blocked_two_factor_attempt_issues_no_token
- blocked_two_factor_attempt_does_not_reset_failed_attempts
- blocked_two_factor_attempt_does_not_reset_locked_until
- two_factor_locked_response_status_423
- two_factor_locked_response_payload_matches_login_endpoint
- two_factor_lock_recheck_honors_login_attempt_enabled_setting
- unlocked_account_completes_two_factor_normally
- token_refresh_rejects_locked_account
- token_refresh_still_works_for_unlocked_account
test_files:
- tests/Feature/Auth/LoginThrottleTest.php
- tests/Feature/Auth/AccountLockoutTest.php
- tests/Unit/Repositories/UserRepositoryAccountLockTest.php
- tests/Feature/Auth/TwoFactorAccountLockTest.php
rules_layer_coverage:
- rule: service-direct-data-access
@@ -0,0 +1,102 @@
# audit:allow test-scenario-coverage reason: 호스트 형태 축은 데이터 프로바이더 행으로 전개되어 메서드 단위 @scenario 마킹으로 표현할 수 없다. 조합 커버는 test_files 의 프로바이더 행이 담당하고, 본 매니페스트는 "무엇을 반드시 담아야 하는가" 의 SSoT 로 둔다.
feature: 아웃바운드 URL 호스트 정규화 (검증 시점 ↔ 연결 시점 동형)
description: |
서버가 대신 외부로 요청을 보내는 모든 지점의 호스트 판정 계약.
근본 결함: 검증기는 `strtolower(trim($host))` 만 하고, 실제로 연결하는 libcurl/libidn2 는
IDNA/UTS#46 정규화를 한다. 두 시점이 주소를 다르게 읽으면 검증기가 공개 호스트로 승인한
주소가 실제로는 루프백·사설 대역으로 연결된다 (`localhost。` → `localhost`).
불변조건: **판정하는 문자열과 연결되는 문자열이 같다.** 정규화는
`OutboundUrlValidator::normalizeHost()` 단일 지점이 수행하고, 호스트를 보는 모든 경로
(`extractSafeHost` / `isPublicHost` / `isPublicHttpUrl` / `isHostAllowed` /
`isStructurallySafeUrl`, 그리고 검증기를 경유하지 않는 형제
`NicePaymentsApiService::isNicePayUrl`) 가 그 한 곳을 재사용한다. 사본을 두지 않는다.
경계: IP 리터럴은 정규화 대상이 아니다. 호스트명 문자 집합 검사에 IPv6 의 `:` 가 걸리면
사설·예약 대역 판정 코드가 도달 불가가 되어, 정규화가 **공개 IPv6 를 전량 차단**한다.
차단 방향의 회귀라 루프백 케이스만 있는 테스트로는 드러나지 않는다.
축 설계: 판정에 실제로 영향을 주는 입력만 축으로 둔다. 소비자(스케줄·언어팩·배송 API·
결제 승인 URL)는 같은 초크포인트를 공유하므로 축이 아니라 통합 지점의 분담이다.
axes:
host_form: [ascii, ideographic_dot_u3002, fullwidth_dot_uff0e, halfwidth_dot_uff61, trailing_dot, punycode_a_label, unicode_u_label, ip_literal_v4, ip_literal_v6]
target: [loopback_or_private, public]
entry_point: [validator_unit, form_request_rule, schedule_url, language_pack_url, shipping_api_url, nicepay_approval_url]
exclusions:
- { host_form: ip_literal_v4, entry_point: nicepay_approval_url, reason: "나이스페이먼츠 승인 URL 은 도메인 suffix 비교 — IP 리터럴은 어떤 형태든 거부" }
- { host_form: ip_literal_v6, entry_point: nicepay_approval_url, reason: "동일" }
- { host_form: punycode_a_label, target: loopback_or_private, reason: "punycode 는 국제화 도메인 표기 — 루프백/사설 대역에 대응하는 A-label 이 없다" }
- { host_form: unicode_u_label, target: loopback_or_private, reason: "동일 — U-label 정규화 결과가 루프백이 되는 경우는 점 동등문자 축이 담당" }
effects:
# 정규화 SSoT
- normalize_host_is_the_single_normalization_point
- extract_safe_host_delegates_to_normalize_host
- is_public_host_delegates_to_normalize_host
- nicepay_is_nicepay_url_reuses_core_normalize_host
- no_duplicated_normalization_logic_outside_validator
# 점 동등 문자 (보고된 우회 경로)
- ideographic_full_stop_u3002_maps_to_ascii_dot
- fullwidth_full_stop_uff0e_maps_to_ascii_dot
- halfwidth_ideographic_stop_uff61_maps_to_ascii_dot
- normalized_loopback_is_denied
- normalized_private_range_is_denied
- mixed_case_variant_is_denied_after_lowercasing
- trailing_dot_is_stripped_before_comparison
# 정상 입력 회귀 방지 (차단 방향 과잉의 안전망)
- public_ascii_domain_still_allowed
- real_internationalized_domain_still_allowed
- punycode_a_label_still_allowed
- non_standard_port_public_url_still_allowed
- public_ipv4_literal_still_allowed
- public_ipv6_literal_still_allowed
- public_ipv6_literal_with_port_still_allowed
- idn_conversion_failure_denies_instead_of_passing_through
# 소비자 전파 (초크포인트 하나가 전부를 보호하는지)
- schedule_url_rejects_normalized_internal_host
- language_pack_install_from_url_rejects_normalized_internal_host
- shipping_api_endpoint_rejects_normalized_internal_host
- form_request_rule_rejects_normalized_internal_host
- userinfo_disguised_host_is_rejected
- allow_internal_outbound_setting_keeps_structural_check_only
# 형제 (검증기 미경유 경로)
- nicepay_approval_url_rejects_host_that_only_looks_like_nicepay
- nicepay_approval_url_still_accepts_official_hosts
test_files:
- tests/Unit/Support/OutboundUrlValidatorTest.php
- tests/Feature/Security/OutboundRequestGuardTest.php
- plugins/_bundled/sirsoft-pay_nicepayments/tests/Unit/Services/NicePaymentsApiServiceTest.php
manual_verification:
- description: "앱 계층 우회 실측 — 스케줄 URL 생성"
steps:
- "관리자로 스케줄 관리 진입 → URL 호출 스케줄 생성"
- "주소에 ASCII `http://localhost/` → 422 차단 확인"
- "주소에 `http://localhost。/`(U+3002) → 422 차단 확인 (수정 전 201 생성)"
- "U+FF0E · U+FF61 변종도 각각 422 확인"
- "정상 공개 도메인·국제화 도메인은 그대로 생성되는지 확인"
- description: "정상 IPv6 회귀 확인"
steps:
- "공인 IPv6 리터럴 주소(대괄호 표기)로 스케줄 생성 → 허용"
- "루프백 `[::1]` · 사설 `[fc00::1]` → 차단"
notes: |
실행 단계(정규화된 호스트로 실제 루프백 연결이 성립하는지)는 호스트 OS 리졸버에 의존한다.
앱 계층 결함은 생성 201/422 로 판정되므로 실행 단계 재현은 판정 대상이 아니다.
관련 코드:
- app/Support/OutboundUrlValidator.php (normalizeHost = SSoT)
- app/Rules/PublicOutboundUrl.php (FormRequest 게이트)
- app/Services/ScheduleService.php · app/Services/LanguagePackService.php
- modules/_bundled/sirsoft-ecommerce (배송 API 엔드포인트 검증)
- plugins/_bundled/sirsoft-pay_nicepayments/src/Services/NicePaymentsApiService.php (isNicePayUrl)