feat(ckeditor5,board,ecommerce,page,core,admin_basic): 미참조 에디터 업로드 이미지 정리 신설 + 업로드 고아 동종 결함 7건 전수 해소

공개 (@Tuwasduliebst 제보) 대응.

- ckeditor5: 미참조 이미지 정리 엔진 신설 — 참조 판정(hash + 파일명 2토큰,
 filter_reference_sources 훅으로 확장 콘텐츠 등록) + 정리 커맨드(기본 꺼짐 옵트인,
 3중 게이트) + 업로드 관리 화면(권한 분리·참조 배지·개별/선택 삭제) + 기설치본
 설정 백필 upgrade step
- board: 임시 첨부 GC(상시) + 소프트삭제 첨부 영구 정리(옵트인) + 설정 UI,
 저장 payload 누락(F4)·빈 temp 디렉토리 잔존(F5) 수정
- ecommerce: 임시 상품 이미지 GC + 카테고리 삭제 시 이미지 파일 미삭제(S4) 수정
- page: 임시 첨부 GC
- 코어: 고아 첨부 정리 커맨드(옵트인, site_logo 보호) + 사이트 로고 교체 시
 구 로고 재편입 차단(S6) + DB 백업 미구현 501 정직화(B3) + 플러그인 관리자
 메뉴 설치·업데이트 자동 동기화(F1·F7)
- 동반: 플러그인 설정 검증 오류 필드명 라벨화(F3), Toggle 노드 type 정정
 수평 전개(marketing 1.0.2 bump·gdpr·ecommerce), ja 언어팩 4종, API 문서,
 hooks.md, 시나리오 매니페스트 8종, Playwright E2E 4종
This commit is contained in:
HeuJung committed 2026-08-17 02:44:54 +09:00
1 parent 1d895a6428
commit cfc2caba1b
170 files changed
+11142 -209

No files matched your search

