fix(auth): 2단계 인증을 켠 사이트의 로그인 흐름 구현
2단계 인증은 7.0.6 에서 서버측이 갖춰졌지만 인증번호를 입력할 화면이 어느 버전에도
없었다. 그래서 그 설정을 켠 사이트는 관리자를 포함한 전원이 로그인할 수 없었다.
원인은 `POST /api/auth/login` 이 조건에 따라 **다른 형태의 200** 을 돌려준다는 것이다.
평소에는 `{token, user}` 지만 2단계 인증이 켜져 있으면 `{two_factor_required,
challenge_id, ...}` 를 돌려준다. 프론트는 앞의 형태만 선언하고 `response.data.user.language`
를 바로 읽었으므로 그 자리에서 TypeError 가 났고, 영문 원문이 로그인 화면에 그대로 노출됐다.
서버는 정상 응답했으므로 서버 로그에는 아무 흔적도 남지 않는다.
이어서 `setToken(undefined)` 가 `localStorage` 에 문자열 `"undefined"` 를 남겼다.
이 값은 truthy 라 이후 모든 요청이 `Bearer undefined` 로 나가 401 이 되고, 사용자에게는
「세션이 만료되었습니다」로 보인다. 관리자 로그인은 한발 더 나가 `null->isAdmin` 으로
500 이 되어, 설정을 되돌릴 수단까지 함께 사라졌다.
## 구현
- 로그인 응답을 판별 유니온(`LoginResult`)으로 표현하고, 형태를 판별한 뒤에 읽는다.
`ApiClient.setToken` 은 비어 있지 않은 문자열만 저장한다.
- 사용자·관리자 로그인 화면에 인증번호 입력 단계를 추가했다. 같은 카드 안에서 넘어가며
「인증번호 다시 받기」와 「처음부터」를 제공한다. 관리자 판정은 코드 확인에 성공한 뒤에
수행하고, 거부할 때는 그 직전에 발급된 토큰을 회수한다.
- 재발송(`login/two-factor/resend`)은 기존 challenge 를 취소하고 새로 발행한다. 유효한
코드를 여러 개 살려 두면 대입 시도의 표적이 넓어진다.
- 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데 401 로
뭉개면 사용자는 비밀번호를 의심하며 같은 시도를 반복하고, 운영자는 메일 설정이 깨진
사실을 알 방법이 없다.
- 공개 본인인증 경로(`identity/verify`·`cancel`)가 로그인 목적의 challenge 를 소진하지
못하도록 403 게이트를 세웠다. 소진되면 그 challenge 로 영영 로그인할 수 없다.
- 로그인 시도 제한 429 응답이 다국어 문구를 싣도록 했다(종전에는 프레임워크 기본 영문).
- 다국어 파라미터에서 파이프 표현식이 평가되지 않아 「유효시간 까지」처럼 값이 빠지던
문제를 함께 고쳤다. 같은 결함이 문의 목록 화면에도 있었다.
## 이번 점검에서 함께 고친 것
- 계정 잠금(423)·발송 실패(503) 응답이 사용자·관리자 컨트롤러에 동일하게 복제돼 있었고
그 주석 자신은 "단일 지점에서 만든다" 고 적혀 있었다. 페이로드에 필드가 하나 추가되면
한쪽만 따라가 같은 실패를 두 화면이 다르게 안내하게 된다 — 트레이트로 통합했다.
- 테스트가 개발자 자신의 사이트 설정을 읽고 있었다. 2단계 인증을 켜 둔 환경에서는 로그인
성공을 전제한 테스트가 503 으로 깨지는데 실패 메시지가 원인을 가리키지도 않는다.
같은 결함군을 위해 이미 존재하던 단일 지점에 그 축을 추가했다.
## 버전
코어 7.0.11 · sirsoft-basic 1.1.4 · sirsoft-admin_basic 1.0.9 ·
번들 일본어팩 3종 · 템플릿 엔진 engine-v1.65.0.
This commit is contained in:
1 parent
72fb12f267
commit
50007d5cc6
98 files changed
+5815
-231
No files matched your search
@@ -127,7 +127,7 @@ class LoginThrottleTest extends TestCase
|
||||
/**
|
||||
* @test
|
||||
*/
|
||||
public function login_attempt_enabled_가_OFF_이면_무제한_시도_허용된다(): void
|
||||
public function login_attempt_enabled_가_off_이면_무제한_시도_허용된다(): void
|
||||
{
|
||||
$this->setSecuritySettings([
|
||||
'login_attempt_enabled' => false,
|
||||
@@ -190,7 +190,7 @@ class LoginThrottleTest extends TestCase
|
||||
/**
|
||||
* @test
|
||||
*/
|
||||
public function 존재하지_않는_이메일은_DB에_카운트_저장되지_않는다(): void
|
||||
public function 존재하지_않는_이메일은_db에_카운트_저장되지_않는다(): void
|
||||
{
|
||||
$response = $this->postJson('/api/auth/login', [
|
||||
'email' => 'ghost@example.com',
|
||||
@@ -202,6 +202,41 @@ class LoginThrottleTest extends TestCase
|
||||
$this->assertDatabaseMissing('users', ['email' => 'ghost@example.com']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @test
|
||||
*
|
||||
* @scenario two_factor=off, controller=user, delivery=sent
|
||||
*
|
||||
* @effects too_many_attempts_message_translated
|
||||
*/
|
||||
public function 분당_요청_상한을_넘으면_다국어_문구로_응답한다(): void
|
||||
{
|
||||
// 기본 응답은 영문 "Too Many Attempts." 이다 — 로그인 화면이 그 문구를 그대로
|
||||
// 노출하므로, 한국어 사이트에서 영문 원문이 오류 박스에 뜬다.
|
||||
$limit = max(30, 3 * 6);
|
||||
|
||||
for ($i = 0; $i <= $limit; $i++) {
|
||||
$response = $this->postJson('/api/auth/login', [
|
||||
'email' => 'ghost@example.com',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
if ($response->getStatusCode() === 429) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$response->assertStatus(429);
|
||||
$this->assertNotSame('Too Many Attempts.', $response->json('message'));
|
||||
$this->assertStringNotContainsString(':seconds', (string) $response->json('message'));
|
||||
$this->assertSame(
|
||||
__('auth.too_many_attempts', ['seconds' => (int) $response->headers->get('Retry-After')]),
|
||||
$response->json('message')
|
||||
);
|
||||
// 재시도 시점 안내는 그대로 유지되어야 한다.
|
||||
$this->assertNotNull($response->headers->get('Retry-After'));
|
||||
}
|
||||
|
||||
private function setSecuritySettings(array $values): void
|
||||
{
|
||||
$existing = (array) config('g7_settings.core.security', []);
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Enums\IdentityVerificationPurpose;
|
||||
use App\Enums\IdentityVerificationStatus;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Services\IdentityVerificationService;
|
||||
use Database\Seeders\IdentityMessageDefinitionSeeder;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
@@ -71,6 +74,9 @@ class TwoFactorAuthTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=off, controller=user
|
||||
*/
|
||||
#[Test]
|
||||
public function login_issues_a_token_directly_when_two_factor_is_off(): void
|
||||
{
|
||||
@@ -82,6 +88,11 @@ class TwoFactorAuthTest extends TestCase
|
||||
$this->assertNotEmpty($response->json('data.token'), '2단계 인증이 꺼져 있으면 종전대로 바로 로그인되어야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, delivery=sent
|
||||
*
|
||||
* @effects challenge_response_has_no_token, challenge_response_has_no_user
|
||||
*/
|
||||
#[Test]
|
||||
public function login_withholds_the_token_when_two_factor_is_on(): void
|
||||
{
|
||||
@@ -102,6 +113,9 @@ class TwoFactorAuthTest extends TestCase
|
||||
$this->assertNotEmpty($response->json('data.challenge_id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=valid
|
||||
*/
|
||||
#[Test]
|
||||
public function verifying_the_challenge_completes_the_login(): void
|
||||
{
|
||||
@@ -119,6 +133,9 @@ class TwoFactorAuthTest extends TestCase
|
||||
$this->assertSame('two-factor@test.com', $response->json('data.user.email'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=invalid
|
||||
*/
|
||||
#[Test]
|
||||
public function a_wrong_code_does_not_issue_a_token(): void
|
||||
{
|
||||
@@ -135,6 +152,9 @@ class TwoFactorAuthTest extends TestCase
|
||||
$this->assertNull($response->json('data.token'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=invalid
|
||||
*/
|
||||
#[Test]
|
||||
public function a_challenge_issued_for_another_purpose_cannot_be_used_to_log_in(): void
|
||||
{
|
||||
@@ -157,6 +177,11 @@ class TwoFactorAuthTest extends TestCase
|
||||
$this->assertNull($response->json('data.token'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, delivery=failed
|
||||
*
|
||||
* @effects delivery_failure_503_with_reason
|
||||
*/
|
||||
#[Test]
|
||||
public function login_fails_clearly_when_the_code_cannot_be_delivered(): void
|
||||
{
|
||||
@@ -169,13 +194,289 @@ class TwoFactorAuthTest extends TestCase
|
||||
|
||||
$response = $this->login();
|
||||
|
||||
$response->assertStatus(401);
|
||||
// 자격 증명은 올바르다 — 401 로 답하면 사용자는 비밀번호를 의심하며 같은 실패를
|
||||
// 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다.
|
||||
$response->assertStatus(503);
|
||||
$this->assertSame(__('auth.two_factor_delivery_failed'), $response->json('message'));
|
||||
$this->assertNull(
|
||||
$response->json('data.token'),
|
||||
'발송 실패 시 2단계 인증을 건너뛰고 로그인시키면 보안 통제가 조용히 열립니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=admin, actor=admin, delivery=sent
|
||||
*
|
||||
* @effects admin_login_returns_challenge_not_500
|
||||
*/
|
||||
#[Test]
|
||||
public function admin_login_returns_a_challenge_instead_of_failing(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
$this->makeAdmin($this->user);
|
||||
|
||||
$response = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
]);
|
||||
|
||||
// 관리자 로그인이 2단계 인증에서 500 이 되면 설정을 되돌릴 수단까지 사라진다.
|
||||
$response->assertStatus(200);
|
||||
$this->assertTrue((bool) $response->json('data.two_factor_required'));
|
||||
$this->assertNull($response->json('data.token'));
|
||||
$this->assertNotEmpty($response->json('data.challenge_id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=admin, actor=admin, code=valid
|
||||
*
|
||||
* @effects admin_two_factor_issues_token_for_admin
|
||||
*/
|
||||
#[Test]
|
||||
public function admin_two_factor_completes_the_login(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
$this->makeAdmin($this->user);
|
||||
|
||||
$challengeId = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
])->json('data.challenge_id');
|
||||
|
||||
$response = $this->postJson('/api/auth/admin/login/two-factor', [
|
||||
'challenge_id' => $challengeId,
|
||||
'code' => $this->issuedCode($challengeId),
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertNotEmpty($response->json('data.token'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=admin, actor=non_admin, code=valid
|
||||
*
|
||||
* @effects non_admin_two_factor_revokes_token
|
||||
*/
|
||||
#[Test]
|
||||
public function a_non_admin_completing_admin_two_factor_keeps_no_token(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
])->json('data.challenge_id');
|
||||
|
||||
$response = $this->postJson('/api/auth/admin/login/two-factor', [
|
||||
'challenge_id' => $challengeId,
|
||||
'code' => $this->issuedCode($challengeId),
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
// 코드 확인 시점에 토큰이 이미 발급된다 — 회수하지 않으면 관리자가 아닌 사용자가
|
||||
// 응답만 403 을 받을 뿐 유효한 세션을 손에 쥔다.
|
||||
$this->assertSame(0, $this->user->tokens()->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=off, controller=admin, actor=non_admin
|
||||
*
|
||||
* @effects non_admin_admin_login_revokes_token
|
||||
*/
|
||||
#[Test]
|
||||
public function a_non_admin_rejected_at_admin_login_keeps_no_token(): void
|
||||
{
|
||||
$this->setTwoFactor(false);
|
||||
|
||||
$response = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
$this->assertSame(0, $this->user->tokens()->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, resend=active
|
||||
*
|
||||
* @effects resend_cancels_previous_challenge
|
||||
*/
|
||||
#[Test]
|
||||
public function resending_cancels_the_previous_challenge_and_issues_a_new_one(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$first = $this->login()->json('data.challenge_id');
|
||||
|
||||
$response = $this->postJson('/api/auth/login/two-factor/resend', [
|
||||
'challenge_id' => $first,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$second = $response->json('data.challenge_id');
|
||||
|
||||
$this->assertNotEmpty($second);
|
||||
$this->assertNotSame($first, $second, '재발송이 같은 challenge 를 돌려주면 새 코드가 발송되지 않은 것입니다.');
|
||||
$this->assertNull($response->json('data.token'));
|
||||
|
||||
// 앞선 코드가 계속 통하면 유효한 코드가 여러 개 살아 있어 대입 시도의 표적이 넓어진다.
|
||||
$this->assertSame(
|
||||
IdentityVerificationStatus::Cancelled->value,
|
||||
IdentityVerificationLog::find($first)->status->value
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, resend=verified
|
||||
*
|
||||
* @effects resend_rejects_verified_challenge
|
||||
*/
|
||||
#[Test]
|
||||
public function a_verified_challenge_cannot_be_resent(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->login()->json('data.challenge_id');
|
||||
|
||||
$this->postJson('/api/auth/login/two-factor', [
|
||||
'challenge_id' => $challengeId,
|
||||
'code' => $this->issuedCode($challengeId),
|
||||
])->assertStatus(200);
|
||||
|
||||
$this->postJson('/api/auth/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
])->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, resend=expired
|
||||
*
|
||||
* @effects resend_rejects_expired_challenge
|
||||
*/
|
||||
#[Test]
|
||||
public function an_expired_challenge_cannot_be_resent(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->login()->json('data.challenge_id');
|
||||
|
||||
$log = IdentityVerificationLog::find($challengeId);
|
||||
$log->expires_at = now()->subMinute();
|
||||
$log->save();
|
||||
|
||||
$this->postJson('/api/auth/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
])->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, resend=cancelled
|
||||
*
|
||||
* @effects resend_rejects_cancelled_challenge
|
||||
*/
|
||||
#[Test]
|
||||
public function a_cancelled_challenge_cannot_be_resent(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->login()->json('data.challenge_id');
|
||||
|
||||
app(IdentityVerificationService::class)->cancel($challengeId);
|
||||
|
||||
$this->postJson('/api/auth/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
])->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, resend=active, lock_state=active
|
||||
*
|
||||
* @effects resend_refused_while_locked
|
||||
*/
|
||||
#[Test]
|
||||
public function resending_is_refused_while_the_account_is_locked(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->login()->json('data.challenge_id');
|
||||
|
||||
// challenge 를 받아 둔 뒤 잠긴 계정에는 새 코드를 보내지 않는다.
|
||||
$this->user->forceFill(['locked_until' => now()->addMinutes(10)])->save();
|
||||
|
||||
$this->postJson('/api/auth/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
])->assertStatus(423);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=admin, actor=admin, resend=active
|
||||
*
|
||||
* @effects admin_resend_returns_new_challenge
|
||||
*/
|
||||
#[Test]
|
||||
public function an_admin_can_resend_through_the_admin_endpoint(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
$this->makeAdmin($this->user);
|
||||
|
||||
$challengeId = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
])->json('data.challenge_id');
|
||||
|
||||
$response = $this->postJson('/api/auth/admin/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertNotEmpty($response->json('data.challenge_id'));
|
||||
$this->assertNotSame($challengeId, $response->json('data.challenge_id'));
|
||||
$this->assertNull($response->json('data.token'));
|
||||
// 해석된 사용자는 관리자 등급 판정에만 쓰고 응답에는 실지 않는다.
|
||||
$this->assertNull($response->json('data.user'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=admin, actor=non_admin, resend=active
|
||||
*
|
||||
* @effects admin_resend_refuses_non_admin
|
||||
*/
|
||||
#[Test]
|
||||
public function a_non_admin_cannot_resend_through_the_admin_endpoint(): void
|
||||
{
|
||||
$this->setTwoFactor(true);
|
||||
|
||||
$challengeId = $this->postJson('/api/auth/admin/login', [
|
||||
'email' => 'two-factor@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
])->json('data.challenge_id');
|
||||
|
||||
// 완료할 수 없는 상대에게 새 인증번호를 계속 보내지 않는다.
|
||||
$this->postJson('/api/auth/admin/login/two-factor/resend', [
|
||||
'challenge_id' => $challengeId,
|
||||
])->assertStatus(403);
|
||||
|
||||
$this->assertSame(0, $this->user->tokens()->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자에게 admin 역할을 부여합니다.
|
||||
*
|
||||
* @param User $user 대상 사용자
|
||||
*/
|
||||
private function makeAdmin(User $user): void
|
||||
{
|
||||
// isAdmin() 은 역할 존재가 아니라 admin 타입 권한 보유로 판정한다 —
|
||||
// 역할만 만들어 붙이면 관리자로 인정되지 않아 403 을 측정하게 된다.
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
|
||||
$role = Role::where('identifier', 'admin')->firstOrFail();
|
||||
|
||||
$user->roles()->syncWithoutDetaching([$role->id => ['assigned_at' => now(), 'assigned_by' => null]]);
|
||||
$user->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* challenge 에 알려진 인증 코드를 심고 그 값을 돌려줍니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Identity;
|
||||
|
||||
use App\Enums\IdentityVerificationPurpose;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Models\User;
|
||||
use App\Services\IdentityVerificationService;
|
||||
use Database\Seeders\IdentityMessageDefinitionSeeder;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 공개 본인인증 엔드포인트의 로그인 목적 게이트 테스트.
|
||||
*
|
||||
* 로그인 2단계 인증 challenge 는 `auth/login/two-factor` 로만 완료된다. 공개 본인인증
|
||||
* 화면(`identity/challenges/{id}/verify` · `/cancel`)이 같은 challenge 를 소비하면,
|
||||
* 그 뒤의 로그인 완료가 "이미 처리된 요청" 으로 거절되어 사용자가 자기 challenge 를
|
||||
* 스스로 못 쓰게 만든다(자기 DoS). 그 화면은 로그인 흐름을 모르므로 되돌릴 방법도 없다.
|
||||
*/
|
||||
class IdentityLoginPurposeGateTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $user;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Mail::fake();
|
||||
|
||||
// 공개 IDV 라우트는 permission 미들웨어가 가드한다 — guest 역할 권한이 없으면
|
||||
// 원하는 게이트에 도달하기 전에 401 로 막혀 검사 자체가 공허해진다.
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
$this->seed(IdentityMessageDefinitionSeeder::class);
|
||||
|
||||
$this->user = User::factory()->create([
|
||||
'email' => 'purpose-gate@test.com',
|
||||
'password' => Hash::make('Passw0rd!2fa'),
|
||||
'status' => UserStatus::Active->value,
|
||||
]);
|
||||
|
||||
config(['g7_settings.core.security.two_factor_auth' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=consumed_by_public_verify
|
||||
*
|
||||
* @effects public_verify_rejects_login_purpose
|
||||
*/
|
||||
#[Test]
|
||||
public function the_public_verify_endpoint_refuses_a_login_challenge(): void
|
||||
{
|
||||
$challengeId = $this->startLoginChallenge();
|
||||
|
||||
$response = $this->postJson("/api/identity/challenges/{$challengeId}/verify", [
|
||||
'code' => $this->issuedCode($challengeId),
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
$this->assertSame('PURPOSE_NOT_ALLOWED', $response->json('errors.failure_code'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=consumed_by_public_verify
|
||||
*
|
||||
* @effects public_cancel_rejects_login_purpose
|
||||
*/
|
||||
#[Test]
|
||||
public function the_public_cancel_endpoint_refuses_a_login_challenge(): void
|
||||
{
|
||||
$challengeId = $this->startLoginChallenge();
|
||||
|
||||
$this->postJson("/api/identity/challenges/{$challengeId}/cancel")
|
||||
->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=valid
|
||||
*
|
||||
* @effects login_completes_after_public_endpoints_refuse
|
||||
*/
|
||||
#[Test]
|
||||
public function a_login_challenge_still_completes_after_the_public_endpoints_refuse_it(): void
|
||||
{
|
||||
$challengeId = $this->startLoginChallenge();
|
||||
$code = $this->issuedCode($challengeId);
|
||||
|
||||
$this->postJson("/api/identity/challenges/{$challengeId}/verify", ['code' => $code]);
|
||||
$this->postJson("/api/identity/challenges/{$challengeId}/cancel");
|
||||
|
||||
// 게이트가 상태를 전혀 바꾸지 않아야 로그인이 그대로 완료된다.
|
||||
$response = $this->postJson('/api/auth/login/two-factor', [
|
||||
'challenge_id' => $challengeId,
|
||||
'code' => $code,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertNotEmpty($response->json('data.token'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario two_factor=on, controller=user, code=valid
|
||||
*
|
||||
* @effects signup_purpose_unaffected_by_login_gate
|
||||
*/
|
||||
#[Test]
|
||||
public function a_signup_challenge_is_unaffected_by_the_gate(): void
|
||||
{
|
||||
// 대조군 — 게이트가 로그인 이외 목적까지 막으면 가입·비밀번호 재설정 화면이 통째로 멈춘다.
|
||||
$challenge = app(IdentityVerificationService::class)->start(
|
||||
IdentityVerificationPurpose::Signup->value,
|
||||
$this->user,
|
||||
['origin_type' => 'route', 'origin_identifier' => 'test']
|
||||
);
|
||||
|
||||
$response = $this->postJson("/api/identity/challenges/{$challenge->id}/verify", [
|
||||
'code' => $this->issuedCode($challenge->id),
|
||||
]);
|
||||
|
||||
$this->assertNotSame(403, $response->getStatusCode(), '로그인 이외 목적까지 막으면 가입 흐름이 멈춥니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인 2단계 인증 challenge 를 발급하고 그 id 를 돌려줍니다.
|
||||
*
|
||||
* @return string challenge UUID
|
||||
*/
|
||||
private function startLoginChallenge(): string
|
||||
{
|
||||
return $this->postJson('/api/auth/login', [
|
||||
'email' => 'purpose-gate@test.com',
|
||||
'password' => 'Passw0rd!2fa',
|
||||
])->json('data.challenge_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* challenge 에 알려진 인증 코드를 심고 그 값을 돌려줍니다.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* 최소 SMTP 싱크 (테스트 전용).
|
||||
*
|
||||
* 2단계 인증 실측은 **인증번호 발송이 성공해야** 코드 입력 단계까지 갈 수 있다. 발송이
|
||||
* 실패하면 서버가 로그인을 503 으로 끊기 때문이다(그것도 정당한 동작이라 PHPUnit 이 따로 잰다).
|
||||
*
|
||||
* 그래서 실제 메일을 보내는 대신 받아서 버리는 SMTP 서버를 잠깐 띄우고 사이트의 메일 설정을
|
||||
* 그쪽으로 돌린다. `log` 메일러를 쓰지 않는 이유는 그것이 이 제품의 설정 스키마에 없어서다 —
|
||||
* 등록된 메일 드라이버(smtp·mailgun·ses) 밖의 값은 저장 검증에서 거부되고, 파일을 직접 고쳐도
|
||||
* 드라이버 해석 단계에서 smtp 로 되돌아간다.
|
||||
*
|
||||
* 의존성을 늘리지 않으려고 Node 기본 `net` 만 쓴다. 받은 메일은 어디에도 남기지 않는다.
|
||||
*/
|
||||
import { createServer, type Server, type Socket } from 'node:net';
|
||||
|
||||
/** 띄운 싱크의 핸들 */
|
||||
export type SmtpSink = {
|
||||
port: number;
|
||||
/** 받은 메시지 수 (진단용) */
|
||||
received(): number;
|
||||
close(): Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 한 연결의 SMTP 대화를 처리한다.
|
||||
*
|
||||
* 인증도 TLS 도 요구하지 않는다 — 테스트 전용이며 127.0.0.1 에만 바인딩한다.
|
||||
*
|
||||
* @param socket 클라이언트 소켓
|
||||
* @param onMessage 메시지 1건 수신 시 호출
|
||||
*/
|
||||
function handleConnection(socket: Socket, onMessage: () => void): void {
|
||||
let inData = false;
|
||||
let buffer = '';
|
||||
|
||||
socket.setEncoding('utf-8');
|
||||
socket.write('220 g7-test-sink ESMTP\r\n');
|
||||
|
||||
socket.on('data', (chunk: string) => {
|
||||
buffer += chunk;
|
||||
|
||||
// 본문 수신 중에는 종료 표식(<CRLF>.<CRLF>)만 본다.
|
||||
if (inData) {
|
||||
const terminator = buffer.indexOf('\r\n.\r\n');
|
||||
if (terminator === -1) return;
|
||||
|
||||
buffer = buffer.slice(terminator + 5);
|
||||
inData = false;
|
||||
onMessage();
|
||||
socket.write('250 2.0.0 Ok: queued\r\n');
|
||||
}
|
||||
|
||||
let newline = buffer.indexOf('\r\n');
|
||||
while (! inData && newline !== -1) {
|
||||
const line = buffer.slice(0, newline);
|
||||
buffer = buffer.slice(newline + 2);
|
||||
|
||||
const verb = line.split(' ')[0].toUpperCase();
|
||||
|
||||
if (verb === 'EHLO' || verb === 'HELO') {
|
||||
// 마지막 줄만 하이픈 없이 — 그래야 클라이언트가 목록의 끝을 안다.
|
||||
socket.write('250-g7-test-sink\r\n250 SIZE 10485760\r\n');
|
||||
} else if (verb === 'DATA') {
|
||||
socket.write('354 End data with <CR><LF>.<CR><LF>\r\n');
|
||||
inData = true;
|
||||
} else if (verb === 'QUIT') {
|
||||
socket.write('221 2.0.0 Bye\r\n');
|
||||
socket.end();
|
||||
return;
|
||||
} else {
|
||||
// MAIL FROM / RCPT TO / RSET / NOOP 등 — 전부 수락한다.
|
||||
socket.write('250 2.0.0 Ok\r\n');
|
||||
}
|
||||
|
||||
newline = buffer.indexOf('\r\n');
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('error', () => {
|
||||
// 클라이언트가 먼저 끊는 것은 정상이다 — 테스트를 실패시키지 않는다.
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SMTP 싱크를 띄운다.
|
||||
*
|
||||
* @param preferredPort 우선 시도할 포트 (사용 중이면 다음 포트로)
|
||||
* @returns 싱크 핸들
|
||||
*/
|
||||
export async function startSmtpSink(preferredPort = 2525): Promise<SmtpSink> {
|
||||
let count = 0;
|
||||
|
||||
const server: Server = createServer((socket) => {
|
||||
handleConnection(socket, () => {
|
||||
count += 1;
|
||||
});
|
||||
});
|
||||
|
||||
const port = await new Promise<number>((resolvePort, rejectPort) => {
|
||||
let attempt = 0;
|
||||
|
||||
const tryListen = (candidate: number): void => {
|
||||
server.once('error', (error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'EADDRINUSE' && attempt < 20) {
|
||||
attempt += 1;
|
||||
tryListen(candidate + 1);
|
||||
return;
|
||||
}
|
||||
rejectPort(error);
|
||||
});
|
||||
|
||||
server.listen(candidate, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
resolvePort(typeof address === 'object' && address ? address.port : candidate);
|
||||
});
|
||||
};
|
||||
|
||||
tryListen(preferredPort);
|
||||
});
|
||||
|
||||
return {
|
||||
port,
|
||||
received: () => count,
|
||||
close: () =>
|
||||
new Promise<void>((resolveClose) => {
|
||||
server.close(() => resolveClose());
|
||||
// 열려 있는 연결이 남아도 테스트 종료를 막지 않는다.
|
||||
server.unref();
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* Playwright 2단계 인증 fixture (코어 영역).
|
||||
*
|
||||
* 로그인 2단계 인증은 **사이트 설정과 메일 발송**에 의존한다. 브라우저만으로는 재현할 수 없으므로
|
||||
* 이 fixture 가 세 가지를 가역적으로 준비한다.
|
||||
*
|
||||
* ① 보안 환경설정 `security.two_factor_auth` 를 켜고, 끝나면 원래 값으로 되돌린다.
|
||||
* ② 메일을 받아서 버리는 로컬 SMTP 싱크를 띄우고 메일 설정을 그쪽으로 돌린다. 끝나면
|
||||
* 원래 값으로 되돌린다. (실제 메일을 보내면 테스트가 외부 상태를 바꾼다)
|
||||
* `log` 메일러를 쓰지 않는 이유는 `smtp-sink.ts` 머리말 참조.
|
||||
* ③ 인증번호는 해시로만 저장되어 되읽을 수 없으므로, 알려진 코드를 심는다
|
||||
* (`php artisan playwright:seed-two-factor --plant=…`).
|
||||
*
|
||||
* 보안 설정은 **관리자 설정 API** 로 바꾼다 — 운영자가 화면에서 하는 것과 같은 경로다.
|
||||
* 메일 설정만 파일을 직접 다룬다: 원래 값(빈 SMTP 호스트)은 저장 검증을 통과하지 못해
|
||||
* API 로는 **되돌릴 수 없기 때문**이다. 파일은 바이트 단위로 백업했다가 그대로 복원한다.
|
||||
*
|
||||
* 원복은 실패해도 조용히 넘기지 않는다 — 되돌리지 못한 채 끝나면 사이트가 2단계 인증이 켜진
|
||||
* 상태로 남아 이후 모든 로그인이 막힌다.
|
||||
*/
|
||||
import type { APIRequestContext } from '@playwright/test';
|
||||
import { startSmtpSink, type SmtpSink } from './smtp-sink';
|
||||
import { execSync } from 'node:child_process';
|
||||
import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
/** artisan 이 있는 코어 루트 */
|
||||
function coreRoot(): string {
|
||||
return process.env.G7_ROOT || resolve(__dirname, '../../../');
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 설정 API 경로.
|
||||
*
|
||||
* 절대 URL 을 만들지 않는다 — Playwright 의 `request` 컨텍스트가 `baseURL` 과
|
||||
* `ignoreHTTPSErrors` 를 이미 갖고 있다. Node 의 `fetch` 를 쓰면 자체 서명 인증서를 쓰는
|
||||
* 개발 호스트에서 TLS 로 막히고, 그것을 우회하려면 이 파일이 TLS 검증을 끄게 된다.
|
||||
*/
|
||||
const SETTINGS_PATH = '/api/admin/settings';
|
||||
|
||||
/**
|
||||
* `playwright:seed-two-factor` 를 실행하고 마지막 출력 줄을 돌려준다.
|
||||
*
|
||||
* @param args 커맨드 인자 (예: ['--plant=<uuid>', '--code=135790'])
|
||||
* @returns stdout 의 마지막 비어있지 않은 줄
|
||||
*/
|
||||
export function runSeedTwoFactor(args: string[]): string {
|
||||
const command = `php artisan playwright:seed-two-factor ${args.join(' ')}`.trim();
|
||||
|
||||
let lastError: unknown;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
const stdout = execSync(command, {
|
||||
cwd: coreRoot(),
|
||||
encoding: 'utf-8',
|
||||
env: { ...process.env, G7_PLAYWRIGHT_BYPASS: '1' },
|
||||
});
|
||||
const lines = stdout.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
if (lines.length === 0) {
|
||||
throw new Error(`playwright:seed-two-factor 가 빈 응답을 반환했습니다: ${command}`);
|
||||
}
|
||||
return lines[lines.length - 1].trim();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < 2) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
||||
}
|
||||
|
||||
/**
|
||||
* 알려진 인증번호를 challenge 에 심는다.
|
||||
*
|
||||
* @param challengeId 로그인 응답이 돌려준 challenge UUID
|
||||
* @param code 심을 인증번호 (기본 135790)
|
||||
* @returns 심어 둔 인증번호
|
||||
*/
|
||||
export function plantTwoFactorCode(challengeId: string, code = '135790'): string {
|
||||
return runSeedTwoFactor([`--plant=${challengeId}`, `--code=${code}`, '--gc-hours=0']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실측이 만든 테스트 계정을 전부 제거한다.
|
||||
*
|
||||
* 이 계정들은 알려진 비밀번호를 갖고, 관리자용은 관리자 역할까지 갖는다 — 나이 기준 정리를
|
||||
* 기다리면 그 사이가 그대로 열린 문이다. 실측이 끝나면 즉시 지운다.
|
||||
*
|
||||
* @returns 커맨드의 마지막 출력 줄
|
||||
*/
|
||||
export function purgeTwoFactorUsers(): string {
|
||||
return runSeedTwoFactor(['--purge-users', '--gc-hours=0']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알려진 비밀번호를 가진 Active 테스트 계정을 준비한다.
|
||||
*
|
||||
* @param suffix 계정 구분 접미사 (예: 'user' / 'nonadmin')
|
||||
* @param options admin 역할 부여 여부와 비밀번호
|
||||
* @returns 준비된 계정 이메일
|
||||
*/
|
||||
export function ensureTwoFactorUser(
|
||||
suffix: string,
|
||||
options: { admin?: boolean; password?: string } = {}
|
||||
): string {
|
||||
const args = [`--ensure-user=${suffix}`, `--password=${options.password ?? 'Passw0rd!2fa'}`];
|
||||
if (options.admin) args.push('--admin');
|
||||
return runSeedTwoFactor(args);
|
||||
}
|
||||
|
||||
/** 되돌리기 위해 보관하는 상태 */
|
||||
type TwoFactorFixtureState = {
|
||||
/** 보안 탭 전체 값 (API 로 그대로 되쓴다) */
|
||||
security: Record<string, unknown>;
|
||||
/** 메일 설정 파일 백업 경로 (없으면 파일 자체가 없던 설치) */
|
||||
mailBackupPath: string | null;
|
||||
sink: SmtpSink;
|
||||
};
|
||||
|
||||
/** 메일 설정 파일 경로 */
|
||||
function mailSettingsPath(): string {
|
||||
return resolve(coreRoot(), 'storage/app/settings/mail.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 설정을 SMTP 싱크로 돌린다.
|
||||
*
|
||||
* 값 3개만 줄 단위로 치환한다 — 재직렬화하면 운영자 파일의 서식이 통째로 바뀐다.
|
||||
* `encryption` 을 비우는 이유는 싱크가 STARTTLS 를 제공하지 않기 때문이다.
|
||||
*
|
||||
* @param port 싱크 포트
|
||||
* @returns 백업 파일 경로 (설정 파일이 없으면 null)
|
||||
*/
|
||||
function redirectMailToSink(port: number): string | null {
|
||||
const path = mailSettingsPath();
|
||||
if (! existsSync(path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const backupPath = `${path}.bak-playwright-2fa`;
|
||||
copyFileSync(path, backupPath);
|
||||
|
||||
const original = readFileSync(path, 'utf-8');
|
||||
const swapped = original
|
||||
.replace(/"host"(\s*):(\s*)"[^"]*"/, `"host"$1:$2"127.0.0.1"`)
|
||||
.replace(/"port"(\s*):(\s*)\d+/, `"port"$1:$2${port}`)
|
||||
.replace(/"encryption"(\s*):(\s*)("[^"]*"|null)/, '"encryption"$1:$2""');
|
||||
|
||||
writeFileSync(path, swapped, 'utf-8');
|
||||
|
||||
return backupPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 탭 하나를 통째로 저장한다.
|
||||
*
|
||||
* @param request Playwright API 요청 컨텍스트
|
||||
* @param token 관리자 Sanctum 토큰
|
||||
* @param tab 설정 탭
|
||||
* @param values 저장할 탭 전체 값
|
||||
*/
|
||||
async function writeSettingsTab(
|
||||
request: APIRequestContext,
|
||||
token: string,
|
||||
tab: string,
|
||||
values: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
const write = await request.post(SETTINGS_PATH, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
data: { _tab: tab, [tab]: values },
|
||||
});
|
||||
|
||||
if (!write.ok()) {
|
||||
throw new Error(`${tab} 설정 저장 실패: HTTP ${write.status()} — ${await write.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 탭 하나를 읽고, 지정한 키만 바꿔 저장한다.
|
||||
*
|
||||
* 저장 페이로드는 `{ _tab, <탭>: { ... } }` 형태이고 탭 **전체**가 검증되므로, 바꿀 키만
|
||||
* 보내면 나머지 필수 항목이 422 로 거부된다. 현재 값을 그대로 되돌려 보내 다른 설정은
|
||||
* 건드리지 않는다.
|
||||
*
|
||||
* @param request Playwright API 요청 컨텍스트 (baseURL·ignoreHTTPSErrors 상속)
|
||||
* @param token 관리자 Sanctum 토큰
|
||||
* @param tab 설정 탭 (`security` · `mail` 등)
|
||||
* @param patch 바꿀 키-값
|
||||
* @returns 바꾸기 전의 탭 전체 값 (원복에 그대로 쓴다)
|
||||
*/
|
||||
async function patchSettingsTab(
|
||||
request: APIRequestContext,
|
||||
token: string,
|
||||
tab: string,
|
||||
patch: Record<string, unknown>
|
||||
): Promise<Record<string, unknown>> {
|
||||
const read = await request.get(`${SETTINGS_PATH}?tab=${tab}`, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!read.ok()) {
|
||||
throw new Error(`${tab} 설정 조회 실패: HTTP ${read.status()}`);
|
||||
}
|
||||
|
||||
const body = await read.json();
|
||||
const current = (body?.data?.[tab] ?? {}) as Record<string, unknown>;
|
||||
|
||||
// `_meta` 같은 내부 키는 저장 페이로드에서 제외한다.
|
||||
const previous = Object.fromEntries(
|
||||
Object.entries(current).filter(([key]) => !key.startsWith('_'))
|
||||
);
|
||||
|
||||
await writeSettingsTab(request, token, tab, { ...previous, ...patch });
|
||||
|
||||
return previous;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2단계 인증 실측 환경을 준비한다.
|
||||
*
|
||||
* @param request Playwright API 요청 컨텍스트
|
||||
* @param token 관리자 Sanctum 토큰 (`core.settings.read` · `core.settings.update`)
|
||||
* @returns 되돌리기에 필요한 상태
|
||||
*/
|
||||
export async function enableTwoFactorFixture(
|
||||
request: APIRequestContext,
|
||||
token: string
|
||||
): Promise<TwoFactorFixtureState> {
|
||||
// 메일 경로를 먼저 돌린다 — 2단계 인증을 켠 뒤에 코드가 발행되면 실제 메일이 나간다.
|
||||
const sink = await startSmtpSink();
|
||||
const mailBackupPath = redirectMailToSink(sink.port);
|
||||
|
||||
const security = await patchSettingsTab(request, token, 'security', { two_factor_auth: true });
|
||||
|
||||
return { security, mailBackupPath, sink };
|
||||
}
|
||||
|
||||
/**
|
||||
* 실측 환경을 되돌린다.
|
||||
*
|
||||
* 되돌리지 못한 채 끝나면 사이트가 2단계 인증이 켜진 상태로 남아 이후 모든 로그인이 막힌다 —
|
||||
* 실패는 삼키지 않고 그대로 던진다. 보안 설정을 먼저 되돌리고, 그 실패가 메일 설정 복원을
|
||||
* 가리지 않도록 둘 다 시도한 뒤에 던진다.
|
||||
*
|
||||
* @param request Playwright API 요청 컨텍스트
|
||||
* @param token 관리자 Sanctum 토큰
|
||||
* @param state `enableTwoFactorFixture` 가 돌려준 상태
|
||||
*/
|
||||
export async function restoreTwoFactorFixture(
|
||||
request: APIRequestContext,
|
||||
token: string,
|
||||
state: TwoFactorFixtureState
|
||||
): Promise<void> {
|
||||
let firstError: unknown;
|
||||
|
||||
try {
|
||||
await writeSettingsTab(request, token, 'security', state.security);
|
||||
} catch (error) {
|
||||
firstError = error;
|
||||
}
|
||||
|
||||
if (state.mailBackupPath && existsSync(state.mailBackupPath)) {
|
||||
copyFileSync(state.mailBackupPath, mailSettingsPath());
|
||||
rmSync(state.mailBackupPath, { force: true });
|
||||
}
|
||||
|
||||
await state.sink.close();
|
||||
|
||||
if (firstError) {
|
||||
throw firstError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
/**
|
||||
* 로그인 2단계 인증 종단 검증 (공개 #133).
|
||||
*
|
||||
* 2단계 인증을 켜면 서버가 로그인에 **두 가지 형태의 200** 을 돌려준다. 화면이 한 형태만
|
||||
* 가정하면 영문 오류(`Cannot read properties of undefined`)가 뜨고 로그인이 불가능해지며,
|
||||
* 관리자 로그인은 서버 오류가 되어 설정을 되돌릴 수단까지 사라진다.
|
||||
*
|
||||
* 이 spec 은 사이트 설정과 메일 설정을 **가역적으로** 바꾼다 — `test.afterAll` 이 실패해도
|
||||
* 되돌아가도록 fixture 가 원복을 담당한다. 되돌리지 못하면 이후 모든 로그인이 막히므로
|
||||
* 반드시 `mode: 'serial'` 로 한 워커에서만 실행한다.
|
||||
*
|
||||
* // @scenario controller=user,admin | two_factor=on | code=valid,invalid | resend=active
|
||||
* // @effects challenge_response_has_no_token, code_step_rendered_on_challenge, no_raw_typeerror_text, resend_cancels_previous_challenge, non_admin_two_factor_revokes_token
|
||||
*/
|
||||
import { test, expect, issueToken } from '../../fixtures/auth';
|
||||
import {
|
||||
enableTwoFactorFixture,
|
||||
ensureTwoFactorUser,
|
||||
plantTwoFactorCode,
|
||||
purgeTwoFactorUsers,
|
||||
restoreTwoFactorFixture,
|
||||
} from '../../fixtures/two-factor';
|
||||
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
const PASSWORD = 'Passw0rd!2fa';
|
||||
|
||||
let adminToken: string;
|
||||
let fixtureRequest: import('@playwright/test').APIRequestContext | undefined;
|
||||
let fixtureState: Awaited<ReturnType<typeof enableTwoFactorFixture>>;
|
||||
let memberEmail: string;
|
||||
let adminEmail: string;
|
||||
let nonAdminEmail: string;
|
||||
|
||||
test.beforeAll(async ({ playwright }) => {
|
||||
adminToken = issueToken('core.settings.read', 'core.settings.update');
|
||||
|
||||
memberEmail = ensureTwoFactorUser('user', { password: PASSWORD });
|
||||
adminEmail = ensureTwoFactorUser('admin', { admin: true, password: PASSWORD });
|
||||
nonAdminEmail = ensureTwoFactorUser('nonadmin', { password: PASSWORD });
|
||||
|
||||
// worker 범위 request 컨텍스트 — baseURL·ignoreHTTPSErrors 는 설정에서 온다.
|
||||
fixtureRequest = await playwright.request.newContext({
|
||||
baseURL: process.env.PLAYWRIGHT_BASE_URL,
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
|
||||
fixtureState = await enableTwoFactorFixture(fixtureRequest, adminToken);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// 되돌리지 못한 채 끝나면 사이트의 모든 로그인이 2단계 인증을 요구하게 된다.
|
||||
if (fixtureState && fixtureRequest) {
|
||||
await restoreTwoFactorFixture(fixtureRequest, adminToken, fixtureState);
|
||||
}
|
||||
|
||||
await fixtureRequest?.dispose();
|
||||
|
||||
// 알려진 비밀번호를 가진 계정(관리자 포함)을 남기지 않는다.
|
||||
purgeTwoFactorUsers();
|
||||
});
|
||||
|
||||
/**
|
||||
* 로그인 응답에서 challenge_id 를 읽는다.
|
||||
*
|
||||
* @param page Playwright 페이지
|
||||
* @param urlPart 대기할 요청 경로 조각
|
||||
* @param submit 제출을 수행하는 함수
|
||||
*/
|
||||
async function submitAndReadChallenge(
|
||||
page: import('@playwright/test').Page,
|
||||
urlPart: string,
|
||||
submit: () => Promise<void>
|
||||
): Promise<string> {
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse((r) => r.url().includes(urlPart) && r.request().method() === 'POST'),
|
||||
submit(),
|
||||
]);
|
||||
|
||||
const body = await response.json();
|
||||
expect(response.status(), '2단계 인증이 켜져 있으면 로그인은 200 챌린지를 돌려준다').toBe(200);
|
||||
expect(body?.data?.two_factor_required).toBe(true);
|
||||
// 코드 확인 전에 토큰이 실리면 2단계 인증이 없는 것과 같다.
|
||||
expect(body?.data?.token, '코드 확인 전에 토큰이 발급되었습니다').toBeFalsy();
|
||||
|
||||
return String(body.data.challenge_id);
|
||||
}
|
||||
|
||||
test('사용자 로그인 — 인증번호 단계로 전환되고 코드 확인 후 로그인된다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
// 2단계 입력이 나타나고 1단계 입력은 사라진다.
|
||||
const codeInput = page.locator('input[name="two_factor_code"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.locator('input[name="email"]')).toHaveCount(0);
|
||||
|
||||
// 영문 TypeError 원문이 화면에 남으면 안 된다.
|
||||
await expect(page.locator('body')).not.toContainText('Cannot read properties of undefined');
|
||||
|
||||
// 오답 → 오류 문구, 로그인 미완료
|
||||
await codeInput.fill('000000');
|
||||
await page.click('form button[type="submit"]');
|
||||
await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 10_000 });
|
||||
expect(page.url()).toContain('/login');
|
||||
|
||||
// 정답 → 홈 이동
|
||||
const code = plantTwoFactorCode(challengeId);
|
||||
await codeInput.fill(code);
|
||||
await page.click('form button[type="submit"]');
|
||||
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
const token = await page.evaluate(() => localStorage.getItem('auth_token'));
|
||||
expect(token, '로그인 완료 후 토큰이 저장되어야 합니다').toBeTruthy();
|
||||
expect(token).not.toBe('undefined');
|
||||
});
|
||||
|
||||
test('사용자 로그인 — 인증번호 다시 받기는 새 challenge 를 발급하고 입력을 비운다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const first = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('input[name="two_factor_code"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
await codeInput.fill('111111');
|
||||
|
||||
const [resendResponse] = await Promise.all([
|
||||
page.waitForResponse((r) => r.url().includes('/two-factor/resend') && r.request().method() === 'POST'),
|
||||
page.getByRole('button', { name: /다시|Resend|再送/ }).click(),
|
||||
]);
|
||||
|
||||
const resendBody = await resendResponse.json();
|
||||
expect(resendResponse.status()).toBe(200);
|
||||
const second = String(resendBody.data.challenge_id);
|
||||
expect(second, '재발송이 같은 challenge 를 돌려주면 새 코드가 발송되지 않은 것입니다').not.toBe(first);
|
||||
|
||||
// 앞서 입력한 값이 남아 있으면 새 코드를 받았는데 옛 값으로 제출된다.
|
||||
await expect(codeInput).toHaveValue('');
|
||||
|
||||
const code = plantTwoFactorCode(second);
|
||||
await codeInput.fill(code);
|
||||
await page.click('form button[type="submit"]');
|
||||
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 인증 단계 상태는 전역이라 화면을 떠나도 남는다. 그래서 되돌리는 통로가 셋 다 살아 있어야 한다 —
|
||||
* 「처음부터」 버튼 · 새로고침 · 다른 화면으로 나갔다 돌아오기. 하나라도 빠지면 사용자가 1단계로
|
||||
* 돌아오지 못한 채 이미 만료된 challenge 앞에 갇힌다.
|
||||
*
|
||||
* 새로고침 축은 잘못 저장된 토큰(`"undefined"`) 회귀도 함께 잡는다 — 그 값이 남으면 이후 요청이
|
||||
* 전부 401 이 되어 `/login?reason=session_expired` 로 튕겼다(공개 #133 의 두 번째 증상).
|
||||
*
|
||||
* // @scenario controller=user | two_factor=on | action=restart
|
||||
* // @effects restart_resets_to_credential_step, init_actions_reset_two_factor_state
|
||||
*/
|
||||
test('인증번호 단계 — 처음부터·새로고침·재진입 모두 1단계로 돌아온다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const enterCodeStep = async () => {
|
||||
await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
await expect(page.locator('input[name="two_factor_code"]')).toBeVisible({ timeout: 10_000 });
|
||||
};
|
||||
|
||||
const expectCredentialStep = async () => {
|
||||
await expect(page.locator('input[name="email"]')).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.locator('input[name="two_factor_code"]')).toHaveCount(0);
|
||||
};
|
||||
|
||||
// ① 「처음부터」 버튼
|
||||
await enterCodeStep();
|
||||
await page.getByRole('button', { name: /처음부터|Start over|最初から/ }).click();
|
||||
await expectCredentialStep();
|
||||
|
||||
// ② 새로고침 — 잘못된 토큰이 남았다면 여기서 session_expired 로 튕긴다.
|
||||
await enterCodeStep();
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
expect(page.url(), '새로고침이 만료 안내로 튕기면 토큰이 잘못 저장된 것입니다').not.toContain(
|
||||
'reason=session_expired'
|
||||
);
|
||||
const staleToken = await page.evaluate(() => localStorage.getItem('auth_token'));
|
||||
expect(staleToken, '코드 확인 전에는 토큰이 저장되면 안 됩니다').not.toBe('undefined');
|
||||
await expectCredentialStep();
|
||||
|
||||
// ③ 다른 화면으로 나갔다 돌아오기 — init_actions 리셋이 없으면 2단계가 그대로 남는다.
|
||||
await enterCodeStep();
|
||||
await page.goto('/register');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
await expectCredentialStep();
|
||||
});
|
||||
|
||||
test('관리자 로그인 — 챌린지 응답이 서버 오류가 아니고 코드 확인 후 관리자 화면으로 간다', async ({ page }) => {
|
||||
await page.goto('/admin/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/admin/login', async () => {
|
||||
await page.fill('input[name="email"]', adminEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('#login_submit_button');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('#two_factor_code');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.locator('body')).not.toContainText('Cannot read properties of undefined');
|
||||
|
||||
await codeInput.fill(plantTwoFactorCode(challengeId));
|
||||
await page.locator('#login_two_factor_submit').click();
|
||||
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/admin/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
});
|
||||
|
||||
test('관리자 로그인 — 관리자가 아닌 계정은 코드 확인에 성공해도 거부되고 토큰이 남지 않는다', async ({ page }) => {
|
||||
await page.goto('/admin/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/admin/login', async () => {
|
||||
await page.fill('input[name="email"]', nonAdminEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('#login_submit_button');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('#two_factor_code');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
await codeInput.fill(plantTwoFactorCode(challengeId));
|
||||
|
||||
const [verifyResponse] = await Promise.all([
|
||||
page.waitForResponse((r) => r.url().includes('/admin/login/two-factor') && r.request().method() === 'POST'),
|
||||
page.locator('#login_two_factor_submit').click(),
|
||||
]);
|
||||
|
||||
expect(verifyResponse.status()).toBe(403);
|
||||
|
||||
// 코드 확인 시점에 발급된 토큰이 회수되지 않으면 유효한 세션이 남는다.
|
||||
const token = await page.evaluate(() => localStorage.getItem('auth_token'));
|
||||
expect(token, '거부된 로그인이 토큰을 남겼습니다').toBeFalsy();
|
||||
expect(page.url()).toContain('/admin/login');
|
||||
});
|
||||
|
||||
test('인증번호 단계 — Enter 키는 확인만 보내고 새 challenge 를 발급하지 않는다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('input[name="two_factor_code"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// 세 자리까지는 확인 버튼이 눌리지 않는다.
|
||||
await codeInput.fill('123');
|
||||
const verifyButton = page.locator('form button[type="submit"]');
|
||||
await expect(verifyButton).toBeDisabled();
|
||||
|
||||
await codeInput.fill(plantTwoFactorCode(challengeId));
|
||||
await expect(verifyButton).toBeEnabled();
|
||||
|
||||
const posts: string[] = [];
|
||||
page.on('request', (req) => {
|
||||
if (req.method() === 'POST' && req.url().includes('/api/auth/')) posts.push(req.url());
|
||||
});
|
||||
|
||||
await codeInput.press('Enter');
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
const verifyCalls = posts.filter((u) => u.includes('/login/two-factor')).length;
|
||||
const loginCalls = posts.filter((u) => u.endsWith('/api/auth/login')).length;
|
||||
|
||||
expect(verifyCalls, 'Enter 가 인증번호 확인을 보내지 않았습니다').toBe(1);
|
||||
// 상호배타 조건이 빠지면 Enter 가 새 challenge 를 발급해 흐름이 깨진다.
|
||||
expect(loginCalls, 'Enter 가 비밀번호 단계를 다시 호출했습니다').toBe(0);
|
||||
});
|
||||
|
||||
test('인증번호 단계 — 모바일 폭과 일본어 로케일에서 문구·배치가 깨지지 않는다', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
await page.addInitScript(() => localStorage.setItem('g7_locale', 'ja'));
|
||||
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
await expect(page.locator('input[name="two_factor_code"]')).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// 다국어 키가 해석되지 않으면 `$t:` 토큰이 그대로 화면에 남는다.
|
||||
const body = (await page.locator('body').innerText()) ?? '';
|
||||
expect(body).not.toContain('$t:');
|
||||
expect(body).not.toContain('auth.two_factor');
|
||||
|
||||
// 다시 받기·처음부터 두 버튼이 좁은 폭에서도 컨테이너를 넘지 않는다.
|
||||
const buttons = page.locator('form button[type="button"]');
|
||||
const count = await buttons.count();
|
||||
expect(count).toBeGreaterThanOrEqual(2);
|
||||
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const box = await buttons.nth(i).boundingBox();
|
||||
if (box) {
|
||||
expect(box.width, '버튼이 375px 화면을 넘칩니다').toBeLessThanOrEqual(375);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('공개 본인인증 화면으로는 로그인 challenge 를 소진할 수 없다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
const code = plantTwoFactorCode(challengeId);
|
||||
|
||||
const status = await page.evaluate(async (id) => {
|
||||
const res = await fetch(`/api/identity/challenges/${id}/verify`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ code: '135790' }),
|
||||
});
|
||||
return res.status;
|
||||
}, challengeId);
|
||||
|
||||
expect(status, '로그인 challenge 가 공개 본인인증 경로로 소진되었습니다').toBe(403);
|
||||
|
||||
// 거부는 상태를 바꾸지 않으므로 로그인은 그대로 완료된다.
|
||||
await page.locator('input[name="two_factor_code"]').fill(code);
|
||||
await page.click('form button[type="submit"]');
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 인증번호를 여러 번 틀려도 그 challenge 로 계속 시도할 수 있어야 한다.
|
||||
*
|
||||
* 오답 때마다 입력을 비우면 오타 한 글자를 고치려던 사용자가 전체를 다시 친다 —
|
||||
* 입력을 남기는 것이 확정된 동작이다(레이아웃의 `loginTwoFactor` onError 는 code 를
|
||||
* 건드리지 않는다). 비우도록 바뀌면 아래 `toHaveValue` 가 red 가 된다.
|
||||
*
|
||||
* // @scenario controller=user | two_factor=on | code=invalid,valid
|
||||
* // @effects invalid_code_retries_until_success
|
||||
*/
|
||||
test('인증번호 단계 — 세 번 틀려도 입력이 남고 네 번째 정답으로 로그인된다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('input[name="two_factor_code"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// 본인인증 정책 상한(max_attempts=5) 안이라 세 번까지는 challenge 가 살아 있다.
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
await codeInput.fill('000000');
|
||||
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(r) =>
|
||||
r.url().includes('/api/auth/login/two-factor') &&
|
||||
!r.url().includes('/resend') &&
|
||||
r.request().method() === 'POST'
|
||||
),
|
||||
page.click('form button[type="submit"]'),
|
||||
]);
|
||||
|
||||
expect(response.status(), `${attempt}회째 오답이 거부되지 않았습니다`).toBe(401);
|
||||
await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// 오답 뒤에도 입력은 남는다.
|
||||
await expect(codeInput).toHaveValue('000000');
|
||||
expect(page.url()).toContain('/login');
|
||||
}
|
||||
|
||||
await codeInput.fill(plantTwoFactorCode(challengeId));
|
||||
await page.click('form button[type="submit"]');
|
||||
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 로그인이 끝난 직후의 상태 — 2단계 흔적이 남으면 다음에 로그인 화면을 열었을 때
|
||||
* 비밀번호 단계가 아니라 코드 단계가 뜬다.
|
||||
*
|
||||
* // @scenario controller=user | two_factor=on | code=valid
|
||||
* // @effects session_state_cleared_after_two_factor_success
|
||||
*/
|
||||
test('인증 완료 직후 — 2단계 상태가 지워지고 사용자·토큰이 자리 잡는다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
await page.locator('input[name="two_factor_code"]').fill(plantTwoFactorCode(challengeId));
|
||||
await page.click('form button[type="submit"]');
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
const state = await page.evaluate(() => {
|
||||
const w = window as unknown as Record<string, any>;
|
||||
const globalState = w.__templateApp?.getGlobalState?.() ?? w.G7Core?.state?.get?.() ?? {};
|
||||
|
||||
return {
|
||||
twoFactor: globalState.twoFactor ?? null,
|
||||
isLoggingIn: globalState.isLoggingIn ?? null,
|
||||
uuid: String(globalState.currentUser?.uuid ?? ''),
|
||||
email: String(globalState.currentUser?.email ?? ''),
|
||||
token: String(localStorage.getItem('auth_token') ?? ''),
|
||||
};
|
||||
});
|
||||
|
||||
expect(state.twoFactor, '로그인이 끝났는데 2단계 상태가 남아 있습니다').toBeNull();
|
||||
expect(state.isLoggingIn, '로딩 표시가 켜진 채 남았습니다').toBe(false);
|
||||
expect(state.uuid.length, '로그인한 사용자가 전역 상태에 실리지 않았습니다').toBeGreaterThan(0);
|
||||
expect(state.email).toBe(memberEmail);
|
||||
// `"undefined"` 가 저장되던 결함(#133)은 길이 9 라 존재 검사만으로는 통과한다.
|
||||
expect(state.token.length, '저장된 토큰이 실제 토큰이 아닙니다').toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
/**
|
||||
* 확인 버튼을 빠르게 두 번 눌러도 인증 요청은 한 번만 나가야 한다.
|
||||
*
|
||||
* 두 번 나가면 두 번째가 이미 소진된 challenge 를 확인하려다 실패해, 로그인은 됐는데
|
||||
* 오류 문구가 함께 뜨는 상태가 된다.
|
||||
*
|
||||
* // @scenario controller=user | two_factor=on | code=valid
|
||||
* // @effects double_submit_sends_single_verify_request
|
||||
*/
|
||||
test('인증번호 단계 — 확인 버튼을 두 번 눌러도 확인 요청은 한 번만 나간다', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
|
||||
const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => {
|
||||
await page.fill('input[name="email"]', memberEmail);
|
||||
await page.fill('input[name="password"]', PASSWORD);
|
||||
await page.click('form button[type="submit"]');
|
||||
});
|
||||
|
||||
const codeInput = page.locator('input[name="two_factor_code"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
await codeInput.fill(plantTwoFactorCode(challengeId));
|
||||
|
||||
const verifyCalls: string[] = [];
|
||||
page.on('request', (req) => {
|
||||
if (
|
||||
req.method() === 'POST' &&
|
||||
req.url().includes('/api/auth/login/two-factor') &&
|
||||
!req.url().includes('/resend')
|
||||
) {
|
||||
verifyCalls.push(req.url());
|
||||
}
|
||||
});
|
||||
|
||||
const verifyButton = page.locator('form button[type="submit"]');
|
||||
const startedAt = Date.now();
|
||||
await verifyButton.click();
|
||||
|
||||
// 두 번째 클릭이 도달하기 전에 버튼이 잠겨야 한다. 잠금은 제출 시퀀스가 세우는
|
||||
// `isLoggingIn` 이 화면에 반영될 때 걸리므로, 그 반영이 사람의 두 번째 클릭보다
|
||||
// 빨라야 한다는 뜻이다.
|
||||
await expect(verifyButton).toBeDisabled({ timeout: 1_000 });
|
||||
const lockedAfterMs = Date.now() - startedAt;
|
||||
expect(
|
||||
lockedAfterMs,
|
||||
`확인 버튼이 잠기기까지 ${lockedAfterMs}ms 가 걸렸습니다 — 사람의 두 번째 클릭이 그 사이에 들어옵니다`
|
||||
).toBeLessThan(200);
|
||||
|
||||
// 잠긴 뒤의 두 번째 클릭은 브라우저가 비활성 버튼에 전달하지 않는다.
|
||||
await verifyButton.click({ force: true, timeout: 2_000 }).catch(() => undefined);
|
||||
|
||||
await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), {
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
expect(verifyCalls.length, '확인 요청이 두 번 나갔습니다').toBe(1);
|
||||
});
|
||||
+12
-2
@@ -104,11 +104,21 @@ abstract class TestCase extends BaseTestCase
|
||||
* 기본 모드를 전제한 테스트(자산 URL 생성·blade 렌더)가 그 환경에서만 무더기로 깨진다.
|
||||
* 실제로 이 환경에서 8건이 그렇게 실패했다.
|
||||
*
|
||||
* 다른 모드를 검증해야 하는 테스트는 `AssetUrl::forceMode()` 로 자기 전제를 명시한다.
|
||||
* `security.two_factor_auth` 도 같다. 켜 둔 사이트에서는 `/api/auth/login` 이 토큰이
|
||||
* 아니라 인증 요청(challenge)을 돌려주므로, 로그인 성공을 전제한 테스트가 그 환경에서만
|
||||
* 깨진다. 게다가 테스트 메일러로는 인증번호를 보낼 수 없어 503 이 되므로 실패 메시지가
|
||||
* 원인을 가리키지도 않는다. 실제로 이 환경에서 3건이 그렇게 실패했다.
|
||||
*
|
||||
* 다른 모드를 검증해야 하는 테스트는 `AssetUrl::forceMode()` 로, 2단계 인증을 켜야 하는
|
||||
* 테스트는 `config(['g7_settings.core.security.two_factor_auth' => true])` 로 자기 전제를
|
||||
* 명시한다 (자식 `setUp()` 은 `parent::setUp()` 뒤에 실행되므로 그 지정이 이긴다).
|
||||
*/
|
||||
private function pinEnvironmentDependentSettings(): void
|
||||
{
|
||||
config(['g7_settings.core.general.asset_url_mode' => AssetUrl::MODE_EXTENSION]);
|
||||
config([
|
||||
'g7_settings.core.general.asset_url_mode' => AssetUrl::MODE_EXTENSION,
|
||||
'g7_settings.core.security.two_factor_auth' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# audit:allow test-scenario-coverage reason: 7축 cross product 는 조건부 축(actor 는 controller=admin 에서만,
|
||||
# lock_state 는 세션을 여는 단계에서만, delivery 는 비밀번호 단계에서만 의미가 있다)을 곱해 낸 명목상 조합이라
|
||||
# 개별 케이스에 docblock 을 매핑할 실체가 없다. 실제 회귀 가드는 effects 22건이며 전부 test_files 의
|
||||
# PHPUnit·Playwright 테스트에 @effects 로 귀속되어 있다(미검증 0건).
|
||||
|
||||
feature: 로그인 2단계 인증 (인증번호 확인·재발송)
|
||||
|
||||
description: |
|
||||
보안 환경설정의 「2단계 인증」이 켜져 있으면 비밀번호가 맞아도 토큰을 발급하지 않고
|
||||
인증 요청(challenge)만 돌려준다. 즉 로그인 응답은 **두 가지 형태의 200** 이다.
|
||||
|
||||
핵심 동작:
|
||||
- 사용자·관리자 두 경로가 같은 규칙으로 challenge 를 발급한다. 관리자 판정은
|
||||
코드 확인에 성공한 뒤에 수행한다 (그 전에는 사용자도 토큰도 없다).
|
||||
- 코드 확인 시점에 토큰이 발급되므로, 그 뒤 관리자 판정으로 거부하는 경로는
|
||||
발급분을 반드시 회수한다.
|
||||
- 재발송은 기존 challenge 를 취소하고 새로 발행한다 — 유효한 코드를 여러 개
|
||||
살려 두면 대입 시도의 표적이 넓어진다.
|
||||
- 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데
|
||||
401 로 뭉개면 사용자는 비밀번호를 의심하고 운영자는 원인을 알 수 없다.
|
||||
- 로그인 challenge 는 공개 본인인증 경로(verify/cancel)로 소진할 수 없다.
|
||||
소진되면 그 challenge 로 영영 로그인할 수 없게 된다(자기 DoS).
|
||||
|
||||
axes:
|
||||
controller: [user, admin]
|
||||
two_factor: [on, off]
|
||||
delivery: [sent, failed]
|
||||
code: [valid, invalid, expired, consumed_by_public_verify]
|
||||
resend: [none, active, expired, verified, cancelled]
|
||||
actor: [admin, non_admin]
|
||||
lock_state: [none, active]
|
||||
|
||||
exclusions:
|
||||
- { two_factor: off, code: valid, reason: "2단계 인증이 꺼져 있으면 코드 확인 단계가 없다" }
|
||||
- { two_factor: off, code: invalid, reason: "동일" }
|
||||
- { two_factor: off, code: expired, reason: "동일" }
|
||||
- { two_factor: off, code: consumed_by_public_verify, reason: "동일" }
|
||||
- { two_factor: off, resend: active, reason: "challenge 자체가 발급되지 않는다" }
|
||||
- { two_factor: off, resend: expired, reason: "동일" }
|
||||
- { two_factor: off, resend: verified, reason: "동일" }
|
||||
- { two_factor: off, resend: cancelled, reason: "동일" }
|
||||
- { two_factor: off, delivery: failed, reason: "발송 경로를 타지 않는다" }
|
||||
- { delivery: failed, code: valid, reason: "발송에 실패하면 확인할 코드가 없다" }
|
||||
- { delivery: failed, code: invalid, reason: "동일" }
|
||||
- { delivery: failed, code: expired, reason: "동일" }
|
||||
- { delivery: failed, code: consumed_by_public_verify, reason: "동일" }
|
||||
- { delivery: failed, resend: active, reason: "동일 — 재발송할 challenge 가 없다" }
|
||||
- { delivery: failed, resend: expired, reason: "동일" }
|
||||
- { delivery: failed, resend: verified, reason: "동일" }
|
||||
- { delivery: failed, resend: cancelled, reason: "동일" }
|
||||
- { controller: user, actor: non_admin, reason: "사용자 경로는 관리자 판정을 하지 않는다" }
|
||||
- { resend: active, code: invalid, reason: "재발송은 코드 확인 이전 단계라 코드 상태와 직교하지 않는다" }
|
||||
- { resend: active, code: expired, reason: "동일" }
|
||||
- { resend: active, code: consumed_by_public_verify, reason: "동일" }
|
||||
- { resend: expired, code: invalid, reason: "동일" }
|
||||
- { resend: expired, code: expired, reason: "동일" }
|
||||
- { resend: expired, code: consumed_by_public_verify, reason: "동일" }
|
||||
- { resend: verified, code: invalid, reason: "동일" }
|
||||
- { resend: verified, code: expired, reason: "동일" }
|
||||
- { resend: verified, code: consumed_by_public_verify, reason: "동일" }
|
||||
- { resend: cancelled, code: invalid, reason: "동일" }
|
||||
- { resend: cancelled, code: expired, reason: "동일" }
|
||||
- { resend: cancelled, code: consumed_by_public_verify, reason: "동일" }
|
||||
|
||||
effects:
|
||||
- challenge_response_has_no_token
|
||||
- challenge_response_has_no_user
|
||||
- delivery_failure_503_with_reason
|
||||
- admin_login_returns_challenge_not_500
|
||||
- admin_two_factor_issues_token_for_admin
|
||||
- non_admin_two_factor_revokes_token
|
||||
- non_admin_admin_login_revokes_token
|
||||
- public_verify_rejects_login_purpose
|
||||
- public_cancel_rejects_login_purpose
|
||||
- login_completes_after_public_endpoints_refuse
|
||||
- signup_purpose_unaffected_by_login_gate
|
||||
- resend_cancels_previous_challenge
|
||||
- resend_rejects_verified_challenge
|
||||
- resend_rejects_expired_challenge
|
||||
- resend_rejects_cancelled_challenge
|
||||
- resend_refused_while_locked
|
||||
- admin_resend_returns_new_challenge
|
||||
- admin_resend_refuses_non_admin
|
||||
- too_many_attempts_message_translated
|
||||
- invalid_code_retries_until_success
|
||||
- session_state_cleared_after_two_factor_success
|
||||
- double_submit_sends_single_verify_request
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Auth/TwoFactorAuthTest.php
|
||||
- tests/Feature/Auth/TwoFactorAccountLockTest.php
|
||||
- tests/Feature/Auth/LoginThrottleTest.php
|
||||
- tests/Feature/Identity/IdentityLoginPurposeGateTest.php
|
||||
- tests/Playwright/specs/auth/two-factor-login.spec.ts
|
||||
Reference in new issue
Block a user