refactor(extension): 확장 미들웨어 선언적 self-gate 정규화
확장이 SP Kernel 미들웨어 그룹을 직접 조작하거나 라우트 파일에 미들웨어 FQCN 을 직접 부착하던 임시 방식을, 확장이 부착 대상(targets)을 명시 선언하고 코어가 요청 시점에 라우트명·URI 로 매칭해 실행하는 self-gate 로 정규화. 번들 7건(ecommerce/gdpr/pay 3종) 이전, audit 룰 3건·문서·버전 동기화 동반. 부수적으로 generate-skills.cjs 가 재생성 시 신의성실(부수의무) 섹션을 소실 시키던 회귀를 수정 — 스킬별 불릿을 스크립트 SSoT 로 편입해 재생성에도 보존.
This commit is contained in:
1 parent
8b9bfd0c91
commit
c0e0d82459
57 files changed
+2427
-205
No files matched your search
@@ -4,6 +4,13 @@
|
||||
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
|
||||
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
|
||||
|
||||
## [1.0.1] - 2026-07-15
|
||||
|
||||
### Changed
|
||||
|
||||
- 쿠키 동의 처리 방식을 코어의 새로운 표준 연결 방식으로 옮겼습니다. 모든 페이지 응답에 동의하지 않은 쿠키를 걸러내는 동작은 이전과 동일합니다.
|
||||
- 코어 최소 요구 버전을 7.0.5 로 상향했습니다. 이 플러그인을 업데이트하기 전에 코어를 먼저 최신으로 업데이트하세요.
|
||||
|
||||
## [1.0.0] - 2026-07-01
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "plugins/sirsoft-gdpr",
|
||||
"description": "GDPR (General Data Protection Regulation) plugin for G7 platform by sirsoft",
|
||||
"type": "library",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@plugins/sirsoft-gdpr",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
"ko": "GDPR (일반 데이터 보호 규정)",
|
||||
"en": "GDPR (General Data Protection Regulation)"
|
||||
},
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"description": {
|
||||
"ko": "쿠키 동의 배너, 자동 차단, 동의 이력 저장, 마이페이지 동의 철회를 제공하는 GDPR 대응 플러그인입니다.",
|
||||
"en": "GDPR-ready plugin: cookie consent banner, auto-blocking, consent history, and mypage consent withdrawal."
|
||||
},
|
||||
"license": "MIT",
|
||||
"g7_version": ">=7.0.0",
|
||||
"g7_version": ">=7.0.5",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -8,6 +8,11 @@ use App\Enums\MenuPermissionType;
|
||||
use App\Extension\AbstractPlugin;
|
||||
use App\Extension\Helpers\ExtensionMenuSyncHelper;
|
||||
use App\Models\Menu;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Middleware\CookieConsentMiddleware;
|
||||
use Plugins\Sirsoft\Gdpr\Listeners\GdprAuthConsentListener;
|
||||
use Plugins\Sirsoft\Gdpr\Listeners\GdprAuthLogoutListener;
|
||||
use Plugins\Sirsoft\Gdpr\Listeners\GdprUserDeleteListener;
|
||||
use Plugins\Sirsoft\Gdpr\Listeners\GdprUserWithdrawListener;
|
||||
|
||||
/**
|
||||
* GDPR (일반 데이터 보호 규정) 플러그인
|
||||
@@ -339,6 +344,28 @@ class Plugin extends AbstractPlugin
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인이 등록할 HTTP 미들웨어 선언을 반환합니다.
|
||||
*
|
||||
* functional cookie 게이팅 미들웨어(CookieConsentMiddleware)를 코어 self-gate 방식으로
|
||||
* 선언합니다. EDPB Guidelines 2/2023 §16(사전 차단) 충족을 위해 모든 web/api 응답을
|
||||
* 대상으로 하므로 targets=['everything'](광역 타게팅) + timing=before_core(코어 전처리 전
|
||||
* 응답 처리)로 지정합니다. 코어 ExtensionMiddlewareGate 가 요청 시점에 실행합니다.
|
||||
*
|
||||
* @return array<int, array{class: class-string, groups: array<int, string>, timing?: string, targets: array<int, string>}>
|
||||
*/
|
||||
public function getMiddleware(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'class' => CookieConsentMiddleware::class,
|
||||
'groups' => ['web', 'api'],
|
||||
'timing' => 'before_core',
|
||||
'targets' => ['everything'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 값 반환 (기본값)
|
||||
*
|
||||
@@ -537,10 +564,10 @@ class Plugin extends AbstractPlugin
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [
|
||||
\Plugins\Sirsoft\Gdpr\Listeners\GdprUserWithdrawListener::class,
|
||||
\Plugins\Sirsoft\Gdpr\Listeners\GdprUserDeleteListener::class,
|
||||
\Plugins\Sirsoft\Gdpr\Listeners\GdprAuthLogoutListener::class,
|
||||
\Plugins\Sirsoft\Gdpr\Listeners\GdprAuthConsentListener::class,
|
||||
GdprUserWithdrawListener::class,
|
||||
GdprUserDeleteListener::class,
|
||||
GdprAuthLogoutListener::class,
|
||||
GdprAuthConsentListener::class,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,6 @@
|
||||
namespace Plugins\Sirsoft\Gdpr\Providers;
|
||||
|
||||
use App\Extension\BasePluginServiceProvider;
|
||||
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Middleware\CookieConsentMiddleware;
|
||||
use Plugins\Sirsoft\Gdpr\Repositories\Contracts\GdprPolicyVersionRepositoryInterface;
|
||||
use Plugins\Sirsoft\Gdpr\Repositories\Contracts\GdprUserConsentHistoryRepositoryInterface;
|
||||
use Plugins\Sirsoft\Gdpr\Repositories\Contracts\GdprUserConsentRepositoryInterface;
|
||||
@@ -16,8 +13,10 @@ use Plugins\Sirsoft\Gdpr\Repositories\GdprUserConsentRepository;
|
||||
/**
|
||||
* GDPR 플러그인 서비스 프로바이더.
|
||||
*
|
||||
* Repository 바인딩은 BasePluginServiceProvider 표준에 위임하며, 부트 단계에서
|
||||
* functional cookie 게이팅 미들웨어를 'web' / 'api' 그룹 앞단에 등록합니다 (Phase 2).
|
||||
* Repository 바인딩은 BasePluginServiceProvider 표준에 위임합니다.
|
||||
* functional cookie 게이팅 미들웨어(CookieConsentMiddleware)는 코어 self-gate 방식으로
|
||||
* 이관되어 Plugin::getMiddleware() 가 선언하고 코어 ExtensionMiddlewareGate 가 실행합니다.
|
||||
* (SP Kernel 직접 조작 제거 — EDPB §16 광역 타게팅은 targets=['everything']/before_core 로 유지)
|
||||
*/
|
||||
class GdprServiceProvider extends BasePluginServiceProvider
|
||||
{
|
||||
@@ -28,25 +27,4 @@ class GdprServiceProvider extends BasePluginServiceProvider
|
||||
GdprUserConsentHistoryRepositoryInterface::class => GdprUserConsentHistoryRepository::class,
|
||||
GdprPolicyVersionRepositoryInterface::class => GdprPolicyVersionRepository::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* 부트스트랩 — functional cookie 게이팅 미들웨어를 'web' / 'api' 그룹 앞단에 등록.
|
||||
*
|
||||
* Phase 2: EDPB Guidelines 2/2023 §16 (사전 차단) 충족 — functional 미동의 시 응답에서
|
||||
* functional cookie 제거. Laravel 11+ HTTP Kernel::prependMiddlewareToGroup() 은
|
||||
* 내부적으로 중복 등록을 방지하므로 매 요청 호출되어도 1회만 등록됩니다.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
$kernel = $this->app->make(HttpKernelContract::class);
|
||||
|
||||
if (! $kernel instanceof HttpKernel) {
|
||||
return;
|
||||
}
|
||||
|
||||
$kernel->prependMiddlewareToGroup('web', CookieConsentMiddleware::class);
|
||||
$kernel->prependMiddlewareToGroup('api', CookieConsentMiddleware::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Gdpr\Tests\Unit;
|
||||
|
||||
use Plugins\Sirsoft\Gdpr\Http\Middleware\CookieConsentMiddleware;
|
||||
use Plugins\Sirsoft\Gdpr\Plugin;
|
||||
use Plugins\Sirsoft\Gdpr\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* GDPR 플러그인 미들웨어 선언 계약 테스트.
|
||||
*
|
||||
* CookieConsentMiddleware 를 코어 self-gate 방식(getMiddleware())으로 선언한다.
|
||||
* EDPB Guidelines 2/2023 §16 사전 차단 요건을 위해 web/api 전 응답을 대상으로 하므로
|
||||
* targets=['everything'](광역), timing=before_core(코어 전처리 전) 여야 한다.
|
||||
*/
|
||||
class PluginMiddlewareDeclarationTest extends PluginTestCase
|
||||
{
|
||||
/**
|
||||
* @effects gdpr_cookie_consent_declared_everything_before_core
|
||||
*/
|
||||
public function test_declares_cookie_consent_middleware_via_get_middleware(): void
|
||||
{
|
||||
$plugin = new Plugin;
|
||||
|
||||
$declaration = collect($plugin->getMiddleware())
|
||||
->firstWhere('class', CookieConsentMiddleware::class);
|
||||
|
||||
$this->assertNotNull($declaration, 'Plugin::getMiddleware() 가 CookieConsentMiddleware 를 선언해야 합니다.');
|
||||
$this->assertEqualsCanonicalizing(['web', 'api'], $declaration['groups'], 'web/api 양 그룹 선언이어야 합니다 (전 응답 대상).');
|
||||
$this->assertSame('before_core', $declaration['timing'] ?? null, '코어 전처리 전 응답 처리를 위해 before_core 여야 합니다.');
|
||||
$this->assertContains('everything', $declaration['targets'], 'EDPB §16 광역 타게팅을 위해 targets=everything 이어야 합니다.');
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,8 @@
|
||||
- 쇼핑몰 환경설정 > 주문설정의 결제수단 목록에서 간편결제가 "PG 고정 · KG이니시스"로 표시됩니다. 간편결제는 KG 이니시스 전용이므로 다른 결제대행사로 바꿀 수 없습니다.
|
||||
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화되어 주문서 입력값이 초기화되는 등의 부작용이 사라집니다.
|
||||
- 주문서의 간편결제 버튼에 표시되는 브랜드 로고(네이버페이·삼성페이·카카오페이·L.pay 등)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
|
||||
- 가상계좌 입금통보 등 결제대행사 서버가 직접 보내는 요청의 발신 주소를 확인하는 처리를 코어의 새로운 표준 연결 방식으로 옮겼습니다. 발신 서버 확인 범위(입금통보 계열 경로에만 적용, 브라우저 결제 콜백은 제외)는 이전과 동일합니다.
|
||||
- 위 변경을 위해 코어 최소 요구 버전을 7.0.5로 상향했습니다. 이 플러그인을 업데이트하기 전에 코어를 7.0.5 이상으로 먼저 업데이트해 주세요.
|
||||
|
||||
## [1.0.0] - 2026-07-01
|
||||
|
||||
|
||||
@@ -73,4 +73,6 @@ HTTP/1.1 200
|
||||
|
||||
가상계좌 입금통보를 받을 콜백 URL(PC 웹용 `url`, 모바일용 `mobile_url`)을 관리자 설정 페이지에 표시하기 위해 반환하는 엔드포인트입니다. 라우트 파일 내 클로저로 정의되어 있으며, `url()` 헬퍼로 현재 사이트 도메인 기준의 절대 URL(`/plugins/sirsoft-pay_kginicis/payment/vbank-notify` 및 `.../payment/mobile/vbank-notify`)을 조합해 내려줍니다. 운영자는 이 URL 을 KG 이니시스 가맹점 설정에 입금통보 URL 로 등록해, 구매자가 가상계좌에 실제로 입금했을 때 KG 이니시스가 이 주소로 통보를 보내도록 합니다. 관리자 인증(`auth:sanctum`)과 `sirsoft-ecommerce.settings.read` 권한이 필요하며, 토큰 누락·만료는 401, 권한 부족은 403 으로 응답합니다.
|
||||
|
||||
> **입금통보 수신 엔드포인트의 발신 서버 확인**: 위 URL 이 가리키는 실제 입금통보 수신 경로(`payment/vbank-notify` · `payment/mobile/vbank-notify` · CBT `payment/cbt/cvs-notify`)는 위변조·재처리 방어를 위해 KG 이니시스 공식 발신 IP 만 허용한다. 이 IP 화이트리스트 검사는 코어의 확장 미들웨어 self-gate(`Plugin::getMiddleware()` 의 `targets` 로 입금통보 계열 라우트명에만 정밀 타게팅)로 수행되며, 브라우저가 접속하는 결제 콜백(`payment/callback`)에는 적용되지 않는다. 검사 자체의 동작·허용 범위는 이전과 동일하다.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"ko": "KG 이니시스 결제 게이트웨이 (표준결제창 연동, 일본결제 지원)",
|
||||
"en": "KG Inicis payment gateway (standard payment window, Japan payment support)"
|
||||
},
|
||||
"g7_version": ">=7.0.0",
|
||||
"g7_version": ">=7.0.5",
|
||||
"dependencies": {
|
||||
"modules": {
|
||||
"sirsoft-ecommerce": ">=1.0.0"
|
||||
|
||||
@@ -333,6 +333,30 @@ class Plugin extends AbstractPlugin
|
||||
return is_array($defaults) ? $defaults : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인이 등록할 HTTP 미들웨어 선언을 반환합니다.
|
||||
*
|
||||
* IP 화이트리스트(InicisNotifyIpWhitelist)는 서버 발신 webhook 라우트에만 부착합니다.
|
||||
* 브라우저 POST 콜백(payment.callback 등)은 사용자 IP 라 대상에서 제외 — self 로 뭉치면
|
||||
* 결제 회귀. 코어 ExtensionMiddlewareGate 가 요청 시점에 실행합니다.
|
||||
*
|
||||
* @return array<int, array{class: class-string, groups: array<int, string>, timing?: string, targets: array<int, string>}>
|
||||
*/
|
||||
public function getMiddleware(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'class' => Http\Middleware\InicisNotifyIpWhitelist::class,
|
||||
'groups' => ['web'],
|
||||
'targets' => [
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.cbt.cvs-notify',
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.vbank-notify',
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.mobile.vbank-notify',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Middleware\SetLocale;
|
||||
use App\Http\Middleware\SetTimezone;
|
||||
use App\Http\Middleware\SyncBoostWithDebugMode;
|
||||
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies;
|
||||
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
|
||||
use Illuminate\Routing\Middleware\SubstituteBindings;
|
||||
use Illuminate\Session\Middleware\StartSession;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\View\Middleware\ShareErrorsFromSession;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\CbtCallbackController;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\CbtCvsNotifyController;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\MobileCallbackController;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\PaymentCallbackController;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\PaymentCloseController;
|
||||
use Plugins\Sirsoft\PayKginicis\Controllers\UserEscrowConfirmController;
|
||||
use Plugins\Sirsoft\PayKginicis\Http\Middleware\InicisNotifyIpWhitelist;
|
||||
|
||||
// 에스크로 구매결정: 사용자 인증 필요
|
||||
Route::get('/payment/escrow-confirm/{orderNumber}', [UserEscrowConfirmController::class, 'show'])
|
||||
@@ -21,36 +29,34 @@ Route::get('/payment/escrow-confirm/close', [UserEscrowConfirmController::class,
|
||||
// PC 표준결제창 닫기 (KG 이니시스 closeUrl — 인증 불필요)
|
||||
Route::get('/payment/close', [PaymentCloseController::class, 'show'])
|
||||
->withoutMiddleware([
|
||||
\App\Http\Middleware\SyncBoostWithDebugMode::class,
|
||||
\Illuminate\Cookie\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
\App\Http\Middleware\SetLocale::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
SyncBoostWithDebugMode::class,
|
||||
EncryptCookies::class,
|
||||
AddQueuedCookiesToResponse::class,
|
||||
StartSession::class,
|
||||
ShareErrorsFromSession::class,
|
||||
ValidateCsrfToken::class,
|
||||
SubstituteBindings::class,
|
||||
SetLocale::class,
|
||||
SetTimezone::class,
|
||||
])
|
||||
->name('payment.close');
|
||||
|
||||
Route::withoutMiddleware([\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class])->group(function () {
|
||||
Route::withoutMiddleware([ValidateCsrfToken::class])->group(function () {
|
||||
Route::match(['get', 'post'], '/payment/cbt/callback', [CbtCallbackController::class, 'handle'])
|
||||
->name('payment.cbt.callback');
|
||||
|
||||
// IP 화이트리스트(InicisNotifyIpWhitelist)는 코어 self-gate 로 이관 — Plugin::getMiddleware() 가
|
||||
// cvs-notify/vbank-notify/mobile.vbank-notify webhook 라우트명에만 타게팅 (payment.callback 제외).
|
||||
Route::post('/payment/cbt/cvs-notify', [CbtCvsNotifyController::class, 'handle'])
|
||||
->middleware(InicisNotifyIpWhitelist::class)
|
||||
->name('payment.cbt.cvs-notify');
|
||||
|
||||
Route::post('/payment/callback', [PaymentCallbackController::class, 'authCallback'])
|
||||
->name('payment.callback');
|
||||
|
||||
// KG 이니시스 공식 발송 IP 만 허용 (위변조/재처리 방어)
|
||||
Route::post('/payment/vbank-notify', [PaymentCallbackController::class, 'vbankNotify'])
|
||||
->middleware(InicisNotifyIpWhitelist::class)
|
||||
->name('payment.vbank-notify');
|
||||
|
||||
Route::post('/payment/mobile/vbank-notify', [PaymentCallbackController::class, 'mobileVbankNotify'])
|
||||
->middleware(InicisNotifyIpWhitelist::class)
|
||||
->name('payment.mobile.vbank-notify');
|
||||
|
||||
// (제거됨) /payment/escrow-notify — KG 이니시스 PC 에스크로 매뉴얼에는 webhook
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Plugins\Sirsoft\PayKginicis\Tests\Feature\Middleware;
|
||||
|
||||
use App\Contracts\Extension\ExtensionMiddlewareRegistryInterface;
|
||||
use App\Extension\ExtensionMiddlewareRegistry;
|
||||
use Plugins\Sirsoft\PayKginicis\Http\Middleware\InicisNotifyIpWhitelist;
|
||||
use Plugins\Sirsoft\PayKginicis\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* InicisNotifyIpWhitelist self-gate 타게팅 정밀도 회귀 테스트.
|
||||
*
|
||||
* IP 화이트리스트는 KG 이니시스 서버 발신 webhook 라우트(cvs-notify/vbank-notify/mobile.vbank-notify)
|
||||
* 에만 부착되고, 브라우저 POST 콜백(payment.callback)에는 부착되지 않아야 한다. self 로 뭉치면
|
||||
* 콜백까지 IP 차단돼 결제 실패. 미들웨어 자체가 testing 환경에서 IP 검사를 우회하므로(403 재현 불가),
|
||||
* 게이트 매칭 여부(registry 인덱스)로 타게팅 정밀도를 직접 관측한다.
|
||||
*/
|
||||
class InicisNotifyIpWhitelistGateTest extends PluginTestCase
|
||||
{
|
||||
private function resolveWeb(string $routeName): array
|
||||
{
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
|
||||
return $this->app->make(ExtensionMiddlewareRegistryInterface::class)
|
||||
->resolveForRoute($routeName, 'x', 'web', 'after_core');
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects pay_ip_guard_matched_for_webhook_routes
|
||||
*/
|
||||
public function test_ip_guard_matched_for_webhook_routes(): void
|
||||
{
|
||||
foreach ([
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.cbt.cvs-notify',
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.vbank-notify',
|
||||
'web.plugins.sirsoft-pay_kginicis.payment.mobile.vbank-notify',
|
||||
] as $routeName) {
|
||||
$this->assertContains(
|
||||
InicisNotifyIpWhitelist::class,
|
||||
$this->resolveWeb($routeName),
|
||||
"IP 가드가 webhook 라우트({$routeName})에 매칭되어야 합니다.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects pay_ip_guard_not_matched_for_browser_callback
|
||||
*/
|
||||
public function test_ip_guard_not_matched_for_browser_callback(): void
|
||||
{
|
||||
// 정밀도 회귀: 브라우저 콜백(사용자 IP)에는 IP 가드가 매칭되지 않아야 결제 회귀가 없다.
|
||||
$this->assertNotContains(
|
||||
InicisNotifyIpWhitelist::class,
|
||||
$this->resolveWeb('web.plugins.sirsoft-pay_kginicis.payment.callback'),
|
||||
'IP 가드가 브라우저 콜백에 잘못 매칭되면 결제 콜백이 차단됩니다 (정밀도 회귀).',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,21 @@
|
||||
|
||||
namespace Plugins\Sirsoft\PayKginicis\Tests;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\ExtensionMiddlewareRegistry;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder;
|
||||
use Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider;
|
||||
use Plugins\Sirsoft\PayKginicis\Providers\PayKginicisServiceProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
abstract class PluginTestCase extends TestCase
|
||||
@@ -18,7 +32,7 @@ abstract class PluginTestCase extends TestCase
|
||||
|
||||
protected function seeder(): string
|
||||
{
|
||||
return \Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder::class;
|
||||
return TestingSeeder::class;
|
||||
}
|
||||
|
||||
protected function migrateFreshUsing(): array
|
||||
@@ -43,17 +57,21 @@ abstract class PluginTestCase extends TestCase
|
||||
|
||||
$this->registerModuleAutoload();
|
||||
|
||||
$this->app->register(\Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider::class);
|
||||
$this->app->register(\Plugins\Sirsoft\PayKginicis\Providers\PayKginicisServiceProvider::class);
|
||||
$this->app->register(EcommerceServiceProvider::class);
|
||||
$this->app->register(PayKginicisServiceProvider::class);
|
||||
$this->app['translator']->addNamespace('sirsoft-pay_kginicis', dirname(__DIR__).'/lang');
|
||||
|
||||
$this->registerModuleRoutes();
|
||||
$this->registerPluginRoutes();
|
||||
|
||||
// 코어 self-gate 미들웨어 실행을 위해 이 플러그인을 활성 상태로 등록한다
|
||||
// (getMiddleware() 선언이 게이트 인덱스에 수집되려면 getActivePlugins() 에 포함돼야 함).
|
||||
$this->activateSelfForMiddlewareGate('sirsoft-pay_kginicis', \Plugins\Sirsoft\PayKginicis\Plugin::class);
|
||||
|
||||
// SettingsServiceProvider 가 storage/app/settings/general.json 의 site_url 로
|
||||
// app.url 을 override 하면 Laravel 의 assertRedirect (APP_URL 기반) 와 mismatch.
|
||||
// 테스트 환경에서는 APP_URL 그대로 사용하도록 명시 리셋.
|
||||
\Illuminate\Support\Facades\Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
|
||||
// BaseModuleServiceProvider::registerStorageBindings 가 ModuleManager 에서
|
||||
// 모듈 인스턴스를 조회해 StorageInterface 를 바인딩하는데, 테스트 환경의
|
||||
@@ -146,7 +164,7 @@ abstract class PluginTestCase extends TestCase
|
||||
if (! class_exists($moduleClass)) {
|
||||
return;
|
||||
}
|
||||
$manager = $this->app->make(\App\Extension\ModuleManager::class);
|
||||
$manager = $this->app->make(ModuleManager::class);
|
||||
$ref = new \ReflectionClass($manager);
|
||||
$prop = $ref->getProperty('modules');
|
||||
$prop->setAccessible(true);
|
||||
@@ -173,14 +191,14 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $moduleBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $moduleBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
}
|
||||
});
|
||||
|
||||
$helpersFile = $moduleBasePath . 'Helpers/helpers.php';
|
||||
$helpersFile = $moduleBasePath.'Helpers/helpers.php';
|
||||
if (file_exists($helpersFile)) {
|
||||
require_once $helpersFile;
|
||||
}
|
||||
@@ -203,7 +221,7 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $pluginBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $pluginBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
@@ -218,20 +236,56 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('modules/sirsoft-ecommerce/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
->name('api.modules.sirsoft-ecommerce.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인을 활성 상태로 등록해 코어 self-gate 미들웨어가 실행되도록 합니다.
|
||||
*
|
||||
* 프로덕션에서는 PluginManager 가 활성 플러그인 인스턴스를 보유하고 plugins 테이블의
|
||||
* status='active' 를 캐시한다. RefreshDatabase 테스트에는 둘 다 없으므로,
|
||||
* 라우트명 self-gate 타게팅(web.plugins.{id}.*)이 동작하도록 (1) plugins active 행 삽입
|
||||
* (2) PluginManager 인스턴스 등록 후 상태 캐시·미들웨어 인덱스를 무효화한다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param class-string $pluginClass 플러그인 클래스 FQCN
|
||||
*/
|
||||
protected function activateSelfForMiddlewareGate(string $identifier, string $pluginClass): void
|
||||
{
|
||||
Plugin::query()->updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]
|
||||
);
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
|
||||
$pluginManager = $this->app->make(PluginManager::class);
|
||||
$property = new \ReflectionProperty($pluginManager, 'plugins');
|
||||
$property->setAccessible(true);
|
||||
$plugins = $property->getValue($pluginManager);
|
||||
$plugins[$identifier] = new $pluginClass;
|
||||
$property->setValue($pluginManager, $plugins);
|
||||
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
}
|
||||
|
||||
protected function registerPluginRoutes(): void
|
||||
{
|
||||
$webRoutesFile = base_path('plugins/_bundled/sirsoft-pay_kginicis/src/routes/web.php');
|
||||
|
||||
if (file_exists($webRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('plugins/sirsoft-pay_kginicis')
|
||||
->name('plugins.sirsoft-pay_kginicis.')
|
||||
// 프로덕션 PluginRouteServiceProvider 와 동일한 'web.plugins.' 이름 접두사 —
|
||||
// 코어 self-gate 미들웨어가 라우트명(web.plugins.{id}.*)으로 타게팅하므로 정합 필수.
|
||||
Route::prefix('plugins/sirsoft-pay_kginicis')
|
||||
->name('web.plugins.sirsoft-pay_kginicis.')
|
||||
->middleware('web')
|
||||
->group($webRoutesFile);
|
||||
}
|
||||
@@ -239,36 +293,36 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('plugins/_bundled/sirsoft-pay_kginicis/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/plugins/sirsoft-pay_kginicis')
|
||||
Route::prefix('api/plugins/sirsoft-pay_kginicis')
|
||||
->name('api.plugins.sirsoft-pay_kginicis.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
}
|
||||
}
|
||||
|
||||
protected function createAdminUser(array $permissions = []): \App\Models\User
|
||||
protected function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
$uniqueRoleIdentifier = 'admin-test-' . $user->id . '-' . time();
|
||||
$userRole = \App\Models\Role::create([
|
||||
$uniqueRoleIdentifier = 'admin-test-'.$user->id.'-'.time();
|
||||
$userRole = Role::create([
|
||||
'identifier' => $uniqueRoleIdentifier,
|
||||
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
|
||||
]);
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
$adminAccessPermission = \App\Models\Permission::firstOrCreate(
|
||||
$adminAccessPermission = Permission::firstOrCreate(
|
||||
['identifier' => 'admin.access'],
|
||||
[
|
||||
'name' => ['ko' => '관리자 접근', 'en' => 'Admin Access'],
|
||||
'type' => \App\Enums\PermissionType::Admin,
|
||||
'type' => PermissionType::Admin,
|
||||
]
|
||||
);
|
||||
$userRole->permissions()->attach($adminAccessPermission->id);
|
||||
|
||||
if (! empty($permissions)) {
|
||||
foreach ($permissions as $permissionIdentifier) {
|
||||
$permission = \App\Models\Permission::firstOrCreate(
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permissionIdentifier],
|
||||
[
|
||||
'name' => ['ko' => $permissionIdentifier, 'en' => $permissionIdentifier],
|
||||
@@ -282,10 +336,10 @@ abstract class PluginTestCase extends TestCase
|
||||
return $user;
|
||||
}
|
||||
|
||||
protected function createUser(): \App\Models\User
|
||||
protected function createUser(): User
|
||||
{
|
||||
$userRole = \App\Models\Role::where('identifier', 'user')->first();
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$userRole = Role::where('identifier', 'user')->first();
|
||||
$user = User::factory()->create();
|
||||
|
||||
if ($userRole) {
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화됩니다.
|
||||
- 주문서의 간편결제 버튼에 표시되는 브랜드 마크(PAYCO·네이버페이·카카오페이 등의 색상 배지)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
|
||||
- 애플페이 간편결제 버튼이 iOS 기기(iPhone·iPad)에서만 주문서에 표시되도록 했습니다. 애플페이는 iOS에서만 결제할 수 있으므로 다른 기기에서는 버튼을 감춰 혼선을 줄입니다.
|
||||
- 가상계좌 입금통보·에스크로 공통통보 등 결제대행사 서버가 직접 보내는 요청의 발신 주소를 확인하는 처리를 코어의 새로운 표준 연결 방식으로 옮겼습니다. 발신 서버 확인 범위(통보 계열 경로에만 적용, 브라우저 결제 콜백은 제외)는 이전과 동일합니다.
|
||||
- 위 변경을 위해 코어 최소 요구 버전을 7.0.5로 상향했습니다. 이 플러그인을 업데이트하기 전에 코어를 7.0.5 이상으로 먼저 업데이트해 주세요.
|
||||
|
||||
## [1.0.0-beta.5] - 2026-06-23
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# API 레퍼런스 문서 목차
|
||||
|
||||
> **소유**: 플러그인 `sirsoft-pay_nhnkcp` · 이 확장의 웹 라우트는 대부분 결제대행사(NHN KCP)와 브라우저가 직접 주고받는 콜백/통보 경로이며, 표준 JSON API 표면이 아니다. 아래 문서는 그중 운영·보안상 명시가 필요한 경로를 사람이 서술한 레퍼런스다.
|
||||
|
||||
| 문서 | 도메인 | 설명 |
|
||||
| --- | --- | --- |
|
||||
| [vbank.md](vbank.md) | `payment` | 가상계좌 입금통보·에스크로 공통통보 수신 경로와 발신 서버(IP) 확인 |
|
||||
@@ -0,0 +1,32 @@
|
||||
# Vbank / 통보 수신 API 레퍼런스
|
||||
|
||||
> **소유**: 플러그인 `sirsoft-pay_nhnkcp`. 이 문서는 결제대행사(NHN KCP) 서버가 직접 POST 로 보내는 통보 수신 경로를 서술한다. 브라우저가 접속하는 결제 콜백과는 접근 제어가 다르다.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. NHN KCP 서버가 직접 보내는 통보(가상계좌 입금·에스크로 공통)를 받는 경로다
|
||||
2. 통보 수신 경로는 KCP 공식 발신 IP 만 허용한다 (위변조·재처리 방어)
|
||||
3. IP 화이트리스트는 코어 확장 미들웨어 self-gate 로 통보 라우트명에만 적용된다
|
||||
4. 브라우저 결제 콜백(payment.callback)에는 IP 확인이 적용되지 않는다
|
||||
5. 검사 동작·허용 범위는 라우트 파일 직접 부착 시절과 동일하다
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 통보 수신 경로
|
||||
|
||||
| 라우트명 | 메서드/URI | 용도 |
|
||||
| --- | --- | --- |
|
||||
| `web.plugins.sirsoft-pay_nhnkcp.payment.vbank-notify` | `POST /plugins/sirsoft-pay_nhnkcp/payment/vbank-notify` | 가상계좌 입금통보(NOTI) 수신 |
|
||||
| `web.plugins.sirsoft-pay_nhnkcp.payment.escrow-common-notify` | `POST /plugins/sirsoft-pay_nhnkcp/payment/escrow-common-notify` | 에스크로 공통통보 수신 |
|
||||
|
||||
**설명**
|
||||
|
||||
위 두 경로는 NHN KCP 서버가 구매자의 가상계좌 실입금·에스크로 상태 변경을 가맹점에 알리기 위해 직접 POST 로 호출한다. 브라우저를 거치지 않는 서버 대 서버 통신이므로, 위변조·재처리 요청을 막기 위해 **NHN KCP 공식 발신 IP 만 허용**한다.
|
||||
|
||||
이 IP 화이트리스트 검사는 코어의 확장 미들웨어 self-gate(`Plugin::getMiddleware()` 의 `targets` 로 위 두 통보 라우트명에만 정밀 타게팅)로 수행된다. 브라우저가 접속하는 결제 콜백(`payment.callback`)에는 적용되지 않는다 — 콜백은 정상 사용자의 브라우저에서 임의 IP 로 도달하므로 IP 로 제한하면 결제가 끊긴다. 검사 자체의 동작·허용 범위는 라우트 파일에서 직접 부착하던 이전 방식과 동일하다.
|
||||
|
||||
상세: [docs/backend/middleware.md "확장 미들웨어 선언 (self-gate)"](../../../../../docs/backend/middleware.md).
|
||||
@@ -13,7 +13,7 @@
|
||||
"ko": "NHN KCP 결제 게이트웨이 (Standard Pay 연동)",
|
||||
"en": "NHN KCP payment gateway (Standard Pay integration)"
|
||||
},
|
||||
"g7_version": ">=7.0.0-beta.2",
|
||||
"g7_version": ">=7.0.5",
|
||||
"dependencies": {
|
||||
"modules": {
|
||||
"sirsoft-ecommerce": ">=1.0.0-beta.5"
|
||||
|
||||
@@ -120,11 +120,11 @@ class Plugin extends AbstractPlugin
|
||||
],
|
||||
],
|
||||
'easy_pay_allow_with_other_pg' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_payco' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_naverpay' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_naverpay_point' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_kakaopay' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_applepay' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_payco' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_naverpay' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_naverpay_point' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_kakaopay' => ['type' => 'boolean', 'default' => false],
|
||||
'easy_pay_applepay' => ['type' => 'boolean', 'default' => false],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -142,11 +142,34 @@ class Plugin extends AbstractPlugin
|
||||
'escrow_test_site_cd' => '',
|
||||
'vbank_expire_days' => 3,
|
||||
'easy_pay_allow_with_other_pg' => false,
|
||||
'easy_pay_payco' => false,
|
||||
'easy_pay_naverpay' => false,
|
||||
'easy_pay_naverpay_point' => false,
|
||||
'easy_pay_kakaopay' => false,
|
||||
'easy_pay_applepay' => false,
|
||||
'easy_pay_payco' => false,
|
||||
'easy_pay_naverpay' => false,
|
||||
'easy_pay_naverpay_point' => false,
|
||||
'easy_pay_kakaopay' => false,
|
||||
'easy_pay_applepay' => false,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인이 등록할 HTTP 미들웨어 선언을 반환합니다.
|
||||
*
|
||||
* IP 화이트리스트(RestrictKcpIp)는 KCP 서버 발신 webhook 라우트에만 부착합니다.
|
||||
* 브라우저 POST 콜백(payment.callback)은 사용자 IP 라 대상에서 제외 — 결제 회귀 방지.
|
||||
* 코어 ExtensionMiddlewareGate 가 요청 시점에 실행합니다.
|
||||
*
|
||||
* @return array<int, array{class: class-string, groups: array<int, string>, timing?: string, targets: array<int, string>}>
|
||||
*/
|
||||
public function getMiddleware(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'class' => Http\Middleware\RestrictKcpIp::class,
|
||||
'groups' => ['web'],
|
||||
'targets' => [
|
||||
'web.plugins.sirsoft-pay_nhnkcp.payment.vbank-notify',
|
||||
'web.plugins.sirsoft-pay_nhnkcp.payment.escrow-common-notify',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Controllers\EscrowCommonNotifyController;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Controllers\PaymentCallbackController;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Http\Middleware\RestrictKcpIp;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@@ -22,19 +22,18 @@ use Plugins\Sirsoft\PayNhnkcp\Http\Middleware\RestrictKcpIp;
|
||||
|
|
||||
*/
|
||||
|
||||
Route::withoutMiddleware([\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class])->group(function () {
|
||||
Route::withoutMiddleware([ValidateCsrfToken::class])->group(function () {
|
||||
// 결제 승인 콜백 (KCP → 브라우저 POST)
|
||||
Route::post('/payment/callback', [PaymentCallbackController::class, 'authCallback'])
|
||||
->name('payment.callback');
|
||||
|
||||
// KCP 서버 발신 webhook 그룹 (IP 화이트리스트 가드)
|
||||
Route::middleware(RestrictKcpIp::class)->group(function () {
|
||||
// 가상계좌 입금 통보 (KCP 서버 → 우리 서버 POST)
|
||||
Route::post('/payment/vbank-notify', [PaymentCallbackController::class, 'vbankNotify'])
|
||||
->name('payment.vbank-notify');
|
||||
// KCP 서버 발신 webhook (IP 화이트리스트 가드는 코어 self-gate 로 이관 —
|
||||
// Plugin::getMiddleware() 가 vbank-notify/escrow-common-notify 라우트명에만 타게팅).
|
||||
// 가상계좌 입금 통보 (KCP 서버 → 우리 서버 POST)
|
||||
Route::post('/payment/vbank-notify', [PaymentCallbackController::class, 'vbankNotify'])
|
||||
->name('payment.vbank-notify');
|
||||
|
||||
// 에스크로 공통통보 (KCP 서버 → 우리 서버 POST: TX02 구매확인/취소, TX03 배송시작)
|
||||
Route::post('/payment/escrow-common-notify', [EscrowCommonNotifyController::class, 'handle'])
|
||||
->name('payment.escrow-common-notify');
|
||||
});
|
||||
// 에스크로 공통통보 (KCP 서버 → 우리 서버 POST: TX02 구매확인/취소, TX03 배송시작)
|
||||
Route::post('/payment/escrow-common-notify', [EscrowCommonNotifyController::class, 'handle'])
|
||||
->name('payment.escrow-common-notify');
|
||||
});
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Plugins\Sirsoft\PayNhnkcp\Tests\Feature\Middleware;
|
||||
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
@@ -30,7 +31,7 @@ class RestrictKcpIpTest extends PluginTestCase
|
||||
$mock->method('get')->willReturn([
|
||||
'is_test_mode' => $isTestMode,
|
||||
'redirect_success_url' => '/shop/orders/{orderId}/complete',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
]);
|
||||
$this->app->instance(PluginSettingsService::class, $mock);
|
||||
}
|
||||
@@ -40,23 +41,26 @@ class RestrictKcpIpTest extends PluginTestCase
|
||||
$mock = $this->createMock(PluginSettingsService::class);
|
||||
$mock->method('get')->willReturn([
|
||||
'redirect_success_url' => '/shop/orders/{orderId}/complete',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
]);
|
||||
$this->app->instance(PluginSettingsService::class, $mock);
|
||||
}
|
||||
|
||||
private function postVbankNotify(string $remoteIp): \Illuminate\Testing\TestResponse
|
||||
private function postVbankNotify(string $remoteIp): TestResponse
|
||||
{
|
||||
return $this->withServerVariables(['REMOTE_ADDR' => $remoteIp])
|
||||
->post('/plugins/sirsoft-pay_nhnkcp/payment/vbank-notify', [
|
||||
'tno' => 'KCP_TNO_TEST',
|
||||
'order_no' => 'ORD-IP-TEST',
|
||||
'tx_cd' => 'TX00',
|
||||
'op_cd' => '50',
|
||||
'tno' => 'KCP_TNO_TEST',
|
||||
'order_no' => 'ORD-IP-TEST',
|
||||
'tx_cd' => 'TX00',
|
||||
'op_cd' => '50',
|
||||
'ipgm_mnyx' => 30000,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects pay_ip_guard_matched_for_webhook_routes
|
||||
*/
|
||||
public function test_blocks_unauthorized_ip_in_live_mode(): void
|
||||
{
|
||||
$this->mockSettings(isTestMode: false);
|
||||
@@ -66,6 +70,28 @@ class RestrictKcpIpTest extends PluginTestCase
|
||||
$response->assertForbidden();
|
||||
}
|
||||
|
||||
/**
|
||||
* self-gate 타게팅 정밀도 회귀: IP 가드는 브라우저 POST 콜백(payment.callback)에는
|
||||
* 부착되지 않아야 한다. 콜백은 사용자 IP 라 화이트리스트로 차단하면 결제 실패.
|
||||
* 미인가 IP 로 콜백을 호출해도 IP 가드에 의한 403 이 발생하지 않음을 단언한다
|
||||
* (컨트롤러는 검증 실패로 302 redirect 하지만 핵심은 403(IP 차단)이 아니라는 것).
|
||||
*
|
||||
* @effects pay_ip_guard_not_matched_for_browser_callback
|
||||
*/
|
||||
public function test_ip_guard_not_applied_to_browser_callback_route(): void
|
||||
{
|
||||
$this->mockSettings(isTestMode: false);
|
||||
|
||||
$response = $this->withServerVariables(['REMOTE_ADDR' => self::UNAUTHORIZED_IP])
|
||||
->post('/plugins/sirsoft-pay_nhnkcp/payment/callback', [
|
||||
'res_cd' => 'XXXX',
|
||||
'ordr_idxx' => 'ORD-CALLBACK-TEST',
|
||||
]);
|
||||
|
||||
// IP 가드가 붙었다면 403 이었을 것 — 붙지 않았으므로 403 이 아니어야 한다.
|
||||
$this->assertNotSame(403, $response->getStatusCode(), 'IP 가드가 브라우저 콜백에 잘못 부착되어 결제 콜백을 차단했습니다 (정밀도 회귀).');
|
||||
}
|
||||
|
||||
public function test_missing_test_mode_setting_fails_closed_for_unauthorized_ip(): void
|
||||
{
|
||||
$this->mockSettingsWithoutMode();
|
||||
|
||||
@@ -2,7 +2,19 @@
|
||||
|
||||
namespace Plugins\Sirsoft\PayNhnkcp\Tests;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\ExtensionMiddlewareRegistry;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder;
|
||||
use Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
abstract class PluginTestCase extends TestCase
|
||||
@@ -16,7 +28,7 @@ abstract class PluginTestCase extends TestCase
|
||||
|
||||
protected function seeder(): string
|
||||
{
|
||||
return \Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder::class;
|
||||
return TestingSeeder::class;
|
||||
}
|
||||
|
||||
protected function migrateFreshUsing(): array
|
||||
@@ -40,15 +52,53 @@ abstract class PluginTestCase extends TestCase
|
||||
$this->registerModuleAutoload();
|
||||
$this->registerPluginAutoload();
|
||||
|
||||
$this->app->register(\Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider::class);
|
||||
$this->app->register(EcommerceServiceProvider::class);
|
||||
|
||||
$this->registerModuleRoutes();
|
||||
$this->registerPluginRoutes();
|
||||
|
||||
// 코어 self-gate 미들웨어 실행을 위해 이 플러그인을 활성 상태로 등록한다
|
||||
// (getMiddleware() 선언이 게이트 인덱스에 수집되려면 getActivePlugins() 에 포함돼야 함).
|
||||
$this->activateSelfForMiddlewareGate('sirsoft-pay_nhnkcp', \Plugins\Sirsoft\PayNhnkcp\Plugin::class);
|
||||
|
||||
// SettingsServiceProvider 가 storage/app/settings/general.json 의 site_url 로
|
||||
// app.url 을 override 하면 Laravel 의 assertRedirect (APP_URL 기반) 와 mismatch.
|
||||
// 테스트 환경에서는 APP_URL 그대로 사용하도록 명시 리셋.
|
||||
\Illuminate\Support\Facades\Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인을 활성 상태로 등록해 코어 self-gate 미들웨어가 실행되도록 합니다.
|
||||
*
|
||||
* 프로덕션에서는 PluginManager 가 활성 플러그인 인스턴스를 보유하고 plugins 테이블의
|
||||
* status='active' 를 캐시한다. RefreshDatabase 테스트에는 둘 다 없으므로,
|
||||
* 라우트명 self-gate 타게팅(web.plugins.{id}.*)이 동작하도록 (1) plugins active 행 삽입
|
||||
* (2) PluginManager 인스턴스 등록 후 상태 캐시·미들웨어 인덱스를 무효화한다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param class-string $pluginClass 플러그인 클래스 FQCN
|
||||
*/
|
||||
protected function activateSelfForMiddlewareGate(string $identifier, string $pluginClass): void
|
||||
{
|
||||
Plugin::query()->updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]
|
||||
);
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
|
||||
$pluginManager = $this->app->make(PluginManager::class);
|
||||
$property = new \ReflectionProperty($pluginManager, 'plugins');
|
||||
$property->setAccessible(true);
|
||||
$plugins = $property->getValue($pluginManager);
|
||||
$plugins[$identifier] = new $pluginClass;
|
||||
$property->setValue($pluginManager, $plugins);
|
||||
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
}
|
||||
|
||||
protected function registerModuleAutoload(): void
|
||||
@@ -64,14 +114,14 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $moduleBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $moduleBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
}
|
||||
});
|
||||
|
||||
$helpersFile = $moduleBasePath . 'Helpers/helpers.php';
|
||||
$helpersFile = $moduleBasePath.'Helpers/helpers.php';
|
||||
if (file_exists($helpersFile)) {
|
||||
require_once $helpersFile;
|
||||
}
|
||||
@@ -90,7 +140,7 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $pluginBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $pluginBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
@@ -103,7 +153,7 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('modules/sirsoft-ecommerce/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
->name('api.modules.sirsoft-ecommerce.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
@@ -115,8 +165,10 @@ abstract class PluginTestCase extends TestCase
|
||||
$webRoutesFile = base_path('plugins/sirsoft-pay_nhnkcp/src/routes/web.php');
|
||||
|
||||
if (file_exists($webRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('plugins/sirsoft-pay_nhnkcp')
|
||||
->name('plugins.sirsoft-pay_nhnkcp.')
|
||||
// 프로덕션 PluginRouteServiceProvider 와 동일한 'web.plugins.' 이름 접두사 —
|
||||
// 코어 self-gate 미들웨어가 라우트명(web.plugins.{id}.*)으로 타게팅하므로 정합 필수.
|
||||
Route::prefix('plugins/sirsoft-pay_nhnkcp')
|
||||
->name('web.plugins.sirsoft-pay_nhnkcp.')
|
||||
->middleware('web')
|
||||
->group($webRoutesFile);
|
||||
}
|
||||
@@ -124,36 +176,36 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('plugins/sirsoft-pay_nhnkcp/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/plugins/sirsoft-pay_nhnkcp')
|
||||
Route::prefix('api/plugins/sirsoft-pay_nhnkcp')
|
||||
->name('api.plugins.sirsoft-pay_nhnkcp.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
}
|
||||
}
|
||||
|
||||
protected function createAdminUser(array $permissions = []): \App\Models\User
|
||||
protected function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
$uniqueRoleIdentifier = 'admin-test-' . $user->id . '-' . time();
|
||||
$userRole = \App\Models\Role::create([
|
||||
$uniqueRoleIdentifier = 'admin-test-'.$user->id.'-'.time();
|
||||
$userRole = Role::create([
|
||||
'identifier' => $uniqueRoleIdentifier,
|
||||
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
|
||||
]);
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
$adminAccessPermission = \App\Models\Permission::firstOrCreate(
|
||||
$adminAccessPermission = Permission::firstOrCreate(
|
||||
['identifier' => 'admin.access'],
|
||||
[
|
||||
'name' => ['ko' => '관리자 접근', 'en' => 'Admin Access'],
|
||||
'type' => \App\Enums\PermissionType::Admin,
|
||||
'type' => PermissionType::Admin,
|
||||
]
|
||||
);
|
||||
$userRole->permissions()->attach($adminAccessPermission->id);
|
||||
|
||||
if (! empty($permissions)) {
|
||||
foreach ($permissions as $permissionIdentifier) {
|
||||
$permission = \App\Models\Permission::firstOrCreate(
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permissionIdentifier],
|
||||
[
|
||||
'name' => ['ko' => $permissionIdentifier, 'en' => $permissionIdentifier],
|
||||
@@ -167,10 +219,10 @@ abstract class PluginTestCase extends TestCase
|
||||
return $user;
|
||||
}
|
||||
|
||||
protected function createUser(): \App\Models\User
|
||||
protected function createUser(): User
|
||||
{
|
||||
$userRole = \App\Models\Role::where('identifier', 'user')->first();
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$userRole = Role::where('identifier', 'user')->first();
|
||||
$user = User::factory()->create();
|
||||
|
||||
if ($userRole) {
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화됩니다.
|
||||
- 주문서의 간편결제 버튼에 표시되는 브랜드 마크(네이버페이·카카오페이·삼성페이·11pay·SSG페이·L.pay 등의 색상 배지)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
|
||||
- 애플페이 간편결제 버튼이 iOS 기기(iPhone·iPad)에서만 주문서에 표시되도록 했습니다. 애플페이는 iOS에서만 결제할 수 있으므로 다른 기기에서는 버튼을 감춰 혼선을 줄입니다.
|
||||
- 가상계좌 입금통보 등 결제대행사 서버가 직접 보내는 요청의 발신 주소를 확인하는 처리를 코어의 새로운 표준 연결 방식으로 옮겼습니다. 발신 서버 확인 범위(입금통보 경로에만 적용, 브라우저 결제 콜백은 제외)는 이전과 동일합니다.
|
||||
- 위 변경을 위해 코어 최소 요구 버전을 7.0.5로 상향했습니다. 이 플러그인을 업데이트하기 전에 코어를 7.0.5 이상으로 먼저 업데이트해 주세요.
|
||||
|
||||
### Security
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# API 레퍼런스 문서 목차
|
||||
|
||||
> **소유**: 플러그인 `sirsoft-pay_nicepayments` · 이 확장의 웹 라우트는 대부분 결제대행사(나이스페이먼츠)와 브라우저가 직접 주고받는 콜백/통보 경로이며, 표준 JSON API 표면이 아니다. 아래 문서는 그중 운영·보안상 명시가 필요한 경로를 사람이 서술한 레퍼런스다.
|
||||
|
||||
| 문서 | 도메인 | 설명 |
|
||||
| --- | --- | --- |
|
||||
| [vbank.md](vbank.md) | `payment` | 가상계좌 입금통보 수신 경로와 발신 서버(IP) 확인 |
|
||||
@@ -0,0 +1,31 @@
|
||||
# Vbank / 통보 수신 API 레퍼런스
|
||||
|
||||
> **소유**: 플러그인 `sirsoft-pay_nicepayments`. 이 문서는 결제대행사(나이스페이먼츠) 서버가 직접 POST 로 보내는 통보 수신 경로를 서술한다. 브라우저가 접속하는 결제 콜백과는 접근 제어가 다르다.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 나이스페이먼츠 서버가 직접 보내는 가상계좌 입금통보를 받는 경로다
|
||||
2. 통보 수신 경로는 나이스페이먼츠 공식 발신 IP 만 허용한다 (위변조·재처리 방어)
|
||||
3. IP 화이트리스트는 코어 확장 미들웨어 self-gate 로 통보 라우트명에만 적용된다
|
||||
4. 브라우저 결제 콜백(payment.callback)에는 IP 확인이 적용되지 않는다
|
||||
5. 검사 동작·허용 범위는 라우트 파일 직접 부착 시절과 동일하다
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 통보 수신 경로
|
||||
|
||||
| 라우트명 | 메서드/URI | 용도 |
|
||||
| --- | --- | --- |
|
||||
| `web.plugins.sirsoft-pay_nicepayments.payment.vbank-notify` | `POST /plugins/sirsoft-pay_nicepayments/payment/vbank-notify` | 가상계좌 입금통보 수신 |
|
||||
|
||||
**설명**
|
||||
|
||||
위 경로는 나이스페이먼츠 서버가 구매자의 가상계좌 실입금을 가맹점에 알리기 위해 직접 POST 로 호출한다. 브라우저를 거치지 않는 서버 대 서버 통신이므로, 위변조·재처리 요청을 막기 위해 **나이스페이먼츠 공식 발신 IP 만 허용**한다.
|
||||
|
||||
이 IP 화이트리스트 검사는 코어의 확장 미들웨어 self-gate(`Plugin::getMiddleware()` 의 `targets` 로 위 통보 라우트명에만 정밀 타게팅)로 수행된다. 브라우저가 접속하는 결제 콜백(`payment.callback`)에는 적용되지 않는다 — 콜백은 정상 사용자의 브라우저에서 임의 IP 로 도달하므로 IP 로 제한하면 결제가 끊긴다. 검사 자체의 동작·허용 범위는 라우트 파일에서 직접 부착하던 이전 방식과 동일하다.
|
||||
|
||||
상세: [docs/backend/middleware.md "확장 미들웨어 선언 (self-gate)"](../../../../../docs/backend/middleware.md).
|
||||
@@ -13,7 +13,7 @@
|
||||
"ko": "나이스페이먼츠 결제 게이트웨이 (통합결제창 연동)",
|
||||
"en": "NicePayments gateway (integrated payment window)"
|
||||
},
|
||||
"g7_version": ">=7.0.0-beta.2",
|
||||
"g7_version": ">=7.0.5",
|
||||
"dependencies": {
|
||||
"modules": {
|
||||
"sirsoft-ecommerce": ">=1.0.0-beta.5"
|
||||
|
||||
@@ -178,6 +178,28 @@ class Plugin extends AbstractPlugin
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인이 등록할 HTTP 미들웨어 선언을 반환합니다.
|
||||
*
|
||||
* IP 화이트리스트(VbankNotifyIpWhitelist)는 나이스페이먼츠 서버 발신 가상계좌 통보
|
||||
* webhook 라우트에만 부착합니다. 브라우저 POST 콜백(payment.callback)은 사용자 IP 라
|
||||
* 대상에서 제외 — 결제 회귀 방지. 코어 ExtensionMiddlewareGate 가 요청 시점에 실행합니다.
|
||||
*
|
||||
* @return array<int, array{class: class-string, groups: array<int, string>, timing?: string, targets: array<int, string>}>
|
||||
*/
|
||||
public function getMiddleware(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'class' => Http\Middleware\VbankNotifyIpWhitelist::class,
|
||||
'groups' => ['web'],
|
||||
'targets' => [
|
||||
'web.plugins.sirsoft-pay_nicepayments.payment.vbank-notify',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Plugins\Sirsoft\PayNicepayments\Controllers\PaymentCallbackController;
|
||||
use Plugins\Sirsoft\PayNicepayments\Http\Middleware\VbankNotifyIpWhitelist;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@@ -16,22 +16,22 @@ use Plugins\Sirsoft\PayNicepayments\Http\Middleware\VbankNotifyIpWhitelist;
|
||||
|
|
||||
*/
|
||||
|
||||
Route::withoutMiddleware([\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class])
|
||||
Route::withoutMiddleware([ValidateCsrfToken::class])
|
||||
->group(function () {
|
||||
// 결제 승인 콜백 (나이스페이먼츠 → 브라우저 POST)
|
||||
Route::post('/payment/callback', [PaymentCallbackController::class, 'authCallback'])
|
||||
->name('payment.callback');
|
||||
|
||||
// 가상계좌 입금 통보 (나이스페이먼츠 서버 → 우리 서버 POST)
|
||||
// IP 화이트리스트 미들웨어로 NicePay 공식 발송 IP 만 허용
|
||||
// IP 화이트리스트(VbankNotifyIpWhitelist)는 코어 self-gate 로 이관 —
|
||||
// Plugin::getMiddleware() 가 payment.vbank-notify 라우트명에만 타게팅 (callback 제외).
|
||||
Route::post('/payment/vbank-notify', [PaymentCallbackController::class, 'vbankNotify'])
|
||||
->middleware(VbankNotifyIpWhitelist::class)
|
||||
->name('payment.vbank-notify');
|
||||
});
|
||||
|
||||
// SignData 생성: 비회원 결제도 결제창 진입 직전에 호출하므로 인증 미들웨어를 걸지 않는다.
|
||||
// 대신 컨트롤러에서 주문번호, 결제 전 상태, 나이스페이 결제 레코드, 청구 금액을 모두 검증한다.
|
||||
Route::withoutMiddleware([\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class])
|
||||
Route::withoutMiddleware([ValidateCsrfToken::class])
|
||||
->middleware(['throttle:30,1'])
|
||||
->group(function () {
|
||||
Route::post('/payment/sign-data', [PaymentCallbackController::class, 'signData'])
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Plugins\Sirsoft\PayNicepayments\Tests\Feature\Middleware;
|
||||
|
||||
use App\Contracts\Extension\ExtensionMiddlewareRegistryInterface;
|
||||
use App\Extension\ExtensionMiddlewareRegistry;
|
||||
use Plugins\Sirsoft\PayNicepayments\Http\Middleware\VbankNotifyIpWhitelist;
|
||||
use Plugins\Sirsoft\PayNicepayments\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* VbankNotifyIpWhitelist self-gate 타게팅 정밀도 회귀 테스트.
|
||||
*
|
||||
* IP 화이트리스트는 나이스페이먼츠 서버 발신 가상계좌 통보 webhook(payment.vbank-notify)에만
|
||||
* 부착되고, 브라우저 POST 콜백(payment.callback)에는 부착되지 않아야 한다. self 로 뭉치면
|
||||
* 콜백까지 IP 차단돼 결제 실패. 미들웨어 자체가 testing 환경에서 IP 검사를 우회하므로(403 재현 불가),
|
||||
* 게이트 매칭 여부(registry 인덱스)로 타게팅 정밀도를 직접 관측한다.
|
||||
*/
|
||||
class VbankNotifyIpWhitelistGateTest extends PluginTestCase
|
||||
{
|
||||
private function resolveWeb(string $routeName): array
|
||||
{
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
|
||||
return $this->app->make(ExtensionMiddlewareRegistryInterface::class)
|
||||
->resolveForRoute($routeName, 'x', 'web', 'after_core');
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects pay_ip_guard_matched_for_webhook_routes
|
||||
*/
|
||||
public function test_ip_guard_matched_for_vbank_notify_route(): void
|
||||
{
|
||||
$this->assertContains(
|
||||
VbankNotifyIpWhitelist::class,
|
||||
$this->resolveWeb('web.plugins.sirsoft-pay_nicepayments.payment.vbank-notify'),
|
||||
'IP 가드가 가상계좌 통보 webhook 라우트에 매칭되어야 합니다.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects pay_ip_guard_not_matched_for_browser_callback
|
||||
*/
|
||||
public function test_ip_guard_not_matched_for_browser_callback(): void
|
||||
{
|
||||
// 정밀도 회귀: 브라우저 콜백(사용자 IP)에는 IP 가드가 매칭되지 않아야 결제 회귀가 없다.
|
||||
$this->assertNotContains(
|
||||
VbankNotifyIpWhitelist::class,
|
||||
$this->resolveWeb('web.plugins.sirsoft-pay_nicepayments.payment.callback'),
|
||||
'IP 가드가 브라우저 콜백에 잘못 매칭되면 결제 콜백이 차단됩니다 (정밀도 회귀).',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,19 @@
|
||||
|
||||
namespace Plugins\Sirsoft\PayNicepayments\Tests;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\ExtensionMiddlewareRegistry;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder;
|
||||
use Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
abstract class PluginTestCase extends TestCase
|
||||
@@ -16,7 +28,7 @@ abstract class PluginTestCase extends TestCase
|
||||
|
||||
protected function seeder(): string
|
||||
{
|
||||
return \Modules\Sirsoft\Ecommerce\Database\Seeders\TestingSeeder::class;
|
||||
return TestingSeeder::class;
|
||||
}
|
||||
|
||||
protected function migrateFreshUsing(): array
|
||||
@@ -40,15 +52,53 @@ abstract class PluginTestCase extends TestCase
|
||||
$this->registerModuleAutoload();
|
||||
$this->registerPluginAutoload();
|
||||
|
||||
$this->app->register(\Modules\Sirsoft\Ecommerce\Providers\EcommerceServiceProvider::class);
|
||||
$this->app->register(EcommerceServiceProvider::class);
|
||||
|
||||
$this->registerModuleRoutes();
|
||||
$this->registerPluginRoutes();
|
||||
|
||||
// 코어 self-gate 미들웨어 실행을 위해 이 플러그인을 활성 상태로 등록한다
|
||||
// (getMiddleware() 선언이 게이트 인덱스에 수집되려면 getActivePlugins() 에 포함돼야 함).
|
||||
$this->activateSelfForMiddlewareGate('sirsoft-pay_nicepayments', \Plugins\Sirsoft\PayNicepayments\Plugin::class);
|
||||
|
||||
// SettingsServiceProvider 가 storage/app/settings/general.json 의 site_url 로
|
||||
// app.url 을 override 하면 Laravel 의 assertRedirect (APP_URL 기반) 와 mismatch.
|
||||
// 테스트 환경에서는 APP_URL 그대로 사용하도록 명시 리셋.
|
||||
\Illuminate\Support\Facades\Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
Config::set('app.url', env('APP_URL', 'http://localhost'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 플러그인을 활성 상태로 등록해 코어 self-gate 미들웨어가 실행되도록 합니다.
|
||||
*
|
||||
* 프로덕션에서는 PluginManager 가 활성 플러그인 인스턴스를 보유하고 plugins 테이블의
|
||||
* status='active' 를 캐시한다. RefreshDatabase 테스트에는 둘 다 없으므로,
|
||||
* 라우트명 self-gate 타게팅(web.plugins.{id}.*)이 동작하도록 (1) plugins active 행 삽입
|
||||
* (2) PluginManager 인스턴스 등록 후 상태 캐시·미들웨어 인덱스를 무효화한다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param class-string $pluginClass 플러그인 클래스 FQCN
|
||||
*/
|
||||
protected function activateSelfForMiddlewareGate(string $identifier, string $pluginClass): void
|
||||
{
|
||||
Plugin::query()->updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]
|
||||
);
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
|
||||
$pluginManager = $this->app->make(PluginManager::class);
|
||||
$property = new \ReflectionProperty($pluginManager, 'plugins');
|
||||
$property->setAccessible(true);
|
||||
$plugins = $property->getValue($pluginManager);
|
||||
$plugins[$identifier] = new $pluginClass;
|
||||
$property->setValue($pluginManager, $plugins);
|
||||
|
||||
ExtensionMiddlewareRegistry::flush();
|
||||
}
|
||||
|
||||
protected static function krwCurrencySnapshot(): array
|
||||
@@ -107,14 +157,14 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $moduleBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $moduleBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
}
|
||||
});
|
||||
|
||||
$helpersFile = $moduleBasePath . 'Helpers/helpers.php';
|
||||
$helpersFile = $moduleBasePath.'Helpers/helpers.php';
|
||||
if (file_exists($helpersFile)) {
|
||||
require_once $helpersFile;
|
||||
}
|
||||
@@ -133,7 +183,7 @@ abstract class PluginTestCase extends TestCase
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $pluginBasePath . str_replace('\\', '/', $relativeClass) . '.php';
|
||||
$file = $pluginBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
@@ -146,7 +196,7 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('modules/sirsoft-ecommerce/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
Route::prefix('api/modules/sirsoft-ecommerce')
|
||||
->name('api.modules.sirsoft-ecommerce.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
@@ -158,8 +208,10 @@ abstract class PluginTestCase extends TestCase
|
||||
$webRoutesFile = base_path('plugins/sirsoft-pay_nicepayments/src/routes/web.php');
|
||||
|
||||
if (file_exists($webRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('plugins/sirsoft-pay_nicepayments')
|
||||
->name('plugins.sirsoft-pay_nicepayments.')
|
||||
// 프로덕션 PluginRouteServiceProvider 와 동일한 'web.plugins.' 이름 접두사 —
|
||||
// 코어 self-gate 미들웨어가 라우트명(web.plugins.{id}.*)으로 타게팅하므로 정합 필수.
|
||||
Route::prefix('plugins/sirsoft-pay_nicepayments')
|
||||
->name('web.plugins.sirsoft-pay_nicepayments.')
|
||||
->middleware('web')
|
||||
->group($webRoutesFile);
|
||||
}
|
||||
@@ -167,36 +219,36 @@ abstract class PluginTestCase extends TestCase
|
||||
$apiRoutesFile = base_path('plugins/sirsoft-pay_nicepayments/src/routes/api.php');
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
\Illuminate\Support\Facades\Route::prefix('api/plugins/sirsoft-pay_nicepayments')
|
||||
Route::prefix('api/plugins/sirsoft-pay_nicepayments')
|
||||
->name('api.plugins.sirsoft-pay_nicepayments.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
}
|
||||
}
|
||||
|
||||
protected function createAdminUser(array $permissions = []): \App\Models\User
|
||||
protected function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
$uniqueRoleIdentifier = 'admin-test-' . $user->id . '-' . time();
|
||||
$userRole = \App\Models\Role::create([
|
||||
$uniqueRoleIdentifier = 'admin-test-'.$user->id.'-'.time();
|
||||
$userRole = Role::create([
|
||||
'identifier' => $uniqueRoleIdentifier,
|
||||
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
|
||||
]);
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
$adminAccessPermission = \App\Models\Permission::firstOrCreate(
|
||||
$adminAccessPermission = Permission::firstOrCreate(
|
||||
['identifier' => 'admin.access'],
|
||||
[
|
||||
'name' => ['ko' => '관리자 접근', 'en' => 'Admin Access'],
|
||||
'type' => \App\Enums\PermissionType::Admin,
|
||||
'type' => PermissionType::Admin,
|
||||
]
|
||||
);
|
||||
$userRole->permissions()->attach($adminAccessPermission->id);
|
||||
|
||||
if (! empty($permissions)) {
|
||||
foreach ($permissions as $permissionIdentifier) {
|
||||
$permission = \App\Models\Permission::firstOrCreate(
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permissionIdentifier],
|
||||
[
|
||||
'name' => ['ko' => $permissionIdentifier, 'en' => $permissionIdentifier],
|
||||
@@ -210,10 +262,10 @@ abstract class PluginTestCase extends TestCase
|
||||
return $user;
|
||||
}
|
||||
|
||||
protected function createUser(): \App\Models\User
|
||||
protected function createUser(): User
|
||||
{
|
||||
$userRole = \App\Models\Role::where('identifier', 'user')->first();
|
||||
$user = \App\Models\User::factory()->create();
|
||||
$userRole = Role::where('identifier', 'user')->first();
|
||||
$user = User::factory()->create();
|
||||
|
||||
if ($userRole) {
|
||||
$user->roles()->attach($userRole->id);
|
||||
|
||||
Reference in new issue
Block a user