@@ -10,6 +10,7 @@ use App\Models\Attachment;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\AttachmentService;
use App\Services\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
@@ -1497,6 +1498,7 @@ class SettingsControllerTest extends TestCase
$app->make(ConfigRepositoryInterface::class),
$app->make(AttachmentRepositoryInterface::class),
$app->make(CacheInterface::class),
$app->make(AttachmentService::class),
);
}
@@ -1596,6 +1598,7 @@ class SettingsControllerTest extends TestCase
$app->make(ConfigRepositoryInterface::class),
$app->make(AttachmentRepositoryInterface::class),
$app->make(CacheInterface::class),
$app->make(AttachmentService::class),
);
$this->stub = $stub;
}
@@ -1650,6 +1653,7 @@ class SettingsControllerTest extends TestCase
$app->make(ConfigRepositoryInterface::class),
$app->make(AttachmentRepositoryInterface::class),
$app->make(CacheInterface::class),
$app->make(AttachmentService::class),
);
}
@@ -0,0 +1,154 @@
<?php
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* DB 백업 엔드포인트의 미제공 응답 검증 (공개 #115 부록 B3)
*
* `POST /api/admin/settings/backup-database` 는 존재하지 않는
* `SettingsService::backupDatabase()` 를 호출해 왔다. PHP 가 던지는 것은 `Error` 라
* 컨트롤러의 `catch (\Exception)` 에 걸리지 않고 그대로 500 이 됐다.
* 화면 버튼이 없어 운영 중에는 드러나지 않지만, 공개 API 레퍼런스에는 정상 기능으로
* 실려 있어 문서를 보고 호출한 쪽에는 무조건 서버 오류였다.
*
* 기능은 아직 없으므로 "서버가 고장났다"(500)가 아니라 "이 기능은 제공하지 않는다"(501)로
* 정직하게 답하는 것이 계약이다.
*/
class SettingsDatabaseBackupTest 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]),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => 'admin',
]
);
$permissionIds[] = $permission->id;
}
$roleIdentifier = 'admin_test_'.uniqid();
$adminRole = Role::create([
'identifier' => $roleIdentifier,
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Admin']),
'description' => json_encode(['ko' => '테스트', 'en' => 'Test']),
'is_active' => true,
]);
$adminBaseRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
$adminRole->permissions()->sync($permissionIds);
$user->roles()->attach($adminBaseRole->id, [
'assigned_at' => now(),
'assigned_by' => null,
]);
$user->roles()->attach($adminRole->id, [
'assigned_at' => now(),
'assigned_by' => null,
]);
return $user->fresh();
}
/**
* 인증된 요청 헬퍼
*/
private function authRequest(): static
{
return $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
]);
}
/**
* 미제공 기능은 500 이 아니라 501 로 응답해야 한다.
*/
#[Test]
public function database_backup_responds_with_not_implemented(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings/backup-database');
$response->assertStatus(501);
$response->assertJson(['success' => false]);
}
/**
* 응답 메시지는 다국어 키가 해석된 사람 말이어야 한다.
*
* 키 원문(`settings.database_backup_unavailable`)이 그대로 나가면 호출자는
* 무슨 상태인지 알 수 없다.
*/
#[Test]
public function not_implemented_response_carries_a_translated_message(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings/backup-database');
$message = (string) $response->json('message');
$this->assertNotSame('', $message);
$this->assertStringNotContainsString('settings.', $message);
$this->assertSame(__('settings.database_backup_unavailable'), $message);
}
/**
* 미구현 응답으로 바꾸더라도 권한 경계는 그대로여야 한다.
*
* 501 을 먼저 돌려주느라 인증·권한 검사를 건너뛰면, 권한 없는 요청에까지
* 내부 구현 상태를 알려주게 된다.
*/
#[Test]
public function guest_still_receives_unauthenticated(): void
{
$response = $this->withHeaders(['Accept' => 'application/json'])
->postJson('/api/admin/settings/backup-database');
$response->assertStatus(401);
}
}
@@ -0,0 +1,282 @@
<?php
namespace Tests\Feature\Console;
use App\Enums\AttachmentSourceType;
use App\Extension\Storage\CoreStorageDriver;
use App\Models\Attachment;
use App\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 고아 첨부 정리 커맨드 테스트
*
* 판정식이 하나라도 느슨해지면 현역 첨부가 지워진다. 네 조건(소유자 없음 / 보존기간 경과 /
* 확장 소유 아님 / 현역 아님)을 각각 회귀로 고정합니다.
*/
class PruneOrphanAttachmentsCommandTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
// 개발 환경 설정 파일에 실제 사이트 로고가 남아 있으면 그 ID 가 보호 목록에 실려
// 같은 ID 로 생성된 픽스처까지 보호된다. 보호 목록은 각 테스트가 명시적으로 정한다.
Config::set('g7_settings.core.general.site_logo', []);
}
/**
* 첨부 파일과 기록을 함께 만듭니다.
*
* @param array<string, mixed> $attributes 덮어쓸 속성
* @param int $ageDays 업로드 경과 일수
* @return Attachment 생성된 첨부
*/
private function makeAttachment(array $attributes = [], int $ageDays = 40): Attachment
{
$filename = uniqid('orphan-').'.png';
$path = "2026/08/14/{$filename}";
$disk = config('attachment.disk');
(new CoreStorageDriver($disk))->put('', $path, 'bytes');
$attachment = Attachment::create(array_merge([
'attachmentable_type' => null,
'attachmentable_id' => null,
'source_type' => AttachmentSourceType::Core,
'source_identifier' => null,
'original_filename' => $filename,
'stored_filename' => $filename,
'disk' => $disk,
'path' => $path,
'mime_type' => 'image/png',
'size' => 5,
'collection' => 'default',
'order' => 0,
], $attributes));
$attachment->forceFill(['created_at' => now()->subDays($ageDays)])->saveQuietly();
return $attachment->refresh();
}
/**
* @effects core_orphan_prune_gate_off_by_default
*/
#[Test]
public function scheduled_run_deletes_nothing_when_the_toggle_is_off(): void
{
$attachment = $this->makeAttachment();
$this->artisan('attachments:prune-orphans --scheduled')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
/**
* @effects core_orphan_prune_gate_on
*/
#[Test]
public function scheduled_run_prunes_when_the_toggle_is_on(): void
{
Config::set('g7_settings.core.upload.orphan_cleanup_enabled', true);
Config::set('g7_settings.core.upload.orphan_retention_days', 30);
$attachment = $this->makeAttachment();
$this->artisan('attachments:prune-orphans --scheduled')->assertSuccessful();
$this->assertDatabaseMissing('attachments', ['id' => $attachment->id]);
}
/**
* 소유자가 있는 첨부는 어떤 경우에도 고아가 아니다.
*
* @scenario age=past_retention, owner_state=has_owner, protected=not_protected, source_owner=core
*
* @effects core_orphan_prune_skips_owned
*/
#[Test]
public function attachment_with_an_owner_is_never_pruned(): void
{
$attachment = $this->makeAttachment([
'attachmentable_type' => 'App\\Models\\User',
'attachmentable_id' => 1,
]);
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
/**
* 확장이 소유한 첨부는 그 확장의 라이프사이클 소관이라 코어가 지우지 않는다.
*
* @scenario age=past_retention, owner_state=no_owner, protected=not_protected, source_owner=extension
*
* @effects core_orphan_prune_skips_extension_owned
*/
#[Test]
public function attachment_owned_by_an_extension_is_never_pruned(): void
{
$attachment = $this->makeAttachment([
'source_type' => AttachmentSourceType::Module,
'source_identifier' => 'sirsoft-board',
]);
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
/**
* 현역 사이트 로고는 소유자가 없어도 설정이 직접 참조하므로 보호해야 한다.
*
* @scenario age=past_retention, owner_state=no_owner, protected=current_site_logo, source_owner=core
*
* @effects core_orphan_prune_protects_site_logo
*/
#[Test]
public function the_current_site_logo_is_protected(): void
{
$logo = $this->makeAttachment(['collection' => 'site_logo']);
$orphan = $this->makeAttachment();
Config::set('g7_settings.core.general.site_logo', [$logo->id]);
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $logo->id]);
$this->assertDatabaseMissing('attachments', ['id' => $orphan->id]);
}
/**
* 로고 보호는 커맨드를 거치지 않아도 성립해야 한다 (조회의 불변식).
*
* 보호 대상을 호출자가 넘기는 값으로 두면 그 인자를 빠뜨린 호출 하나가 운영 중인 로고를
* 파기한다. 나머지 세 조건은 조회 자체의 불변식이므로 보호 조건만 규약으로 남을 수 없다.
*
* @scenario age=past_retention, owner_state=no_owner, protected=current_site_logo, source_owner=core
*
* @effects core_orphan_prune_protects_site_logo
*/
#[Test]
public function the_site_logo_is_protected_even_when_the_service_is_called_directly(): void
{
$logo = $this->makeAttachment(['collection' => 'site_logo']);
$orphan = $this->makeAttachment();
Config::set('g7_settings.core.general.site_logo', [$logo->id]);
app(AttachmentService::class)->pruneOrphans(1, 500);
$this->assertDatabaseHas('attachments', ['id' => $logo->id]);
$this->assertDatabaseMissing('attachments', ['id' => $orphan->id]);
}
/**
* 보호는 **현역** 로고에만 걸린다 — 설정에서 빠진 구 로고는 회수 대상이다.
*
* 로고 교체는 저장이 성공한 뒤에야 구 파일을 파기한다. 저장이 실패하면 파기하지 않으므로
* (설정에는 없는데 파일만 남는 상태를 막기 위한 순서다) 그렇게 남은 첨부를 거둘 마지막
* 통로가 이 GC 다. 보호 조건이 컬렉션 전체로 넓어지면 그 통로가 막혀 구 로고가 영구
* 잔존하므로, 보호 방향(현역 보존)과 반대 방향(구 로고 회수)을 함께 고정한다.
*
* @scenario age=past_retention, owner_state=no_owner, protected=not_protected, source_owner=core
*
* @effects core_orphan_prune_collects_replaced_site_logo
*/
#[Test]
public function a_replaced_site_logo_is_collected_once_it_leaves_the_setting(): void
{
$previous = $this->makeAttachment(['collection' => 'site_logo']);
$current = $this->makeAttachment(['collection' => 'site_logo']);
// 교체 후 설정에는 새 로고만 남아 있다.
Config::set('g7_settings.core.general.site_logo', [$current->id]);
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $current->id]);
$this->assertDatabaseMissing('attachments', ['id' => $previous->id]);
}
/**
* @scenario age=within_retention, owner_state=no_owner, protected=not_protected, source_owner=core
*
* @effects core_orphan_prune_keeps_within_retention
*/
#[Test]
public function attachment_within_retention_is_kept(): void
{
$attachment = $this->makeAttachment(ageDays: 3);
$this->artisan('attachments:prune-orphans --days=30')->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
/**
* @effects core_orphan_prune_dry_run
*/
#[Test]
public function dry_run_reports_targets_without_deleting(): void
{
$attachment = $this->makeAttachment();
$this->artisan('attachments:prune-orphans --days=1 --dry-run')
->expectsOutputToContain('[DRY RUN]')
->assertSuccessful();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
/**
* @scenario age=past_retention, owner_state=no_owner, protected=not_protected, source_owner=core
*
* @effects core_orphan_prune_deletes_file
*/
#[Test]
public function pruning_removes_the_physical_file_as_well(): void
{
$attachment = $this->makeAttachment();
$storage = new CoreStorageDriver($attachment->disk);
$this->assertTrue($storage->exists('', $attachment->path));
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertFalse($storage->exists('', $attachment->path));
}
/**
* 소프트삭제된 고아도 회수된다.
*
* 후보 조회는 소프트삭제 행까지 포함하므로, 삭제 경로가 기본 조회를 쓰면 대상을 찾지 못해
* 매 회차 같은 행을 실패로만 계상하고 파일·기록이 영원히 남는다.
*
* @scenario age=past_retention, owner_state=no_owner, protected=not_protected, source_owner=core
*
* @effects core_orphan_prune_deletes_soft_deleted
*/
#[Test]
public function soft_deleted_orphan_is_purged_too(): void
{
$attachment = $this->makeAttachment();
$storage = new CoreStorageDriver($attachment->disk);
$attachment->delete();
$this->assertNotNull(Attachment::withTrashed()->find($attachment->id));
$this->artisan('attachments:prune-orphans --days=1')->assertSuccessful();
$this->assertNull(Attachment::withTrashed()->find($attachment->id));
$this->assertFalse($storage->exists('', $attachment->path));
}
}
@@ -0,0 +1,189 @@
<?php
namespace Tests\Feature\Services;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Enums\AttachmentSourceType;
use App\Extension\Storage\CoreStorageDriver;
use App\Models\Attachment;
use App\Services\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 사이트 로고 교체 시 구 로고가 재편입되지 않는지 검증 (회귀)
*
* 저장할 목록은 **이번 요청이 제출한 것**이 정한다. 컬렉션 전체를 다시 수집하면 저장에
* 실패했거나 작성 중 이탈해 남은 미참조 첨부까지 설정에 되살아나, 운영자가 올린 적 없는
* 로고가 화면에 다시 나타난다(브라우저 실측 — 신규 1건만 제출했는데 저장 결과가 2건).
*/
class SettingsServiceSiteLogoTest extends TestCase
{
use RefreshDatabase;
/**
* site_logo 컬렉션 첨부를 파일과 함께 만듭니다.
*
* @return Attachment 생성된 첨부
*/
private function makeLogo(): Attachment
{
$filename = uniqid('logo-').'.png';
$path = "2026/08/14/{$filename}";
$disk = config('attachment.disk');
(new CoreStorageDriver($disk))->put('', $path, 'bytes');
return Attachment::create([
'attachmentable_type' => null,
'attachmentable_id' => null,
'source_type' => AttachmentSourceType::Core,
'source_identifier' => null,
'original_filename' => $filename,
'stored_filename' => $filename,
'disk' => $disk,
'path' => $path,
'mime_type' => 'image/png',
'size' => 5,
'collection' => 'site_logo',
'order' => 0,
]);
}
/**
* @effects site_logo_replacement_drops_previous
*/
#[Test]
public function replacing_the_logo_removes_the_previous_one_instead_of_re_collecting_it(): void
{
$service = app(SettingsService::class);
$config = app(ConfigRepositoryInterface::class);
// 1차 저장 — 첫 로고가 설정에 실린다.
$first = $this->makeLogo();
$service->saveSettings(['_tab' => 'general', 'general' => ['site_logo' => [$first->id]]]);
$this->assertSame([$first->id], $config->getCategory('general')['site_logo']);
// 2차 저장 — 운영자가 첫 로고를 빼고 새 로고를 올린 상태.
// 화면은 업로드를 끝낸 뒤 저장을 보내므로 새 로고 id 가 제출값에 실린다.
$second = $this->makeLogo();
$service->saveSettings(['_tab' => 'general', 'general' => ['site_logo' => [$second->id]]]);
$saved = $config->getCategory('general')['site_logo'];
$this->assertSame([$second->id], $saved, '설정에는 최신 로고만 남아야 한다.');
$this->assertDatabaseMissing('attachments', ['id' => $first->id]);
}
/**
* 저장에 실패했거나 이탈로 남은 미참조 첨부가 설정에 되살아나면 안 된다.
*
* @effects site_logo_unreferenced_collection_member_not_re_absorbed
*/
#[Test]
public function an_unreferenced_collection_member_is_not_re_absorbed(): void
{
$service = app(SettingsService::class);
$config = app(ConfigRepositoryInterface::class);
// 설정에 실린 적 없는 첨부 (직전 저장 실패로 남은 상태)
$orphan = $this->makeLogo();
// 운영자는 새 로고 1건만 올려 저장한다.
$fresh = $this->makeLogo();
$service->saveSettings(['_tab' => 'general', 'general' => ['site_logo' => [$fresh->id]]]);
$this->assertSame(
[$fresh->id],
$config->getCategory('general')['site_logo'],
'제출하지 않은 미참조 첨부가 설정에 편입되면 안 된다.'
);
$this->assertDatabaseHas('attachments', ['id' => $orphan->id]);
}
/**
* 제출값에 이미 삭제된 첨부 id 가 섞여 있어도 그 id 는 저장되지 않아야 한다.
*
* @effects site_logo_stale_submitted_id_filtered
*/
#[Test]
public function a_submitted_id_that_no_longer_exists_is_filtered_out(): void
{
$service = app(SettingsService::class);
$config = app(ConfigRepositoryInterface::class);
$logo = $this->makeLogo();
$service->saveSettings(['_tab' => 'general', 'general' => ['site_logo' => [$logo->id, 999999]]]);
$this->assertSame([$logo->id], $config->getCategory('general')['site_logo']);
}
/**
* site_logo 를 제출하지 않은 저장(다른 필드만 변경)은 로고를 건드리지 않아야 한다.
*
* @effects site_logo_untouched_when_not_submitted
*/
#[Test]
public function saving_other_fields_does_not_remove_the_logo(): void
{
$service = app(SettingsService::class);
$config = app(ConfigRepositoryInterface::class);
$logo = $this->makeLogo();
$service->saveSettings(['_tab' => 'general', 'general' => ['site_logo' => [$logo->id]]]);
$service->saveSettings(['_tab' => 'general', 'general' => ['site_name' => '테스트 사이트']]);
$this->assertSame([$logo->id], $config->getCategory('general')['site_logo']);
$this->assertDatabaseHas('attachments', ['id' => $logo->id]);
}
/**
* 저장이 실패하면 뺀 로고의 파일도 남아 있어야 한다 (회귀).
*
* 파기를 저장보다 먼저 하면, 저장이 실패했을 때 설정에는 구 로고 id 가 그대로 남는데
* 파일은 이미 사라져 로고가 깨진다. 파기는 저장이 확정된 뒤에만 수행해야 한다.
*
* @effects site_logo_failed_save_keeps_removed_attachment
*/
#[Test]
public function a_failed_save_does_not_destroy_the_removed_logo(): void
{
$config = app(ConfigRepositoryInterface::class);
// 로고가 저장된 상태를 만든다.
$logo = $this->makeLogo();
app(SettingsService::class)->saveSettings([
'_tab' => 'general',
'general' => ['site_logo' => [$logo->id]],
]);
$this->assertSame([$logo->id], $config->getCategory('general')['site_logo']);
// 저장 단계만 실패하도록 만든다 (조회는 실제 동작 유지).
$failing = \Mockery::mock($config);
$failing->shouldReceive('saveCategory')->andReturnFalse();
$this->app->instance(ConfigRepositoryInterface::class, $failing);
// 운영자가 로고를 빼고 저장 → 저장 실패
app(SettingsService::class)->saveSettings([
'_tab' => 'general',
'general' => ['site_logo' => []],
]);
$this->app->instance(ConfigRepositoryInterface::class, $config);
$this->assertDatabaseHas('attachments', ['id' => $logo->id]);
$this->assertTrue(
(new CoreStorageDriver($logo->disk))->exists('', $logo->path),
'저장이 실패했으면 파일도 남아 있어야 한다.'
);
$this->assertSame(
[$logo->id],
$config->getCategory('general')['site_logo'],
'저장이 실패했으므로 설정도 그대로여야 한다.'
);
}
}