fix(core,admin_basic): S3 스토리지 드라이버 실동작 결함 수정 및 S3 호환 스토리지 연결 지원

공개 제보 — 파일 스토리지에서 S3 를 선택해 저장해도 실제 파일 저장이
동작하지 않던 결함의 전면 수정.

- S3 어댑터(league/flysystem-aws-s3-v3)·predis 를 코어 기본 의존성으로 포함
 — 어댑터 부재 즉사, phpredis 확장 없는 서버의 redis 선택 전면 다운 차단
 (부트 시 확장 부재 감지 → predis 자동 폴백)
- storage_driver=s3 저장 시 코어 첨부 업로드 디스크를 s3 로 전환
 (ATTACHMENT_DISK env 명시가 항상 우선, 기존 행은 저장 당시 disk 로 서빙)
- 첨부·템플릿 레이아웃 첨부 서빙을 행 disk 를 따르는 스토리지 스트림으로 교체
 — 로컬 절대 경로 전제 fileResponse 는 S3 행에서 filemtime stat 500
 (streamedFileResponse: 행 메타 기반 ETag/304/Cache-Control)
- S3 호환 스토리지(R2/MinIO/NCP) 연결 지원: 엔드포인트 URL·path-style 설정
 신설, 리전 목록 선택 → 자유 입력 전환, 연결 테스트를 실제 저장 경로와
 동일 설정(endpoint/path-style)으로 정렬
- 사용 불능 드라이버(어댑터·PHP 확장 부재)의 저장/테스트 요청을 사유와 함께
 422 로 차단하는 서버 게이트 신설 (DriverRegistryService 능력 판정)
- 웹소켓 연결 테스트에 서버(백엔드 발송용) endpoint 검사 추가 — 클라이언트만
 검사해 테스트 성공 + 실제 발송 실패가 가능하던 비대칭 해소
- env 빈 값(`KEY=`) 함정 정규화: AWS_URL/AWS_ENDPOINT/ATTACHMENT_DISK 빈 문자열을
 미설정으로 취급 (config 정규화 + 예시 파일 주석 처리)
- 플러그인 드라이버 폴백의 log 카테고리 죽은 키(logging.default) 정정 및
 websocket 유령 설정 키 제거
- 실 AWS S3 종단 검증 완료 (설정 저장 → 업로드 S3 실저장 → 서빙 200/304)
This commit is contained in:
HeuJung committed 2026-08-13 15:15:19 +09:00
1 parent c128a6ea3a
commit ea58c606a2
56 files changed
+2899 -243

No files matched your search

