feat(core): DB 최고권한 계정 차단 + OPcache 상태 안내

설치 단계와 코어 부팅의 정책이 엇갈려 있었다. 인스톨러는 root 를 자유롭게
허용하면서, 설치 후 부팅은 같은 값을 보고 확장 로딩 전체를 조용히 스킵했다.
설치는 성공하지만 이후 깨진 화면만 뜨고 원인은 로그 한 줄에만 남았다.

판정을 프레임워크 의존성 0 인 공용 SSoT 로 모아 인스톨러와 코어가 같은 답을
내게 하고, 설치 단계에서 서버 2경로로 차단하며, 설치 후 변경은 전용 에러
페이지로 드러낸다. 가드를 boot 가 아닌 미들웨어에 두어 artisan 이 죽지 않게
해 복구 수단을 남겼다. admin 은 일반 권한 운영 계정 오차단을 막기 위해 차단
목록에서 제외했다.

OPcache 는 상태 조회 경로 자체가 없어 성능 저하를 인지할 방법이 없었다.
설치 단계 경고(비차단)와 관리자 정보 탭 표시를 같은 판정 SSoT 로 추가했다.
확장 로드 여부만으로는 부족해 opcache.enable 지시자까지 확인하며, ini_get 이
차단된 환경은 "확인 불가"로 폴백해 경고도 차단도 하지 않는다.
This commit is contained in:
HeuJung committed 2026-07-20 14:17:49 +09:00
1 parent 91ec5f2d1f
commit 062a88ca04
38 files changed
+2402 -56

No files matched your search

