feat(core): 리버스 프록시 신뢰 설정 지원 및 미설정 진단

TLS 가 앞단에서 종단되고 앱에는 HTTP 로 전달되는 구성에서 X-Forwarded-* 가 전부
무시되어 화면 백지·IP 왜곡·webhook 403 이 함께 발생했다. 코어에 신뢰 프록시 설정
지점이 아예 없던 것이 원인이다.

- config/trustedproxy.php 로 내장 TrustProxies 미들웨어에 값을 공급한다.
 bootstrap/app.php 는 건드리지 않는다 — withMiddleware 클로저는 .env 로드 전에
 평가되어 env 가 항상 null 이 되는 조용한 no-op 이다.
- 판정은 App\Support\TrustedProxyDiagnostic 단일 SSoT 에서 계산하고 대시보드
 알림·환경설정 고급 탭·설치 마법사·trusted-proxy:status 네 면이 소비한다.
 판정식은 "HTTPS 인식 실패" 가 아니라 "X-Forwarded-* 수신 중 AND 신뢰 프록시
 미설정" 이다 — HTTP 전용 사이트가 프록시 뒤에 있으면 화면은 정상인 채로
 나머지만 조용히 어긋나기 때문이다.
- 값 편집 UI 와 쓰기 엔드포인트는 두지 않는다(잠금 역설 + XFF 위조 경로).
- 혼합 콘텐츠 차단을 부트스트랩 폴백의 별도 사유로 가른다. 새로고침으로 낫지
 않으므로 버튼을 렌더하지 않고, 원인·조치는 콘솔로 운영자에게 보낸다.
- 대시보드 알림을 심각도로 배치한다 — warning 은 상단 배너, 그 외는 하단 카드.
 같은 알림이 두 곳에 뜨지 않으며, 여러 건은 간격을 두고 쌓인다.

공개 이슈: (@lyg-kaban 제보)
This commit is contained in:
HeuJung committed 2026-08-28 18:09:27 +09:00
1 parent 46ada4dddb
commit b6c5e1f323
55 files changed
+2861 -38

No files matched your search