@@ -0,0 +1,376 @@
<?php
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\DriverRegistryService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* 드라이버 탭 S3 검증 테스트 (공개 #99 / 내부 #563, A4·A7)
*
* s3_region 형식 검증 완화(리전 하드코딩 제거), s3_endpoint/s3_use_path_style
* 신규 키 검증, 드라이버 가용성 서버 게이트를 검증합니다.
*/
class SettingsControllerS3ValidationTest extends TestCase
{
use RefreshDatabase;
private User $admin;
private string $token;
protected function setUp(): void
{
parent::setUp();
$this->admin = $this->createAdminUser();
$this->token = $this->admin->createToken('test-token')->plainTextToken;
}
/**
* 설정 권한을 가진 관리자 사용자를 생성합니다.
*/
private function createAdminUser(): User
{
$user = User::factory()->create([
'password' => Hash::make('password123'),
]);
$permissionIds = [];
foreach (['core.settings.read', 'core.settings.update'] as $permIdentifier) {
$permission = Permission::firstOrCreate(
['identifier' => $permIdentifier],
[
'name' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => 'admin',
]
);
$permissionIds[] = $permission->id;
}
$adminRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'description' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'is_active' => true,
]
);
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
$user->roles()->attach($adminRole->id);
return $user;
}
/**
* 인증 헤더를 부착한 요청 헬퍼입니다.
*/
private function authRequest(): static
{
return $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
]);
}
/**
* drivers 탭 저장의 기본 payload 를 반환합니다.
*
* @param array $overrides drivers 오버라이드 값
* @return array 요청 payload
*/
private function driversPayload(array $overrides = []): array
{
return [
'_tab' => 'drivers',
'drivers' => array_merge([
'storage_driver' => 'local',
'cache_driver' => 'file',
'session_driver' => 'file',
'queue_driver' => 'database',
'log_driver' => 'daily',
'log_level' => 'error',
'websocket_enabled' => false,
], $overrides),
];
}
/**
* 리전 형식 검증 — 유효한 값(구 화이트리스트·신규 AWS 리전·R2 auto·MinIO 커스텀)은
* 저장이 허용되어야 합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects s3_disk_resolves
*/
#[DataProvider('validRegionProvider')]
public function test_store_accepts_valid_region_shapes(string $region): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => $region,
's3_access_key' => 'key',
's3_secret_key' => 'secret',
]));
$response->assertStatus(200)->assertJson(['success' => true]);
}
/**
* 유효한 리전 형식 목록 (구 하드코딩 5종 밖 값 포함 — A4 회귀 가드)
*
* @return array<string, array{string}>
*/
public static function validRegionProvider(): array
{
return [
'구 화이트리스트 값' => ['ap-northeast-2'],
'구 목록 밖 AWS 리전' => ['eu-central-1'],
'Cloudflare R2 표준값' => ['auto'],
'MinIO 관례값' => ['us-east-1'],
];
}
/**
* 리전 형식 검증 — 불량 형식은 422 로 거부되어야 합니다.
*
* @scenario region_shape=invalid_format,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects invalid_region_rejected
*/
#[DataProvider('invalidRegionProvider')]
public function test_store_rejects_invalid_region_shapes(string $region): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => $region,
's3_access_key' => 'key',
's3_secret_key' => 'secret',
]));
$response->assertStatus(422)
->assertJsonValidationErrors(['drivers.s3_region']);
}
/**
* 불량 리전 형식 목록
*
* @return array<string, array{string}>
*/
public static function invalidRegionProvider(): array
{
return [
'특수문자' => ['S3!bad'],
'대문자' => ['AP-NORTHEAST-2'],
'공백 포함' => ['ap northeast 2'],
];
}
/**
* s3_endpoint 는 URL 형식이어야 합니다 (불량 형식 422).
*
* @scenario region_shape=aws_region,endpoint=custom_url,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_store_validates_s3_endpoint_url_format(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => 'auto',
's3_access_key' => 'key',
's3_secret_key' => 'secret',
's3_endpoint' => 'not-a-url',
]));
$response->assertStatus(422)
->assertJsonValidationErrors(['drivers.s3_endpoint']);
}
/**
* s3_endpoint/s3_use_path_style 정상 값은 저장 왕복이 성립해야 합니다.
*
* @scenario region_shape=custom_minio,endpoint=path_style,driver_usability=adapter_present,attachment_disk=follow_s3
*
* @effects endpoint_injected, attachment_upload_follows_driver
*/
public function test_store_saves_s3_endpoint_and_path_style_roundtrip(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => 'us-east-1',
's3_access_key' => 'key',
's3_secret_key' => 'secret',
's3_endpoint' => 'http://127.0.0.1:9000',
's3_use_path_style' => true,
]));
$response->assertStatus(200)->assertJson(['success' => true]);
$show = $this->authRequest()->getJson('/api/admin/settings');
$show->assertStatus(200);
$drivers = $show->json('data.drivers');
$this->assertSame('http://127.0.0.1:9000', $drivers['s3_endpoint'] ?? null);
$this->assertTrue((bool) ($drivers['s3_use_path_style'] ?? false));
}
/**
* s3_use_path_style 은 boolean 이어야 합니다.
*
* @scenario region_shape=aws_region,endpoint=path_style,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_store_validates_s3_use_path_style_boolean(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => 'auto',
's3_access_key' => 'key',
's3_secret_key' => 'secret',
's3_use_path_style' => 'not-bool',
]));
$response->assertStatus(422)
->assertJsonValidationErrors(['drivers.s3_use_path_style']);
}
/**
* 드라이버 가용성 서버 게이트 — 사용 불능 드라이버 저장은 422 로 차단되어야 합니다 (A7).
*
* memcached PHP 확장 존재 여부는 환경 의존이므로, 확장이 있는 환경에서는
* isDriverUsable 단위 검증(DriverRegistryServiceUsabilityTest)이 판정 로직을 담당하고
* 이 테스트는 통과로 간주합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_absent,attachment_disk=local_default
*
* @effects unusable_driver_rejected
*/
public function test_store_rejects_unusable_driver(): void
{
if (extension_loaded('memcached')) {
$this->markTestSkipped('memcached 확장이 설치된 환경 — 사용 불능 상태를 만들 수 없어 단위 테스트가 판정을 담당');
}
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'cache_driver' => 'memcached',
'memcached_host' => '127.0.0.1',
'memcached_port' => 11211,
]));
$response->assertStatus(422)
->assertJsonValidationErrors(['drivers.cache_driver']);
}
/**
* 드라이버 가용성 게이트의 컨트롤러↔서비스 결합을 환경 무관하게 검증합니다 (A7).
*
* 위 테스트는 확장 미설치 환경에서만 실 422 를 밟으므로, 레지스트리를 컨테이너
* partialMock 으로 교체해 "사용 불능" 판정 시 저장 요청이 422 + 사유 문구로
* 차단되는 결합점을 어느 환경에서든 단언한다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_absent,attachment_disk=local_default
*
* @effects unusable_driver_rejected
*/
public function test_store_rejects_unusable_driver_via_registry_gate(): void
{
$this->partialMock(DriverRegistryService::class, function ($mock) {
$mock->shouldReceive('isDriverUsable')
->andReturnUsing(fn (string $category, string $driverId) => ! ($category === 'cache' && $driverId === 'redis'));
$mock->shouldReceive('usabilityFailureReason')
->andReturn('mocked: redis client missing');
});
$response = $this->authRequest()->postJson('/api/admin/settings', $this->driversPayload([
'cache_driver' => 'redis',
'redis_host' => '127.0.0.1',
'redis_port' => 6379,
]));
$response->assertStatus(422)
->assertJsonValidationErrors(['drivers.cache_driver']);
// 사유가 422 응답 본문까지 도달해야 운영자가 원인을 알 수 있다
$messages = $response->json('errors')['drivers.cache_driver'] ?? [];
$this->assertStringContainsString('mocked: redis client missing', implode(' ', $messages));
}
/**
* 연결 테스트 요청도 동일한 리전 완화·신규 키 규칙을 적용해야 합니다 (게이트 대칭).
*
* @scenario region_shape=auto,endpoint=custom_url,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_test_driver_request_accepts_relaxed_region_and_new_keys(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings/test-driver', [
'storage_driver' => 's3',
's3_bucket' => 'my-bucket',
's3_region' => 'auto',
's3_access_key' => 'key',
's3_secret_key' => 'secret',
's3_endpoint' => 'http://127.0.0.1:9',
's3_use_path_style' => true,
]);
// 검증 통과(422 아님) — 연결 자체는 도달 불가 endpoint 라 실패 결과가 반환된다
$response->assertStatus(200);
$this->assertFalse($response->json('data.results.s3.success'));
}
/**
* 연결 테스트 요청이 websocket server 3필드를 수용해야 합니다 (A6 요청부).
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects test_covers_server_websocket
*/
public function test_test_driver_request_accepts_websocket_server_fields(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings/test-driver', [
'websocket_enabled' => true,
'websocket_host' => 'localhost',
'websocket_port' => 65500,
'websocket_scheme' => 'http',
'websocket_server_host' => '127.0.0.1',
'websocket_server_port' => 65501,
'websocket_server_scheme' => 'http',
'websocket_app_key' => 'k',
]);
// 검증 통과 — 서버 미기동이므로 연결 실패 결과가 반환될 뿐 422 는 아니어야 한다
$response->assertStatus(200);
$this->assertFalse($response->json('data.results.websocket.success'));
}
/**
* 비인증 요청은 401 로 차단되어야 합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects unauthenticated_returns_401
*/
public function test_store_and_test_driver_return_401_without_authentication(): void
{
$this->postJson('/api/admin/settings', $this->driversPayload())->assertStatus(401);
$this->postJson('/api/admin/settings/test-driver', ['storage_driver' => 's3'])->assertStatus(401);
}
}
@@ -1373,6 +1373,42 @@ class SettingsControllerTest extends TestCase
->assertJson(['success' => true]);
}
/**
* 드라이버 탭 저장 왕복에 S3 신규 키(s3_endpoint/s3_use_path_style)가 포함되어야 합니다 (#563).
*/
public function test_store_drivers_roundtrip_includes_new_s3_keys(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings', [
'_tab' => 'drivers',
'drivers' => [
'storage_driver' => 's3',
's3_bucket' => 'roundtrip-bucket',
's3_region' => 'auto',
's3_access_key' => 'roundtrip-key',
's3_secret_key' => 'roundtrip-secret',
's3_endpoint' => 'https://roundtrip.r2.cloudflarestorage.com',
's3_use_path_style' => true,
'cache_driver' => 'file',
'session_driver' => 'file',
'queue_driver' => 'database',
'log_driver' => 'daily',
'log_level' => 'error',
'websocket_enabled' => false,
],
]);
$response->assertStatus(200)
->assertJson(['success' => true]);
$drivers = $this->authRequest()->getJson('/api/admin/settings')
->assertStatus(200)
->json('data.drivers');
$this->assertSame('auto', $drivers['s3_region'] ?? null);
$this->assertSame('https://roundtrip.r2.cloudflarestorage.com', $drivers['s3_endpoint'] ?? null);
$this->assertTrue((bool) ($drivers['s3_use_path_style'] ?? false));
}
// ========================================================================
// 시스템 정보 probe 실패 격리 테스트 — gnuboard/g7#59
// (구조/캐시/정상값은 위 systemInfo 테스트가 이미 커버. 여기서는 호스팅
@@ -0,0 +1,133 @@
<?php
namespace Tests\Feature\Api\Public;
use App\Contracts\Extension\StorageInterface;
use App\Models\Attachment;
use App\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tests\TestCase;
/**
* S3 디스크 첨부의 공개 이미지 서빙 회귀 테스트 (공개 #99 / 내부 #563)
*
* attachment.disk 가 s3 로 전환된 상태에서 이미지 인라인 서빙 분기가 로컬 절대
* 경로(filemtime/filesize)를 전제해 500 이 나던 결함의 회귀 가드.
* 실환경 재현: 실 AWS 업로드 후 GET /api/attachment/{hash} →
* "filemtime(): stat failed for \\2026/08/13/….png" 500 (2026-08-13 라이브 로그).
*
* S3 디스크의 getBasePath('') 는 로컬 stat 가능한 경로가 아니므로(어댑터 prefix
* 가 빈 문자열), 그 의미를 재현하는 StorageInterface 대역으로 원격 디스크 행을
* 만든다. Storage::fake('s3') 는 로컬 디스크라 이 결함을 재현하지 못한다.
*/
class AttachmentS3DiskServingTest extends TestCase
{
use RefreshDatabase;
/**
* 원격(S3) 디스크 의미를 재현하는 스토리지 대역을 컨텍스트 바인딩합니다.
*
* @param string $content 스트림으로 서빙될 바이트
*/
private function bindRemoteDiskStorage(string $content = 'png-bytes'): void
{
$storage = Mockery::mock(StorageInterface::class);
$storage->shouldReceive('withDisk')->andReturnSelf();
$storage->shouldReceive('exists')->andReturn(true);
// S3 어댑터의 path('') 의미 재현 — 로컬 stat 불가능한 값 (라이브 로그의 '\2026/…' 원인)
$storage->shouldReceive('getBasePath')->andReturn('');
$storage->shouldReceive('response')->andReturnUsing(
fn () => new StreamedResponse(
function () use ($content) {
echo $content;
},
200,
['Content-Type' => 'image/png', 'Content-Length' => (string) strlen($content)]
)
);
$this->app->when(AttachmentService::class)
->needs(StorageInterface::class)
->give(fn () => $storage);
}
/**
* s3 디스크 이미지 행을 생성합니다.
*/
private function makeS3ImageAttachment(): Attachment
{
return Attachment::factory()->create([
'disk' => 's3',
'path' => '2026/08/13/regression-guard.png',
'mime_type' => 'image/png',
]);
}
/**
* s3 디스크 이미지 첨부가 200 스트림 + 캐싱 헤더로 서빙되어야 합니다.
*
* 종전 코드는 getBasePath 로 로컬 절대 경로를 조립해 filemtime 에서 죽었다(500).
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=follow_s3
*
* @effects attachment_upload_follows_driver
*/
public function test_s3_disk_image_attachment_serves_200_with_cache_headers(): void
{
$this->bindRemoteDiskStorage();
$attachment = $this->makeS3ImageAttachment();
$response = $this->get('/api/attachment/'.$attachment->hash);
$response->assertStatus(200);
$this->assertNotEmpty($response->headers->get('ETag'));
$this->assertStringContainsString('image/png', (string) $response->headers->get('Content-Type'));
$this->assertNotEmpty((string) $response->headers->get('Cache-Control'));
}
/**
* 동일 ETag 의 If-None-Match 재요청은 304 로 응답해야 합니다 (캐싱 계약 유지).
*
* ETag 는 파일 stat 이 아닌 행 메타(디스크·경로·수정시각·크기) 기반이어야
* 원격 디스크에서도 결정적이다.
*/
public function test_s3_disk_image_attachment_etag_roundtrip_yields_304(): void
{
$this->bindRemoteDiskStorage();
$attachment = $this->makeS3ImageAttachment();
$first = $this->get('/api/attachment/'.$attachment->hash);
$first->assertStatus(200);
$etag = $first->headers->get('ETag');
$this->assertNotEmpty($etag);
$second = $this->withHeaders(['If-None-Match' => $etag])
->get('/api/attachment/'.$attachment->hash);
$second->assertStatus(304);
$this->assertSame($etag, $second->headers->get('ETag'));
}
/**
* 로컬 디스크 이미지 행의 서빙 계약(200 + ETag)이 유지되어야 합니다 (혼재 회귀 가드).
*
* 기존 행은 행 disk 로 계속 서빙된다 — s3 전환 후에도 과거 로컬 행이 깨지면 안 된다.
*/
public function test_local_disk_image_attachment_still_serves(): void
{
$this->bindRemoteDiskStorage();
$attachment = Attachment::factory()->create([
'disk' => 'attachments',
'path' => '2026/08/13/legacy-local.png',
'mime_type' => 'image/png',
]);
$response = $this->get('/api/attachment/'.$attachment->hash);
$response->assertStatus(200);
$this->assertNotEmpty($response->headers->get('ETag'));
}
}
@@ -0,0 +1,192 @@
/**
* E2E: 환경설정 > 드라이버 — S3 리전 자유입력·엔드포인트·path-style (#99/#563)
*
* 시나리오 매니페스트: tests/scenarios/s3-storage-driver.yaml (마킹은 각 테스트의
* @scenario k=v 조합 + @effects 가 담당 — 헤더 요약 마킹은 파서 형식이 아님)
*
* 배경: S3 리전이 5개 하드코딩 Select 라 Cloudflare R2(auto)·신규 AWS 리전을 입력할 수
* 없었고, S3 호환 스토리지의 API 주소(endpoint)를 넣을 자리가 없어 s3_url(공개 URL)에
* 잘못 넣는 혼란이 있었다. 리전 Input 전환 + endpoint/path-style 신설을 브라우저에서
* 확인한다.
*
* 검증:
* 1. s3 선택 시 리전이 자유 입력 Input(Select 아님)·endpoint Input·path-style Toggle 이
* 번역문과 함께 마운트된다
* 2. 불량 형식 리전은 저장 버튼 클릭이 422 로 거부되고 리전 필드에 inline 에러가
* 표시된다 (s3 저장 게이트가 요구하는 연결 테스트만 route 스텁으로 성공 처리 —
* 외부 S3 실연결이 E2E 환경에 없기 때문이며, 저장 요청·에러 렌더는 전부 실경로)
* 3. local 드라이버 저장 왕복(외부 연결 불요 경로)이 신규 키를 보존한다
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
/** 관리자 환경설정 드라이버 탭 진입 + s3 선택 */
async function gotoDriversTabWithS3(page: import('@playwright/test').Page): Promise<void> {
await page.goto('/admin/settings?tab=drivers');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
// 템플릿 Select 는 options 모드에서 네이티브 select 가 아니라
// 커스텀 드롭다운(button[aria-haspopup=listbox] + role=option)을 렌더한다.
const storageSelect = page.locator('[name="drivers.storage_driver"]').first();
await expect(storageSelect).toBeAttached({ timeout: 20_000 });
await storageSelect.locator('button[aria-haspopup="listbox"]').first().click();
await page.getByRole('option', { name: 'Amazon S3' }).click();
await expect(page.locator('#s3_settings')).toBeAttached({ timeout: 10_000 });
}
// @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
// @effects region_free_input_mounted
test('@smoke #99 - s3 선택 시 리전이 자유 입력 Input 으로 마운트된다 (Select 아님)', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoDriversTabWithS3(page);
expect(page.url()).not.toMatch(/\/admin\/login/);
// 존재 확정: 리전 필드는 자유 입력 input 이다 (종전에는 커스텀 드롭다운이라 input 자체가 없었다)
const regionInput = page.locator('input[name="drivers.s3_region"]').first();
await expect(regionInput).toBeAttached();
// 부재 단언: 종전 리전 드롭다운(커스텀 Select 루트)이 제거되었다
await expect(page.locator('[name="drivers.s3_region"] button[aria-haspopup="listbox"]')).toHaveCount(0);
// 자유 입력이 실제로 동작한다 (R2 표준값)
await regionInput.fill('auto');
await expect(regionInput).toHaveValue('auto');
});
// @scenario region_shape=custom_minio,endpoint=path_style,driver_usability=adapter_present,attachment_disk=local_default
// @effects endpoint_field_mounted, path_style_toggle_mounted
test('#99 - endpoint Input 과 path-style Toggle 이 번역문과 함께 마운트된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoDriversTabWithS3(page);
const endpointField = page.locator('#s3_endpoint_field');
await expect(endpointField).toBeAttached();
await expect(endpointField.locator('input[name="drivers.s3_endpoint"]')).toBeAttached();
const toggleField = page.locator('#s3_use_path_style_field');
await expect(toggleField).toBeAttached();
await expect(toggleField.locator('input[type="checkbox"]').first()).toBeAttached();
// 다국어 키 미해석 회귀 가드 — s3 블록 전체에 "$t:" 원문이 노출되면 안 된다
const blockText = (await page.locator('#s3_settings').innerText()).trim();
expect(blockText).not.toContain('$t:');
expect(blockText.length).toBeGreaterThan(0);
});
// @scenario region_shape=invalid_format,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
// @effects invalid_region_rejected
test('#99 - 불량 형식 리전은 저장 클릭이 422 로 거부되고 리전 필드에 오류가 표시된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
// s3 저장 게이트는 연결 테스트 성공을 요구한다. 외부 S3 실연결이 E2E 환경에
// 없으므로 연결 테스트 응답만 성공으로 스텁한다 — 저장 요청 자체는 실서버로
// 나가 422 계약과 inline 에러 렌더를 실경로로 검증한다.
await page.route('**/api/admin/settings/test-driver', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
data: { results: { s3: { success: true, message: 'stubbed' } } },
}),
})
);
await gotoDriversTabWithS3(page);
// s3 필드 입력 — 불량 형식 리전 포함 (대문자·특수문자)
await page.locator('input[name="drivers.s3_bucket"]').fill('bucket');
await page.locator('input[name="drivers.s3_region"]').fill('S3!bad');
await page.locator('input[name="drivers.s3_access_key"]').fill('key');
await page.locator('input[name="drivers.s3_secret_key"]').fill('secret');
// 연결 테스트(스텁 성공) → 저장 게이트 해제 → 저장 버튼 활성 전이
await page.locator('#s3_test_section button').click();
const saveButton = page.locator('#save_button');
await expect(saveButton).toBeEnabled({ timeout: 10_000 });
// 저장 클릭 → 실서버 422
const [saveResponse] = await Promise.all([
page.waitForResponse(
(r) =>
r.request().method() === 'POST' &&
r.url().includes('/api/admin/settings') &&
!r.url().includes('test-driver')
),
saveButton.click(),
]);
expect(saveResponse.status()).toBe(422);
// 서버가 돌려준 리전 오류 문구가 리전 필드 inline 에러로 렌더된다
const body = await saveResponse.json();
const regionMessage = body?.errors?.['drivers.s3_region']?.[0];
expect(regionMessage).toBeTruthy();
await expect(page.locator('input[name="drivers.s3_region"]')).toHaveClass(/input-error/);
await expect(page.locator('#s3_settings')).toContainText(regionMessage);
});
// @scenario region_shape=auto,endpoint=custom_url,driver_usability=adapter_present,attachment_disk=local_default
// @effects local_roundtrip_preserves_new_keys
test('#99 - local 드라이버 저장 왕복이 신규 키(s3_endpoint/path-style)를 보존한다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await page.goto('/admin/settings?tab=drivers');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const result = await page.evaluate(async (bearer) => {
const headers = {
Authorization: `Bearer ${bearer}`,
Accept: 'application/json',
'Content-Type': 'application/json',
};
// 현재 값을 읽어 그대로 되돌려 놓는 왕복 — 검수 서버 상태를 바꾸지 않는다
const before = await (
await fetch('/api/admin/settings', { headers })
).json();
const drivers = before?.data?.drivers ?? {};
const save = await fetch('/api/admin/settings', {
method: 'POST',
headers,
body: JSON.stringify({
_tab: 'drivers',
drivers: {
...drivers,
storage_driver: 'local',
s3_region: 'auto',
s3_endpoint: 'http://127.0.0.1:9000',
s3_use_path_style: true,
},
}),
});
const after = await (
await fetch('/api/admin/settings', { headers })
).json();
// 원상 복구 (검수 서버 상태 보존)
await fetch('/api/admin/settings', {
method: 'POST',
headers,
body: JSON.stringify({ _tab: 'drivers', drivers }),
});
return {
saveStatus: save.status,
savedEndpoint: after?.data?.drivers?.s3_endpoint,
savedPathStyle: after?.data?.drivers?.s3_use_path_style,
savedRegion: after?.data?.drivers?.s3_region,
};
}, token);
expect(result.saveStatus).toBe(200);
expect(result.savedRegion).toBe('auto');
expect(result.savedEndpoint).toBe('http://127.0.0.1:9000');
expect(Boolean(result.savedPathStyle)).toBe(true);
});
@@ -0,0 +1,277 @@
<?php
namespace Tests\Unit\Providers;
use App\Providers\SettingsServiceProvider;
use App\Repositories\JsonConfigRepository;
use Illuminate\Support\Facades\Config;
use Mockery;
use ReflectionMethod;
use Tests\TestCase;
/**
* SettingsServiceProvider S3 설정 주입 테스트 (공개 #99 / 내부 #563)
*
* applyS3Config()의 endpoint/path-style 주입, s3_url→url 매핑,
* applyDriverConfig()의 첨부 디스크 전환(A8), 죽은 주입 제거(a2·a3) 회귀를 검증합니다.
*/
class SettingsServiceProviderS3ConfigTest extends TestCase
{
/**
* applyS3Config를 리플렉션으로 호출합니다.
*
* @param array $driverSettings drivers 카테고리 설정 데이터
*/
private function callApplyS3Config(array $driverSettings): void
{
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyS3Config');
$method->invoke($provider, $driverSettings);
}
/**
* applyDriverConfig를 리플렉션으로 호출합니다 (drivers 카테고리 mock 주입).
*
* @param array $driverSettings drivers 카테고리 설정 데이터
*/
private function callApplyDriverConfig(array $driverSettings): void
{
$repository = Mockery::mock(JsonConfigRepository::class);
$repository->shouldReceive('getCategory')->with('drivers')->andReturn($driverSettings);
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyDriverConfig');
$method->invoke($provider, $repository);
}
/**
* s3_endpoint 가 filesystems.disks.s3.endpoint 로 주입되는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=custom_url,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_s3_endpoint_injected_into_disk_config(): void
{
Config::set('filesystems.disks.s3.endpoint', null);
$this->callApplyS3Config([
's3_endpoint' => 'https://account.r2.cloudflarestorage.com',
]);
$this->assertSame(
'https://account.r2.cloudflarestorage.com',
config('filesystems.disks.s3.endpoint'),
's3_endpoint 는 SDK 요청 대상(endpoint)에 주입되어야 함 — 미주입 시 S3 호환 스토리지 연결 불가 (#99)'
);
}
/**
* s3_use_path_style 이 use_path_style_endpoint 로 주입되는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=path_style,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_s3_use_path_style_injected_into_disk_config(): void
{
Config::set('filesystems.disks.s3.use_path_style_endpoint', false);
$this->callApplyS3Config(['s3_use_path_style' => true]);
$this->assertTrue((bool) config('filesystems.disks.s3.use_path_style_endpoint'));
}
/**
* 빈 endpoint/path-style 은 주입되지 않는지 테스트합니다 (AWS 기본 경로 보존).
*/
public function test_empty_s3_endpoint_and_path_style_not_injected(): void
{
Config::set('filesystems.disks.s3.endpoint', null);
Config::set('filesystems.disks.s3.use_path_style_endpoint', false);
$this->callApplyS3Config([
's3_endpoint' => '',
's3_use_path_style' => false,
's3_bucket' => 'my-bucket',
]);
$this->assertNull(config('filesystems.disks.s3.endpoint'));
$this->assertFalse((bool) config('filesystems.disks.s3.use_path_style_endpoint'));
}
/**
* s3_url 은 public URL(url)에만 매핑되고 endpoint 에는 매핑되지 않는지 테스트합니다.
*/
public function test_s3_url_maps_to_public_url_not_endpoint(): void
{
Config::set('filesystems.disks.s3.url', null);
Config::set('filesystems.disks.s3.endpoint', null);
$this->callApplyS3Config(['s3_url' => 'https://cdn.example.com']);
$this->assertSame('https://cdn.example.com', config('filesystems.disks.s3.url'));
$this->assertNull(
config('filesystems.disks.s3.endpoint'),
's3_url 은 공개 URL base — SDK 요청 대상(endpoint)과 별개 축이어야 함'
);
}
/**
* storage_driver=s3 + ATTACHMENT_DISK 미명시 시 첨부 디스크가 s3 로 전환되는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=follow_s3
*
* @effects attachment_upload_follows_driver
*/
public function test_attachment_disk_follows_s3_when_env_not_explicit(): void
{
Config::set('attachment.disk', 'attachments');
Config::set('attachment.disk_explicit', null);
$this->callApplyDriverConfig(['storage_driver' => 's3']);
$this->assertSame('s3', config('attachment.disk'));
}
/**
* ATTACHMENT_DISK 명시 시 env 가 항상 우선하는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=env_override
*
* @effects attachment_upload_follows_driver
*/
public function test_attachment_disk_env_override_wins_over_s3(): void
{
Config::set('attachment.disk', 'custom-disk');
Config::set('attachment.disk_explicit', 'custom-disk');
$this->callApplyDriverConfig(['storage_driver' => 's3']);
$this->assertSame('custom-disk', config('attachment.disk'));
}
/**
* ATTACHMENT_DISK= 빈 값(키 존재·값 없음)은 "미명시" 로 간주되어야 합니다.
*
* `cp .env.example .env` 설치 절차에서 `ATTACHMENT_DISK=` 가 그대로 복사되면
* env() 는 기본값 대신 빈 문자열을 돌려준다 — `=== null` 판별이면 s3 전환이
* 영구 미발동하고, `attachment.disk` 도 '' 가 되어 첨부 업로드가 전면 실패한다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=follow_s3
*
* @effects attachment_upload_follows_driver
*/
public function test_attachment_disk_follows_s3_when_env_is_blank_string(): void
{
Config::set('attachment.disk', 'attachments');
Config::set('attachment.disk_explicit', '');
$this->callApplyDriverConfig(['storage_driver' => 's3']);
$this->assertSame(
's3',
config('attachment.disk'),
'ATTACHMENT_DISK= 빈 값은 미명시와 동일해야 함 — 빈 문자열을 명시로 취급하면 신규 설치에서 전환이 절대 발동하지 않는다'
);
}
/**
* storage_driver=local 이면 첨부 디스크가 기본값을 유지하는지 테스트합니다.
*/
public function test_attachment_disk_unchanged_when_storage_driver_local(): void
{
Config::set('attachment.disk', 'attachments');
Config::set('attachment.disk_explicit', null);
$this->callApplyDriverConfig(['storage_driver' => 'local']);
$this->assertSame('attachments', config('attachment.disk'));
}
/**
* A2 실효성 — REDIS_CLIENT=phpredis 활성 배포(.env.example 표준 설치) + 확장 부재
* 조합에서 predis 폴백이 발동해야 합니다.
*
* 종전 게이트(env('REDIS_CLIENT') === null)는 표준 설치에서 env 값이 'phpredis' 라
* 영구 미발동 — A2 가 막으려던 `Class "Redis" not found` 전면 다운이 그대로 남는다.
* 확장 설치 머신에서는 부재 상태를 재현할 수 없으므로(A5 선례: mock 불가 시 구성
* 검증으로 대체), 판정 술어를 확장 로드 여부 인자로 분리해 검증한다.
*/
public function test_predis_fallback_fires_for_phpredis_client_without_extension(): void
{
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'shouldFallBackToPredis');
// 표준 설치 상태: config 클라이언트 phpredis + 확장 부재 → 폴백해야 함
Config::set('database.redis.client', 'phpredis');
$this->assertTrue(
$method->invoke($provider, false),
'REDIS_CLIENT=phpredis 활성 배포 + 확장 부재 = 표준 설치 시나리오 — 폴백 미발동이면 redis 저장 시 전면 다운 (#99 A2)'
);
// 확장이 있으면 phpredis 경로 유지
$this->assertFalse($method->invoke($provider, true));
// predis 명시 설정이면 이미 동작 경로 — 개입하지 않음
Config::set('database.redis.client', 'predis');
$this->assertFalse($method->invoke($provider, false));
}
/**
* applyRedisConfig 통합 — 폴백 판정이 env() 가 아닌 config 값을 기준으로 해야 합니다.
*
* env() 직접 호출은 config:cache 환경에서 null 로 고정된다 (A8 disk_explicit 와 동형).
* 이 머신은 확장 설치 여부에 따라 결과가 갈리므로 분기 단언한다.
*/
public function test_apply_redis_config_fallback_uses_config_not_env(): void
{
Config::set('database.redis.client', 'phpredis');
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyRedisConfig');
$method->invoke($provider, []);
if (extension_loaded('redis')) {
$this->assertSame('phpredis', config('database.redis.client'), '확장이 있으면 phpredis 유지');
} else {
$this->assertSame('predis', config('database.redis.client'), '확장 부재 시 predis 폴백 (표준 설치 REDIS_CLIENT=phpredis 포함)');
}
}
/**
* upload.disk 죽은 주입 제거 회귀 — upload 카테고리의 disk 값이
* filesystems.default 를 더 이상 덮어쓰지 않아야 합니다 (a2).
*/
public function test_upload_disk_no_longer_overrides_filesystems_default(): void
{
Config::set('filesystems.default', 'local');
$repository = Mockery::mock(JsonConfigRepository::class);
$repository->shouldReceive('getCategory')->with('upload')->andReturn([
'disk' => 'rogue-disk',
'max_file_size' => 10,
]);
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyUploadConfig');
$method->invoke($provider, $repository);
$this->assertSame(
'local',
config('filesystems.default'),
'upload.disk 는 저장 rule 없는 유령 키 — filesystems.default 를 storage_driver 와 경쟁 기록하면 안 됨'
);
}
/**
* cache.driver/prefix 죽은 주입 제거 회귀 — applyCacheConfig 메서드 자체가 제거되어야 합니다 (a3).
*/
public function test_apply_cache_config_dead_injection_removed(): void
{
$this->assertFalse(
method_exists(SettingsServiceProvider::class, 'applyCacheConfig'),
'cache.driver/prefix 는 저장 경로 없는 죽은 주입 — drivers.cache_driver(cache.default SSoT)와 경쟁하므로 제거 유지'
);
}
}
@@ -0,0 +1,236 @@
<?php
namespace Tests\Unit\Services;
use App\Services\DriverConnectionTester;
use Illuminate\Support\Facades\Http;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use Tests\TestCase;
/**
* DriverConnectionTester 테스트 (공개 #99 / 내부 #563, A5·A6)
*
* testS3 의 endpoint/path-style 반영·어댑터 선검사, testWebsocket 의
* client/server 양측 endpoint probe 를 검증합니다.
*
* 한계: Http::fake 는 요청 URL 계약까지만 검증한다 (요청 본문 미검증 —
* feedback_http_fake_does_not_validate_request_body). S3 종단 검증은
* Chrome MCP MinIO 매트릭스가 담당한다.
*/
class DriverConnectionTesterTest extends TestCase
{
private DriverConnectionTester $tester;
protected function setUp(): void
{
parent::setUp();
$this->tester = new DriverConnectionTester;
}
/**
* 필수 설정 누락 시 s3_missing_config 메시지를 반환하는지 테스트합니다.
*/
public function test_s3_missing_config_returns_failure(): void
{
$result = $this->tester->testS3(['s3_bucket' => 'only-bucket']);
$this->assertFalse($result['success']);
$this->assertSame(__('settings.s3_missing_config'), $result['message']);
}
/**
* 커스텀 endpoint 가 실제 아웃바운드 대상에 반영되는지 테스트합니다.
*
* 도달 불가한 로컬 endpoint 로 시도 → 연결 실패의 error 문자열에 해당 endpoint
* 호스트가 나타나야 한다 (AWS 리전 도메인이 아니라). 이것이 endpoint 미반영
* 결함(#99 ③ — s3_url 만 있고 SDK 요청 대상은 amazonaws.com 고정)의 회귀 가드다.
*
* @scenario region_shape=custom_minio,endpoint=path_style,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_s3_custom_endpoint_reaches_outbound_target(): void
{
$result = $this->tester->testS3([
's3_bucket' => 'test-bucket',
's3_region' => 'us-east-1',
's3_access_key' => 'test-key',
's3_secret_key' => 'test-secret',
's3_endpoint' => 'http://127.0.0.1:9',
's3_use_path_style' => true,
]);
$this->assertFalse($result['success']);
$this->assertArrayHasKey('error', $result);
$this->assertStringContainsString(
'127.0.0.1',
$result['error'],
'아웃바운드가 커스텀 endpoint 를 향해야 함 — amazonaws.com 고정이면 endpoint 미반영 회귀'
);
$this->assertStringNotContainsString('amazonaws.com', $result['error']);
}
/**
* path-style 토글이 아웃바운드 주소 형태를 실제로 바꾸는지 테스트합니다.
*
* IP endpoint 는 SDK 가 path-style 을 자동 강제해 off↔on 이 구분되지 않으므로
* hostname endpoint 로 검증한다: off = virtual-hosted(버킷이 호스트에 접두) /
* on = path-style(버킷이 경로로 이동). off 상태로도 통과하던 endpoint 단언의
* 사각을 메우는 회귀 가드다.
*
* @scenario region_shape=custom_minio,endpoint=path_style,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects endpoint_injected
*/
public function test_s3_path_style_toggle_changes_outbound_address_shape(): void
{
$config = [
's3_bucket' => 'test-bucket',
's3_region' => 'us-east-1',
's3_access_key' => 'test-key',
's3_secret_key' => 'test-secret',
's3_endpoint' => 'http://s3-parity.invalid:9',
];
$virtualHosted = $this->tester->testS3($config + ['s3_use_path_style' => false]);
$pathStyle = $this->tester->testS3($config + ['s3_use_path_style' => true]);
$this->assertFalse($virtualHosted['success']);
$this->assertFalse($pathStyle['success']);
// off: 버킷명이 호스트에 접두된 virtual-hosted 주소를 향해야 한다
$this->assertStringContainsString(
'test-bucket.s3-parity.invalid',
$virtualHosted['error'],
'path-style off 는 virtual-hosted 주소여야 함'
);
// on: 버킷 접두 호스트가 사라져야 한다 — off 와 동일하면 path-style 주입 회귀
$this->assertStringNotContainsString(
'test-bucket.s3-parity.invalid',
$pathStyle['error'],
'path-style on 인데 버킷 접두 호스트가 남아 있으면 use_path_style_endpoint 미반영 회귀'
);
$this->assertStringContainsString('s3-parity.invalid', $pathStyle['error']);
}
/**
* 어댑터 선검사 계약 — 어댑터가 설치된 환경에서는 missing 분기가 발동하지 않고,
* 코드가 어댑터 존재를 검사하고 있는지(클래스 상수 참조) 검증합니다.
*
* 어댑터는 composer 필수 의존성이라 부재 상태를 만들 수 없으므로 구성 검증으로 대체한다
* (계획서 A5 — "mock 불가 시 구성 검증으로 대체").
*/
public function test_s3_adapter_precheck_present_in_code(): void
{
$this->assertTrue(
class_exists(AwsS3V3Adapter::class),
'어댑터는 코어 필수 의존성 (#99 A1)'
);
$source = file_get_contents(app_path('Services/DriverConnectionTester.php'));
$this->assertStringContainsString(
'AwsS3V3Adapter::class',
$source,
'testS3 는 어댑터 존재 선검사를 유지해야 함 — 테스트(SDK 직접)와 실경로(Flysystem)의 분리가 결함을 가리는 구조 방지 (A5)'
);
$this->assertStringContainsString('s3_adapter_missing', $source);
}
/**
* testWebsocket 이 client 와 server endpoint 를 모두 probe 하는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects test_covers_server_websocket
*/
public function test_websocket_probes_both_client_and_server_endpoints(): void
{
Http::fake([
'client.test:8443*' => Http::response('ok', 200),
'server.test:8080*' => Http::response('ok', 200),
]);
$result = $this->tester->testWebsocket([
'websocket_host' => 'client.test',
'websocket_port' => 8443,
'websocket_scheme' => 'https',
'websocket_server_host' => 'server.test',
'websocket_server_port' => 8080,
'websocket_server_scheme' => 'http',
]);
$this->assertTrue($result['success']);
Http::assertSent(fn ($request) => str_starts_with($request->url(), 'https://client.test'));
Http::assertSent(fn ($request) => str_starts_with($request->url(), 'http://server.test'));
}
/**
* server endpoint 실패 시 어느 쪽 실패인지 구분된 메시지를 반환하는지 테스트합니다.
*/
public function test_websocket_server_endpoint_failure_is_distinguished(): void
{
Http::fake([
'client.test:8443*' => Http::response('ok', 200),
'server.test:8080*' => Http::response('error', 500),
]);
$result = $this->tester->testWebsocket([
'websocket_host' => 'client.test',
'websocket_port' => 8443,
'websocket_scheme' => 'https',
'websocket_server_host' => 'server.test',
'websocket_server_port' => 8080,
'websocket_server_scheme' => 'http',
]);
$this->assertFalse($result['success']);
$this->assertSame(
__('settings.websocket_server_test_failed'),
$result['message'],
'백엔드 발송은 server endpoint 를 쓴다 — client 만 검사하면 "테스트 성공 + 실제 발송 실패" (A6)'
);
}
/**
* server 필드가 비어 있으면 client 값으로 폴백하며 중복 probe 를 생략하는지 테스트합니다.
*/
public function test_websocket_server_fields_fallback_to_client(): void
{
Http::fake([
'client.test:8443*' => Http::response('ok', 200),
]);
$result = $this->tester->testWebsocket([
'websocket_host' => 'client.test',
'websocket_port' => 8443,
'websocket_scheme' => 'https',
]);
$this->assertTrue($result['success']);
Http::assertSentCount(1);
}
/**
* client endpoint 실패 시 기존 메시지 계약이 유지되는지 테스트합니다 (하위호환).
*/
public function test_websocket_client_failure_keeps_existing_contract(): void
{
Http::fake([
'client.test:8443*' => Http::response('error', 500),
]);
$result = $this->tester->testWebsocket([
'websocket_host' => 'client.test',
'websocket_port' => 8443,
'websocket_scheme' => 'https',
'websocket_server_host' => 'server.test',
'websocket_server_port' => 8080,
'websocket_server_scheme' => 'http',
]);
$this->assertFalse($result['success']);
$this->assertSame(__('settings.websocket_test_failed'), $result['message']);
}
}
@@ -0,0 +1,132 @@
<?php
namespace Tests\Unit\Services;
use App\Services\DriverRegistryService;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use Predis\Client;
use Tests\TestCase;
/**
* DriverRegistryService 드라이버 가용성 판정 테스트 (공개 #99 / 내부 #563, A7)
*
* isDriverUsable()/usabilityFailureReason() 의 런타임 능력 판정과
* a5(CONFIG_KEYS 로그 키 정정)·a6(websocket 설정 키 제외) 회귀를 검증합니다.
*/
class DriverRegistryServiceUsabilityTest extends TestCase
{
private DriverRegistryService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = new DriverRegistryService;
}
/**
* s3 드라이버 가용성이 Flysystem 어댑터 존재와 일치하는지 테스트합니다.
*
* 어댑터는 composer require 로 코어에 포함되므로(#99 A1) 항상 true 여야 합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=local_default
*
* @effects s3_disk_resolves
*/
public function test_s3_usability_matches_adapter_presence(): void
{
$expected = class_exists(AwsS3V3Adapter::class);
$this->assertSame($expected, $this->service->isDriverUsable('storage', 's3'));
$this->assertTrue(
$expected,
'league/flysystem-aws-s3-v3 는 코어 필수 의존성 — 부재 시 S3 선택이 즉사한다 (#99 A1)'
);
$this->assertNull($this->service->usabilityFailureReason('storage', 's3'));
}
/**
* redis 드라이버 가용성이 phpredis 확장 또는 predis 존재와 일치하는지 테스트합니다.
*
* predis 는 composer require 로 코어에 포함되므로(#99 A2) 항상 true 여야 합니다.
*/
public function test_redis_usability_matches_client_presence(): void
{
$expected = extension_loaded('redis') || class_exists(Client::class);
$this->assertSame($expected, $this->service->isDriverUsable('cache', 'redis'));
$this->assertTrue(
$expected,
'predis/predis 는 코어 필수 의존성 — 확장 없는 서버에서 redis 선택 시 전면 다운 방어 (#99 A2)'
);
// predis 명시 설정 분기 — 판정은 설정 클라이언트 기준 (predis 는 코어 의존성이라 참)
config(['database.redis.client' => 'predis']);
$this->assertTrue($this->service->isDriverUsable('cache', 'redis'));
}
/**
* memcached 드라이버 가용성이 PHP 확장 존재와 일치하는지 테스트합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_absent,attachment_disk=local_default
*
* @effects unusable_driver_rejected
*/
public function test_memcached_usability_matches_extension(): void
{
$expected = extension_loaded('memcached');
$this->assertSame($expected, $this->service->isDriverUsable('cache', 'memcached'));
if (! $expected) {
$this->assertNotNull(
$this->service->usabilityFailureReason('cache', 'memcached'),
'사용 불능 드라이버는 사유 문자열을 제공해야 함 (422 메시지 파라미터)'
);
}
}
/**
* 능력 요구가 없는 드라이버(local/file 등)와 미지정 드라이버는 항상 사용 가능해야 합니다.
*/
public function test_unknown_and_capability_free_drivers_are_usable(): void
{
$this->assertTrue($this->service->isDriverUsable('storage', 'local'));
$this->assertTrue($this->service->isDriverUsable('cache', 'file'));
$this->assertTrue($this->service->isDriverUsable('queue', 'database'));
// 플러그인 등록 드라이버 — 가용성은 해당 플러그인 SP 가 보증하므로 코어는 통과
$this->assertTrue($this->service->isDriverUsable('storage', 'plugin-custom-driver'));
}
/**
* a5 회귀 — log 카테고리 Config 키가 실제 적용 키(stack.channels)와 일치해야 합니다.
*/
public function test_log_config_key_matches_actual_applied_key(): void
{
$this->assertSame(
'logging.channels.stack.channels',
$this->service->getConfigKey('log'),
'logging.default 는 어디에서도 읽지 않는 죽은 키 — applyLogConfig 실제 기록 키와 일치해야 폴백이 실효한다 (a5)'
);
}
/**
* log 카테고리의 Config 기록 값은 채널 배열 형태여야 합니다.
*/
public function test_log_config_value_is_channel_array(): void
{
$this->assertSame(['daily'], $this->service->getConfigValueForDriver('log', 'daily'));
$this->assertSame('file', $this->service->getConfigValueForDriver('cache', 'file'));
}
/**
* a6 회귀 — websocket 은 드라이버 ID 선택 설정이 없으므로 설정 키 매핑에서 제외되어야 합니다.
*/
public function test_websocket_settings_key_excluded(): void
{
$this->assertNull(
$this->service->getSettingsKey('websocket'),
"websocket 은 불리언 websocket_enabled 뿐 — 종전 'websocket_driver' 는 어떤 저장 경로에도 없는 유령 키였다 (a6)"
);
}
}
@@ -0,0 +1,124 @@
<?php
namespace Tests\Unit\Services;
use App\Contracts\Extension\StorageInterface;
use App\Contracts\Repositories\TemplateLayoutAttachmentRepositoryInterface;
use App\Contracts\Repositories\TemplateRepositoryInterface;
use App\Models\Template;
use App\Models\TemplateLayoutAttachment;
use App\Services\TemplateLayoutAttachmentService;
use Mockery;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tests\TestCase;
/**
* 템플릿 레이아웃 첨부 디스크 인지 서빙 테스트 (공개 #99 / 내부 #563)
*
* PublicAttachmentController 이미지 서빙과 동형 결함 — getServableFilePath 가
* getBasePath 로 로컬 절대 경로를 조립해 S3 디스크 행에서 fileResponse(filemtime)가
* 500 이 나던 구조의 회귀 가드. 서빙은 StorageInterface::response() 스트림으로
* 디스크 무관하게 성립해야 한다.
*/
class TemplateLayoutAttachmentServingTest extends TestCase
{
private TemplateLayoutAttachmentService $service;
private $templateRepository;
private $storage;
protected function setUp(): void
{
parent::setUp();
$repository = Mockery::mock(TemplateLayoutAttachmentRepositoryInterface::class);
$this->templateRepository = Mockery::mock(TemplateRepositoryInterface::class);
$this->storage = Mockery::mock(StorageInterface::class);
$this->service = new TemplateLayoutAttachmentService(
$repository,
$this->templateRepository,
$this->storage
);
}
/**
* 소속 템플릿 첨부를 만듭니다 (DB 미저장).
*/
private function makeAttachment(int $templateId, string $disk = 's3'): TemplateLayoutAttachment
{
$attachment = new TemplateLayoutAttachment([
'layout_name' => 'home',
'disk' => $disk,
'path' => 'sirsoft-basic/home/bg.png',
'original_name' => 'bg.png',
'mime_type' => 'image/png',
'size' => 70,
]);
$attachment->template_id = $templateId;
return $attachment;
}
/**
* s3 디스크 행이 StorageInterface::response() 스트림으로 서빙 정보를 반환해야 합니다.
*
* @scenario region_shape=aws_region,endpoint=absent,driver_usability=adapter_present,attachment_disk=follow_s3
*
* @effects attachment_upload_follows_driver
*/
public function test_s3_disk_attachment_returns_streamed_response(): void
{
$template = new Template;
$template->id = 7;
$this->templateRepository->shouldReceive('findByIdentifier')
->with('sirsoft-basic')->andReturn($template);
$stream = new StreamedResponse(function () {
echo 'bytes';
}, 200, ['Content-Type' => 'image/png']);
$this->storage->shouldReceive('withDisk')->with('s3')->andReturnSelf();
$this->storage->shouldReceive('response')->andReturn($stream);
$result = $this->service->getServableResponse('sirsoft-basic', $this->makeAttachment(7));
$this->assertNotNull($result);
$this->assertSame($stream, $result['response']);
$this->assertNotEmpty($result['etag_source']);
}
/**
* 경로 템플릿과 첨부 소속이 다르면 null 이어야 합니다 (교차 템플릿 접근 차단 유지).
*/
public function test_cross_template_access_returns_null(): void
{
$template = new Template;
$template->id = 7;
$this->templateRepository->shouldReceive('findByIdentifier')
->with('sirsoft-basic')->andReturn($template);
$result = $this->service->getServableResponse('sirsoft-basic', $this->makeAttachment(99));
$this->assertNull($result);
}
/**
* 스토리지에 파일이 없으면(response null) null 이어야 합니다.
*/
public function test_missing_file_returns_null(): void
{
$template = new Template;
$template->id = 7;
$this->templateRepository->shouldReceive('findByIdentifier')
->with('sirsoft-basic')->andReturn($template);
$this->storage->shouldReceive('withDisk')->with('s3')->andReturnSelf();
$this->storage->shouldReceive('response')->andReturnNull();
$result = $this->service->getServableResponse('sirsoft-basic', $this->makeAttachment(7));
$this->assertNull($result);
}
}
+74
View File
@@ -0,0 +1,74 @@
feature: S3 스토리지 드라이버 실동작 (공개 #99 / 내부 #563)
description: |
관리자 > 환경설정 > 드라이버의 S3 선택이 실제 파일 저장으로 이어지게 하는 결함 수정.
핵심 동작:
- league/flysystem-aws-s3-v3 / predis 코어 의존성 포함 (해석 시점 즉사 소멸)
- s3_endpoint / s3_use_path_style 신설 → filesystems.disks.s3.{endpoint,use_path_style_endpoint} 주입
(S3 호환 스토리지 R2/MinIO/NCP 연결 경로)
- s3_region 3중 하드코딩 제거 → 형식 검증(regex ^[a-z0-9-]+$, max 64) 완화
- 드라이버 가용성 서버 게이트: 어댑터 클래스/PHP 확장 부재 드라이버 저장·테스트 422
- 코어 첨부 업로드 디스크: ATTACHMENT_DISK env > storage_driver=s3 → s3 > attachments
(기존 행은 행 disk 서빙 — 혼재 안전)
- 연결 테스트: 어댑터 선검사 + endpoint/path-style 반영, websocket 은 client/server
양측 endpoint probe (백엔드 발송은 server endpoint 사용)
axes:
region_shape: [aws_region, auto, custom_minio, invalid_format]
endpoint: [absent, custom_url, path_style]
driver_usability: [adapter_present, adapter_absent]
attachment_disk: [env_override, follow_s3, local_default]
exclusions:
- { region_shape: invalid_format, endpoint: custom_url, reason: "리전 검증이 선행 422 — endpoint 축 도달 전 차단" }
- { region_shape: invalid_format, endpoint: path_style, reason: "동일" }
- { region_shape: invalid_format, attachment_disk: env_override, reason: "저장 실패 시 디스크 전환 미발생" }
- { region_shape: invalid_format, attachment_disk: follow_s3, reason: "동일" }
- { driver_usability: adapter_absent, endpoint: custom_url, reason: "가용성 게이트가 선행 422 — 어댑터는 코어 필수 의존성이라 부재 상태는 memcached 확장 축으로 대변" }
- { driver_usability: adapter_absent, endpoint: path_style, reason: "동일" }
- { driver_usability: adapter_absent, attachment_disk: follow_s3, reason: "저장 차단 시 디스크 전환 미발생" }
- { driver_usability: adapter_absent, attachment_disk: env_override, reason: "동일" }
- { driver_usability: adapter_absent, region_shape: invalid_format, reason: "리전 검증이 선행 422 — 가용성 축 도달 전 차단" }
- { driver_usability: adapter_absent, region_shape: auto, reason: "가용성 게이트는 드라이버 ID 만 판정 — 리전 값과 직교, aws_region 대표 조합으로 검증" }
- { driver_usability: adapter_absent, region_shape: custom_minio, reason: "동일" }
- { attachment_disk: env_override, region_shape: auto, reason: "디스크 전환 판정은 storage_driver 값만 본다 — 리전·endpoint 와 직교, aws_region×absent 대표 조합으로 검증" }
- { attachment_disk: env_override, region_shape: custom_minio, reason: "동일" }
- { attachment_disk: env_override, endpoint: custom_url, reason: "동일" }
- { attachment_disk: env_override, endpoint: path_style, reason: "동일" }
- { attachment_disk: follow_s3, region_shape: auto, reason: "디스크 전환 판정은 storage_driver 값만 본다 — aws_region×absent(단위)·custom_minio×path_style(Feature 왕복) 두 대표 조합으로 검증" }
- { attachment_disk: follow_s3, endpoint: custom_url, reason: "동일" }
- { attachment_disk: follow_s3, region_shape: aws_region, endpoint: path_style, reason: "동일" }
- { attachment_disk: follow_s3, region_shape: custom_minio, endpoint: absent, reason: "동일" }
- { region_shape: auto, endpoint: absent, reason: "R2 의 auto 리전은 커스텀 endpoint 전제 — endpoint 없는 auto 는 실사용 조합이 아님" }
- { region_shape: auto, endpoint: path_style, reason: "R2 는 virtual-host 스타일 — path_style 조합은 custom_minio 축이 대표" }
- { region_shape: custom_minio, endpoint: absent, reason: "MinIO 리전 값은 커스텀 endpoint 전제 — endpoint 없는 조합은 실사용이 아님" }
- { region_shape: custom_minio, endpoint: custom_url, reason: "MinIO 는 path-style 대표 조합으로 검증 — virtual-host 모드도 endpoint 주입 경로는 동일" }
effects:
- s3_disk_resolves
- endpoint_injected
- attachment_upload_follows_driver
- unusable_driver_rejected
- invalid_region_rejected
- test_covers_server_websocket
- unauthenticated_returns_401
# E2E/렌더 표면 효과 (Playwright·Vitest 가 마킹)
- region_free_input_mounted
- endpoint_field_mounted
- path_style_toggle_mounted
- local_roundtrip_preserves_new_keys
# E2E 표면 명세 (문서화) — 커버리지 집계는 아래 test_files 의 @scenario/@effects 마킹이 담당
e2e:
surfaces: [region_free_input, endpoint_field, path_style_toggle, save_gating]
test_files:
- tests/Playwright/specs/admin/settings-drivers-s3-endpoint.spec.ts
- tests/Unit/Providers/SettingsServiceProviderS3ConfigTest.php
- tests/Unit/Services/DriverConnectionTesterTest.php
- tests/Unit/Services/DriverRegistryServiceUsabilityTest.php
- tests/Feature/Api/Admin/SettingsControllerS3ValidationTest.php
- tests/Feature/Api/Public/AttachmentS3DiskServingTest.php
- tests/Unit/Services/TemplateLayoutAttachmentServingTest.php
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-settings-drivers-s3-fields.test.tsx