@@ -0,0 +1,42 @@
<?php
namespace App\Http\Middleware\Concerns;
use Illuminate\Http\Request;
/**
* SetLocale 미들웨어보다 앞서 실행되는 미들웨어를 위한 로케일 자체 감지.
*
* 메인터넌스 페이지·DB 자격증명 가드처럼 인증·세션·확장 로딩 이전에 응답을
* 만들어야 하는 미들웨어는 SetLocale 이 아직 실행되지 않은 상태에서 동작한다.
* 이 트레이트가 SetLocale 의 판정 로직을 준용해 Accept-Language 를 해석한다.
*/
trait DetectsRequestLocale
{
/**
* 요청 헤더에서 로케일을 감지합니다.
*
* @param Request $request HTTP 요청
* @return string 감지된 로케일 (지원 목록에 없으면 앱 기본 로케일)
*/
protected function detectLocale(Request $request): string
{
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
$acceptLanguage = $request->header('Accept-Language');
if ($acceptLanguage) {
$languages = explode(',', $acceptLanguage);
foreach ($languages as $language) {
$lang = trim(explode(';', $language)[0]);
if (strpos($lang, '-') !== false) {
$lang = explode('-', $lang)[0];
}
if (in_array($lang, $supportedLocales)) {
return $lang;
}
}
}
return config('app.locale', 'ko');
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Http\Middleware;
use App\Http\Middleware\Concerns\DetectsRequestLocale;
use App\Support\PrivilegedDatabaseAccounts;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* DB 사용자명이 사용 불가일 때 전용 에러 페이지를 렌더링합니다.
*
* 배경: DB 사용자명이 최고권한 계정이거나 비어 있으면 CoreServiceProvider 가
* 확장(모듈·플러그인·템플릿) 로딩 전체를 스킵한다. 그 결과 템플릿 없는 깨진
* 화면만 뜨고 원인은 로그 한 줄에만 남아 운영자가 알 방법이 없었다.
* 이 미들웨어가 그 "조용한 실패" 를 드러낸다.
*
* ServiceProvider::boot() 가 아니라 미들웨어에 두는 이유: boot() 에서 abort 하면
* `php artisan` 자체가 죽어 복구 수단을 잃는다. 미들웨어는 웹 요청만 타므로
* 콘솔이 자연히 통과하고 운영자가 config:clear 등으로 복구할 수 있다.
*/
class DatabaseCredentialGuard
{
use DetectsRequestLocale;
/**
* DB 자격증명을 검사해 사용 불가 시 503 응답을 반환합니다.
*
* @param Request $request HTTP 요청
* @param Closure $next 다음 미들웨어
* @return Response HTTP 응답
*/
public function handle(Request $request, Closure $next): Response
{
// 미설치 상태는 통과 — DB 설정이 비어 있는 것이 정상이며,
// public/index.php 가 이미 /install 로 유도한다.
if (! config('app.installer_completed')) {
return $next($request);
}
$username = $this->resolveUsername();
if (PrivilegedDatabaseAccounts::isUsable($username)) {
return $next($request);
}
// SetLocale 미실행 상태이므로 로케일을 자체 감지한다.
// API/HTML 분기보다 먼저 적용해야 JSON 메시지도 활성 로케일을 반영한다.
app()->setLocale($this->detectLocale($request));
if ($request->expectsJson() || $request->is('api/*')) {
return response()->json([
'success' => false,
'message' => __('database_credential.message'),
], 503);
}
// 확장·템플릿이 로딩되지 않은 상태이므로 템플릿 뷰나 errors/layout 을
// 쓸 수 없다. DB/JS 무의존 자체 완결 정적 페이지를 반환한다.
return response()->view('database-credential-error', [
// 실제 계정명은 전달하지 않는다 — 미인증 공개 페이지이므로 정보 유출.
'reason' => PrivilegedDatabaseAccounts::isBlocked($username) ? 'blocked' : 'empty',
], 503);
}
/**
* 현재 DB 커넥션 설정에서 사용자명을 해석합니다.
*
* DB::connection() 을 거치지 않고 config 배열만 읽습니다. 이 가드는 DB 설정이
* 잘못된 상황에서 동작해야 하므로, 판정을 위해 커넥션을 해석하는 것 자체가
* 새로운 실패 지점이 됩니다. read/write 우선순위 규칙은
* PrivilegedDatabaseAccounts 가 CoreServiceProvider 와 공유합니다.
*
* @return string|null 해석된 사용자명 (없으면 null)
*/
protected function resolveUsername(): ?string
{
$connection = config('database.default');
return PrivilegedDatabaseAccounts::resolveUsername(
config("database.connections.{$connection}", [])
);
}
}
+3 -27
View File
@@ -2,6 +2,7 @@
namespace App\Http\Middleware;
use App\Http\Middleware\Concerns\DetectsRequestLocale;
use Closure;
use Illuminate\Foundation\Http\MaintenanceModeBypassCookie;
use Illuminate\Http\Request;
@@ -9,6 +10,8 @@ use Symfony\Component\HttpFoundation\Response;
class MaintenanceModePage
{
use DetectsRequestLocale;
/**
* Maintenance 모드일 때 전용 정적 페이지를 렌더링합니다.
*
@@ -76,31 +79,4 @@ class MaintenanceModePage
return MaintenanceModeBypassCookie::isValid($cookie, $data['secret']);
}
/**
* 로케일을 감지합니다. SetLocale 미들웨어의 로직을 준용합니다.
*
* @param Request $request HTTP 요청
* @return string 감지된 로케일
*/
protected function detectLocale(Request $request): string
{
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
$acceptLanguage = $request->header('Accept-Language');
if ($acceptLanguage) {
$languages = explode(',', $acceptLanguage);
foreach ($languages as $language) {
$lang = trim(explode(';', $language)[0]);
if (strpos($lang, '-') !== false) {
$lang = explode('-', $lang)[0];
}
if (in_array($lang, $supportedLocales)) {
return $lang;
}
}
}
return config('app.locale', 'ko');
}
}
+9 -18
View File
@@ -92,6 +92,7 @@ use App\Services\DriverRegistryService;
use App\Services\LayoutExtensionService;
use App\Services\TemplateLayoutAttachmentService;
use App\Services\UniqueIdService;
use App\Support\PrivilegedDatabaseAccounts;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
@@ -338,9 +339,9 @@ class CoreServiceProvider extends ServiceProvider
return;
}
// DB 연결 유효성 검증 (root 사용자 접속 방지)
// DB 연결 유효성 검증 (최고권한 계정 접속 방지)
if (! $this->isDatabaseConnectionValid()) {
Log::error('Database connection invalid: using root user or missing credentials. Skipping extension loading.');
Log::error('Database connection invalid: using a privileged database account or missing credentials. Skipping extension loading.');
return;
}
@@ -444,30 +445,20 @@ class CoreServiceProvider extends ServiceProvider
/**
* 데이터베이스 연결이 유효한지 검증합니다.
*
* root 사용자로 접속하거나 비밀번호가 없는 경우를 감지하여
* DB 최고권한 계정으로 접속하거나 사용자명이 비어 있는 경우를 감지하여
* 잘못된 설정으로 인한 접속 오류를 방지합니다.
* 계정 판정은 `PrivilegedDatabaseAccounts` 가 SSoT 입니다.
*
* @return bool 연결이 유효하면 true
*/
protected function isDatabaseConnectionValid(): bool
{
try {
$config = DB::connection()->getConfig();
// read/write 분리 설정의 우선순위 규칙까지 PrivilegedDatabaseAccounts 가 소유한다.
// 호출처마다 규칙이 달라지면 같은 설정에 서로 다른 판정이 나온다.
$username = PrivilegedDatabaseAccounts::resolveUsername(DB::connection()->getConfig());
// read/write 분리 설정인 경우 read 설정 확인
$username = $config['username'] ?? null;
// read 설정이 배열로 있는 경우
if (isset($config['read']['username'])) {
$username = $config['read']['username'];
}
// root 사용자 또는 빈 username인 경우 무효
if (empty($username) || $username === 'root') {
return false;
}
return true;
return PrivilegedDatabaseAccounts::isUsable($username);
} catch (\Throwable $e) {
Log::error('Database configuration check failed: '.$e->getMessage());
+17
View File
@@ -8,6 +8,7 @@ use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\HookManager;
use App\Http\Resources\AttachmentResource;
use App\Support\ConfigCacheHelper;
use App\Support\OpcacheStatus;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
@@ -844,6 +845,9 @@ class SettingsService
'php_memory_limit' => $this->safeSystemProbe('php_memory_limit', fn () => ini_get('memory_limit'), __('common.unknown')),
'max_execution_time' => $this->safeSystemProbe('max_execution_time', fn () => ini_get('max_execution_time').__('settings.seconds'), __('common.unknown')),
'upload_max_filesize' => $this->safeSystemProbe('upload_max_filesize', fn () => ini_get('upload_max_filesize'), __('common.unknown')),
// 판정은 App\Support\OpcacheStatus 가 SSoT — 인스톨러 요구사항 화면과 같은 답을 낸다.
// enabled 가 null 이면 "확인 불가"(ini_get 차단 환경).
'opcache' => $this->safeSystemProbe('opcache', fn () => $this->getOpcacheStatus(), ['loaded' => false, 'enabled' => null]),
'install_path' => base_path(),
'config_path' => storage_path('app/settings'),
'log_path' => storage_path('logs'),
@@ -854,6 +858,19 @@ class SettingsService
];
}
/**
* OPcache 활성화 상태를 조회합니다.
*
* 판정은 App\Support\OpcacheStatus 가 SSoT 이며, 인스톨러 요구사항 화면과
* 같은 답을 냅니다. `enabled` 가 null 이면 ini_get 이 차단된 "확인 불가" 상태입니다.
*
* @return array{loaded: bool, enabled: bool|null} OPcache 상태
*/
protected function getOpcacheStatus(): array
{
return OpcacheStatus::probe();
}
/**
* 시스템 정보 probe 를 안전하게 실행합니다.
*
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Support;
/**
* OPcache 활성화 상태 판정 (인스톨러·코어 공용 SSoT).
*
* 인스톨러(`public/install/`)는 Laravel 오토로드 없이 동작하는 순수 PHP 이므로
* 이 클래스는 파사드·헬퍼 등 프레임워크 의존성을 일절 참조하지 않는다.
* 인스톨러는 `require_once` 로 이 파일을 직접 로드해 사용한다.
*
* 확장 로드 여부만으로는 부족하다 — `Zend OPcache` 가 로드돼 있어도
* `opcache.enable=0` 이면 실제로는 동작하지 않는다.
*/
final class OpcacheStatus
{
/** OPcache PHP 확장명 */
public const EXTENSION_NAME = 'Zend OPcache';
/** OPcache 활성화 여부를 담은 php.ini 지시자 */
public const ENABLE_DIRECTIVE = 'opcache.enable';
/**
* OPcache 상태를 조회합니다.
*
* `enabled` 가 null 이면 "확인 불가" 를 뜻합니다 — `ini_get` 이
* `disable_functions` 로 차단된 환경에서 발생하며, 경고도 차단도 하지 않습니다.
*
* 두 콜백 파라미터는 테스트에서 환경을 주입하기 위한 것으로,
* 운영 코드는 인수 없이 호출합니다.
*
* @param callable|null $extensionLoaded 확장 로드 여부 판정 콜백 (기본: extension_loaded)
* @param callable|null $iniGet php.ini 지시자 조회 콜백 (기본: ini_get)
* @return array{loaded: bool, enabled: bool|null} 확장 로드 여부와 활성화 여부
*/
public static function probe(?callable $extensionLoaded = null, ?callable $iniGet = null): array
{
$extensionLoaded ??= static fn (string $name): bool => extension_loaded($name);
$iniGet ??= static fn (string $key) => ini_get($key);
if (! $extensionLoaded(self::EXTENSION_NAME)) {
return ['loaded' => false, 'enabled' => false];
}
try {
$raw = $iniGet(self::ENABLE_DIRECTIVE);
} catch (\Throwable) {
// ini_get 이 disable_functions 로 차단된 환경 — 확인 불가
return ['loaded' => true, 'enabled' => null];
}
// ini_get 은 지시자를 못 읽으면 false 를 반환한다 (값 '0' 과 구분해야 함)
if ($raw === false || $raw === null || $raw === '') {
return ['loaded' => true, 'enabled' => null];
}
return ['loaded' => true, 'enabled' => filter_var($raw, FILTER_VALIDATE_BOOLEAN)];
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Support;
/**
* DB 최고권한 계정 판정 (인스톨러·코어 공용 SSoT).
*
* 인스톨러(`public/install/`)는 Laravel 오토로드 없이 동작하는 순수 PHP 이므로
* 이 클래스는 파사드·헬퍼 등 프레임워크 의존성을 일절 참조하지 않는다.
* 인스톨러는 `require_once` 로 이 파일을 직접 로드해 사용한다.
*/
final class PrivilegedDatabaseAccounts
{
/**
* 차단 대상 DB 최고권한 계정명 (소문자 기준).
*
* `admin` 은 의도적으로 제외한다 — 일반 권한으로 운영 중인 `admin` 계정
* 사용자가 업그레이드 후 오차단되는 것을 막기 위함이다.
*/
public const BLOCKED = [
'root', // MySQL / MariaDB
'postgres', // PostgreSQL
'sa', // SQL Server
'sys', // Oracle
'system', // Oracle
];
/**
* 최고권한 계정명인지 판정합니다.
*
* 대소문자와 앞뒤 공백을 무시해 `ROOT`, ` root ` 같은 우회를 차단합니다.
*
* @param string|null $username 검사할 DB 사용자명
* @return bool 최고권한 계정이면 true
*/
public static function isBlocked(?string $username): bool
{
if ($username === null) {
return false;
}
return in_array(self::normalize($username), self::BLOCKED, true);
}
/**
* G7 이 사용할 수 있는 DB 사용자명인지 판정합니다.
*
* 빈 값(설정 누락)과 최고권한 계정을 모두 사용 불가로 봅니다.
*
* @param string|null $username 검사할 DB 사용자명
* @return bool 사용 가능하면 true
*/
public static function isUsable(?string $username): bool
{
if ($username === null || self::normalize($username) === '') {
return false;
}
return ! self::isBlocked($username);
}
/**
* DB 커넥션 설정에서 실제 사용되는 사용자명을 해석합니다.
*
* read/write 분리 설정인 경우 read 사용자명을 우선합니다. 이 우선순위 규칙이
* 호출처마다 달라지면 같은 설정을 두고 서로 다른 판정이 나오므로 여기서만 정의합니다.
*
* @param array $config DB 커넥션 설정 배열
* @return string|null 해석된 사용자명 (없으면 null)
*/
public static function resolveUsername(array $config): ?string
{
if (isset($config['read']['username'])) {
return $config['read']['username'];
}
return $config['username'] ?? null;
}
/**
* 비교용으로 사용자명을 정규화합니다.
*
* @param string $username 원본 사용자명
* @return string 소문자·트림된 사용자명
*/
private static function normalize(string $username): string
{
return strtolower(trim($username));
}
}