@@ -0,0 +1,87 @@
<?php
namespace App\Console\Commands;
use App\Support\TrustedProxyDiagnostic;
use Illuminate\Console\Command;
/**
* 신뢰 프록시 설정 상태 점검 커맨드 (#124)
*
* 프록시 뒤에서 신뢰 프록시가 설정되지 않으면 관리자 화면 자체가 뜨지 않을 수 있다. 화면으로
* 확인할 수 없는 바로 그 상태에서 쓰는 통로가 이 커맨드다.
*
* 콘솔에는 요청이 없으므로 `isSecure()`·`ip()` 같은 **실측 항목은 판정할 수 없다.** 그 항목은
* `판정 불가` 로 구분해 표시하고, 값이 비어 있는 것과 뭉뚱그리지 않는다 — 둘을 같은 문구로
* 내보내면 운영자가 "설정이 비었다" 로 오독한다.
*
* 종료 코드: 설정이 없으면 1. 비-0 은 "커맨드 실행 실패" 가 아니라 **점검 대상 신호**다.
* 다만 프록시를 쓰지 않는 직접 노출 구성에서는 미설정이 정상이므로, 그 사실을 출력에 명시한다.
*
* @since 7.0.10
*/
class TrustedProxyStatusCommand extends Command
{
/**
* The name and signature of the console command.
*/
protected $signature = 'trusted-proxy:status';
/**
* The console command description.
*/
protected $description = '리버스 프록시 신뢰 설정(TRUSTED_PROXIES) 상태를 점검합니다';
/**
* Execute the console command.
*
* @return int 설정되어 있으면 0, 미설정이면 1
*/
public function handle(): int
{
// 콘솔에는 요청이 없다 — null 을 넘겨 실측 축을 not_applicable 로 받는다.
$diagnostic = TrustedProxyDiagnostic::forRequest(null);
$this->line('');
$this->line('<options=bold>리버스 프록시 신뢰 설정 상태</>');
$this->line('');
$this->line(' 설정 파일 : config/trustedproxy.php');
$this->line(' 환경변수 : TRUSTED_PROXIES');
if ($diagnostic['trusted_configured']) {
$this->line(' 현재 값 : '.$diagnostic['configured_proxies']);
} else {
$this->line(' 현재 값 : <comment>미설정 (아무 프록시도 신뢰하지 않음)</comment>');
}
$this->line('');
$this->line(' <options=bold>요청 기반 실측</>');
$this->line(' 수신 전달 헤더 : <comment>판정 불가 (콘솔에는 요청이 없습니다)</comment>');
$this->line(' HTTPS 인식 : <comment>판정 불가</comment>');
$this->line(' 방문자 IP : <comment>판정 불가</comment>');
$this->line('');
$this->comment(' 실측 축은 웹 요청에서만 판정됩니다 — 관리자 대시보드 알림 또는');
$this->comment(' 환경설정 > 고급 의 진단 블록에서 확인하세요.');
$this->line('');
if ($diagnostic['trusted_configured']) {
$this->info('신뢰 프록시가 설정되어 있습니다. X-Forwarded-* 헤더를 신뢰합니다.');
$this->line('');
return self::SUCCESS;
}
$this->warn('• 신뢰 프록시가 설정되어 있지 않습니다.');
$this->line('');
$this->line(' 프록시(AWS ALB, CloudFront, Cloudflare, nginx, ngrok) 뒤에서 구동 중이라면');
$this->line(' .env 에 TRUSTED_PROXIES 를 지정하세요. 미설정 시 접속 주소·방문자 IP 가');
$this->line(' 프록시 기준으로 인식되어 화면 표시·IP 기록·결제 통보 수신이 어긋납니다.');
$this->line(' 프록시를 쓰지 않는 직접 노출 구성이라면 미설정이 정상입니다.');
$this->line(' 상세: https://github.com/gnuboard/g7/blob/main/docs/backend/reverse-proxy.md');
$this->line('');
return self::FAILURE;
}
}
@@ -15,6 +15,7 @@ use App\Services\DriverConnectionTester;
use App\Services\DriverRegistryService;
use App\Services\OutboundProxyTester;
use App\Services\SettingsService;
use App\Support\TrustedProxyDiagnostic;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
@@ -150,6 +151,23 @@ class SettingsController extends AdminBaseController
}
}
/**
* 신뢰 프록시(리버스 프록시) 설정 진단 결과를 조회합니다 (#124).
*
* 읽기 전용이다 — 값 편집 엔드포인트는 두지 않는다. 이 값은 "앱이 프록시 없이 도달
* 가능한가" 라는 배포 구조 지식이 있어야 정할 수 있고, 웹에서 편집 가능해지면 관리자
* 계정 탈취가 곧 X-Forwarded-For 위조 경로가 된다. 편집은 `.env` 전용이다.
*
* 판정 대상은 관리자 브라우저의 **실제 요청**이므로 현재 요청을 그대로 쓴다.
* 입력을 받지 않는 읽기 전용 조회라 FormRequest 를 두지 않는다.
*
* @return JsonResponse 진단 결과 JSON 응답
*/
public function trustedProxy(): JsonResponse
{
return $this->success('common.success', TrustedProxyDiagnostic::forRequest(request()));
}
/**
* 시스템 캐시를 정리합니다.
*
@@ -0,0 +1,80 @@
<?php
namespace App\Listeners;
use App\Contracts\Extension\HookListenerInterface;
use App\Support\TrustedProxyDiagnostic;
/**
* 신뢰 프록시 미설정 경고 리스너 (#124)
*
* 프록시 뒤에서 신뢰 프록시가 설정되지 않은 상태는 HTTPS 종단 구성에서는 화면 백지로 즉시
* 드러나지만, HTTP 전용 사이트가 프록시 뒤에 있으면 **화면이 완전히 정상이다.** 그 상태에서도
* webhook 403 · IP 기록 왜곡 · 로그인 제한 붕괴는 그대로 발생한다. 이 알림이 그 조용한 구성을
* 덮는 유일한 통로다.
*
* 대시보드 레이아웃·컨트롤러·API 스키마는 건드리지 않는다 — 기존 `core.dashboard.alerts`
* 필터 훅에 항목을 얹기만 한다(선례: StaticPublishFailureAlertListener).
*
* @since 7.0.10
*/
class TrustedProxyAlertListener implements HookListenerInterface
{
/**
* 구독할 훅과 메서드 매핑 반환.
*
* @return array 훅 매핑 배열
*/
public static function getSubscribedHooks(): array
{
return [
'core.dashboard.alerts' => [
'method' => 'addTrustedProxyAlert',
'priority' => 15,
'type' => 'filter',
],
];
}
/**
* 훅 이벤트 처리 (기본 핸들러).
*
* @param mixed ...$args 훅에서 전달된 인수들
*/
public function handle(...$args): void
{
// 기본 핸들러는 사용하지 않음
}
/**
* 신뢰 프록시 미설정 경고를 대시보드에 추가합니다.
*
* @param array $alerts 기존 알림 배열
* @return array 알림이 추가된 배열
*/
public function addTrustedProxyAlert(array $alerts): array
{
$diagnostic = TrustedProxyDiagnostic::forRequest(request());
if ($diagnostic['status'] !== TrustedProxyDiagnostic::STATUS_WARNING) {
return $alerts;
}
$alerts[] = [
'id' => 'trusted_proxy_missing',
'type' => 'warning',
'subtype' => 'trusted_proxy_missing',
'icon' => 'exclamation-triangle',
'title' => __('settings.trusted_proxy.alert_title'),
// 원인과 조치를 함께 담는다 — 원인만 알려 주면 운영자가 어디를 고쳐야 할지 모른다.
'message' => __('settings.trusted_proxy.alert_message', [
'headers' => implode(', ', $diagnostic['forwarded_headers']),
'ip' => (string) ($diagnostic['client_ip'] ?? '-'),
]),
'time' => null,
'read' => false,
];
return $alerts;
}
}
+3
View File
@@ -13,6 +13,7 @@ use App\Http\View\Composers\TemplateComposer;
use App\Http\View\Composers\UserTemplateComposer;
use App\Listeners\ExtensionCompatibilityAlertListener;
use App\Listeners\StaticPublishFailureAlertListener;
use App\Listeners\TrustedProxyAlertListener;
use App\Notifications\NotificationChannelManager;
use App\Services\ChannelReadinessService;
use App\Services\GeoIpService;
@@ -145,12 +146,14 @@ class AppServiceProvider extends ServiceProvider
* 등록 대상:
* - `ExtensionCompatibilityAlertListener` — 코어 호환성으로 자동 비활성화/재호환된 확장
* - `StaticPublishFailureAlertListener` — 부트스트랩 리소스 정적 게시 실패 (#122)
* - `TrustedProxyAlertListener` — 프록시 헤더 수신 중 신뢰 프록시 미설정 (#124)
*/
private function registerCoreHookListeners(): void
{
$listenerClasses = [
ExtensionCompatibilityAlertListener::class,
StaticPublishFailureAlertListener::class,
TrustedProxyAlertListener::class,
];
foreach ($listenerClasses as $listenerClass) {
+146
View File
@@ -0,0 +1,146 @@
<?php
namespace App\Support;
use Illuminate\Http\Request;
/**
* 신뢰 프록시 설정 진단 (#124)
*
* 리버스 프록시 뒤에서 신뢰 프록시가 설정되지 않으면 요청 객체가 프록시를 방문자로 인식한다.
* HTTPS 종단 구성에서는 화면이 백지가 되어 곧바로 드러나지만, HTTP 전용 사이트가 프록시 뒤에
* 있는 구성(Cloudflare flexible SSL, 사내 LB)에서는 **화면이 완전히 정상 렌더된다.** 그 상태로
* webhook 403 · IP 기록 왜곡 · 로그인 제한 붕괴 · GeoIP 오판정이 계속되며, 사용자도 운영자도
* 이상을 감지할 단서가 없다. 능동 경고가 없으면 영구 미발견이다.
*
* 그래서 판정식은 "HTTPS 인식 실패" 가 아니라 다음이다:
*
* X-Forwarded-* 헤더를 수신 중 AND config('trustedproxy.proxies') 가 비어 있음
*
* 이 판정은 여기 한 곳에서만 계산하고 네 노출면(대시보드 알림 · 환경설정 고급 탭 ·
* 설치 마법사 · Artisan 커맨드)이 그것을 소비한다. 면마다 조건을 다시 쓰면 한 곳만
* 어긋나도 서로 다른 답을 내놓는다.
*
* @since 7.0.10
*/
class TrustedProxyDiagnostic
{
/** 프록시 헤더 수신 중인데 신뢰 설정이 없음 — 조치가 필요한 상태 */
public const STATUS_WARNING = 'warning';
/** 정상 — 설정이 되어 있거나, 프록시 헤더가 아예 없는 직접 노출 구성 */
public const STATUS_OK = 'ok';
/** 요청이 없는 맥락(콘솔 등) — "값 없음" 이 아니라 "판정 불가" 다 */
public const STATUS_NOT_APPLICABLE = 'not_applicable';
/**
* Laravel 내장 TrustProxies 미들웨어가 신뢰하는 전달 헤더 목록.
*
* 미들웨어는 PROTO·FOR·HOST·PORT·PREFIX·AWS_ELB 를 함께 신뢰하므로, 그중 하나라도
* 수신 중이면 앞단에 무언가가 있다는 신호다.
*
* @var array<int, string>
*/
public const FORWARDED_HEADERS = [
'X-Forwarded-For',
'X-Forwarded-Proto',
'X-Forwarded-Host',
'X-Forwarded-Port',
'X-Forwarded-Prefix',
'X-Forwarded-Aws-Elb',
'Forwarded',
];
/**
* 요청 1건에 대한 신뢰 프록시 진단 결과를 반환합니다.
*
* @param Request|null $request 진단 대상 요청 (콘솔 등 요청이 없는 맥락이면 null)
* @return array{forwarded_headers: array<int, string>, trusted_configured: bool, configured_proxies: string|null, is_secure: bool|null, client_ip: string|null, remote_addr: string|null, status: string} 진단 결과
*/
public static function forRequest(?Request $request): array
{
$configured = self::configuredProxies();
$trustedConfigured = self::isConfigured();
if ($request === null) {
return [
'forwarded_headers' => [],
'trusted_configured' => $trustedConfigured,
'configured_proxies' => $configured,
'is_secure' => null,
'client_ip' => null,
'remote_addr' => null,
'status' => self::STATUS_NOT_APPLICABLE,
];
}
$forwarded = self::forwardedHeaders($request);
return [
'forwarded_headers' => $forwarded,
'trusted_configured' => $trustedConfigured,
'configured_proxies' => $configured,
'is_secure' => $request->isSecure(),
'client_ip' => $request->ip(),
'remote_addr' => $request->server('REMOTE_ADDR'),
'status' => ($forwarded !== [] && ! $trustedConfigured)
? self::STATUS_WARNING
: self::STATUS_OK,
];
}
/**
* 요청이 수신 중인 전달 헤더의 이름 목록을 반환합니다.
*
* @param Request $request 대상 요청
* @return array<int, string> 수신 중인 헤더 이름 목록
*/
public static function forwardedHeaders(Request $request): array
{
$present = [];
foreach (self::FORWARDED_HEADERS as $header) {
if ($request->headers->has($header)) {
$present[] = $header;
}
}
return $present;
}
/**
* 신뢰 프록시가 설정되어 있는지 반환합니다.
*
* 빈 문자열은 미설정과 같게 다룬다 — `.env` 에 `TRUSTED_PROXIES=` 만 남겨 둔 상태가
* "설정됨" 으로 판정되면 경고가 조용히 사라지는데, 미들웨어는 여전히 아무것도 신뢰하지 않는다.
*
* @return bool 설정 여부
*/
public static function isConfigured(): bool
{
return self::configuredProxies() !== null;
}
/**
* 설정된 신뢰 프록시 값을 반환합니다 (미설정이면 null).
*
* @return string|null 설정값
*/
public static function configuredProxies(): ?string
{
$proxies = config('trustedproxy.proxies');
if (is_array($proxies)) {
$proxies = implode(',', $proxies);
}
if (! is_string($proxies)) {
return null;
}
$proxies = trim($proxies);
return $proxies === '' ? null : $proxies;
}
}