v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,259 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\AllowedModuleFileType;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
class AllowedModuleFileTypeTest extends TestCase
{
/**
* JavaScript 파일이 허용되는지 테스트
*/
public function test_allows_javascript_files(): void
{
$rule = new AllowedModuleFileType();
$jsFiles = ['dist/js/module.iife.js', 'app.js', 'script.mjs'];
foreach ($jsFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "File {$file} should be allowed");
}
}
/**
* CSS 파일이 허용되는지 테스트
*/
public function test_allows_css_files(): void
{
$rule = new AllowedModuleFileType();
$validator = Validator::make(
['path' => 'dist/css/module.css'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* JSON 파일이 허용되는지 테스트
*/
public function test_allows_json_files(): void
{
$rule = new AllowedModuleFileType();
$validator = Validator::make(
['path' => 'data/config.json'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* Source Map 파일이 허용되는지 테스트
*/
public function test_allows_sourcemap_files(): void
{
$rule = new AllowedModuleFileType();
$validator = Validator::make(
['path' => 'dist/js/module.iife.js.map'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 이미지 파일이 허용되는지 테스트
*/
public function test_allows_image_files(): void
{
$rule = new AllowedModuleFileType();
$imageFiles = [
'images/logo.png',
'images/photo.jpg',
'images/banner.jpeg',
'icons/arrow.svg',
'images/hero.webp',
'images/animation.gif',
'favicon.ico',
];
foreach ($imageFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "Image file {$file} should be allowed");
}
}
/**
* 폰트 파일이 허용되는지 테스트
*/
public function test_allows_font_files(): void
{
$rule = new AllowedModuleFileType();
$fontFiles = [
'fonts/roboto.woff',
'fonts/roboto.woff2',
'fonts/arial.ttf',
'fonts/custom.otf',
'fonts/legacy.eot',
];
foreach ($fontFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "Font file {$file} should be allowed");
}
}
/**
* PHP 파일이 차단되는지 테스트
*/
public function test_blocks_php_files(): void
{
$rule = new AllowedModuleFileType();
$phpFiles = ['malicious.php', 'index.phtml', 'shell.php3', 'backdoor.php4', 'exploit.php5', 'hack.phps'];
foreach ($phpFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "PHP file {$file} should be blocked");
}
}
/**
* 실행 파일이 차단되는지 테스트
*/
public function test_blocks_executable_files(): void
{
$rule = new AllowedModuleFileType();
$executableFiles = ['malware.exe', 'script.sh', 'run.bat', 'library.dll', 'module.so'];
foreach ($executableFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Executable file {$file} should be blocked");
}
}
/**
* 스크립트 파일이 차단되는지 테스트
*/
public function test_blocks_script_files(): void
{
$rule = new AllowedModuleFileType();
$scriptFiles = ['exploit.py', 'attack.rb', 'hack.pl', 'malicious.cgi'];
foreach ($scriptFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Script file {$file} should be blocked");
}
}
/**
* 서버 스크립트 파일이 차단되는지 테스트
*/
public function test_blocks_server_script_files(): void
{
$rule = new AllowedModuleFileType();
$serverScriptFiles = ['page.asp', 'app.aspx', 'index.jsp', 'api.jspx'];
foreach ($serverScriptFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Server script file {$file} should be blocked");
}
}
/**
* 설정 파일이 차단되는지 테스트
*/
public function test_blocks_config_files(): void
{
$rule = new AllowedModuleFileType();
$configFiles = ['.htaccess', '.htpasswd', '.env'];
foreach ($configFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Config file {$file} should be blocked");
}
}
/**
* 대소문자 구분 없이 차단되는지 테스트
*/
public function test_case_insensitive_blocking(): void
{
$rule = new AllowedModuleFileType();
$caseVariations = ['MALICIOUS.PHP', 'Exploit.Php', 'SCRIPT.EXE', 'attack.PY'];
foreach ($caseVariations as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Case variation {$file} should be blocked");
}
}
/**
* getAllowedExtensions() 메서드가 올바른 목록을 반환하는지 테스트
*/
public function test_get_allowed_extensions_returns_correct_list(): void
{
$extensions = AllowedModuleFileType::getAllowedExtensions();
$this->assertIsArray($extensions);
$this->assertContains('js', $extensions);
$this->assertContains('css', $extensions);
$this->assertContains('json', $extensions);
$this->assertContains('map', $extensions);
$this->assertContains('png', $extensions);
$this->assertContains('woff2', $extensions);
}
/**
* 문자열이 아닌 값 차단 테스트
*/
public function test_blocks_non_string_value(): void
{
$rule = new AllowedModuleFileType();
$validator = Validator::make(
['path' => ['array', 'value']],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
}
@@ -0,0 +1,259 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\AllowedPluginFileType;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
class AllowedPluginFileTypeTest extends TestCase
{
/**
* JavaScript 파일이 허용되는지 테스트
*/
public function test_allows_javascript_files(): void
{
$rule = new AllowedPluginFileType();
$jsFiles = ['dist/js/plugin.iife.js', 'app.js', 'script.mjs'];
foreach ($jsFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "File {$file} should be allowed");
}
}
/**
* CSS 파일이 허용되는지 테스트
*/
public function test_allows_css_files(): void
{
$rule = new AllowedPluginFileType();
$validator = Validator::make(
['path' => 'dist/css/plugin.css'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* JSON 파일이 허용되는지 테스트
*/
public function test_allows_json_files(): void
{
$rule = new AllowedPluginFileType();
$validator = Validator::make(
['path' => 'data/config.json'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* Source Map 파일이 허용되는지 테스트
*/
public function test_allows_sourcemap_files(): void
{
$rule = new AllowedPluginFileType();
$validator = Validator::make(
['path' => 'dist/js/plugin.iife.js.map'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 이미지 파일이 허용되는지 테스트
*/
public function test_allows_image_files(): void
{
$rule = new AllowedPluginFileType();
$imageFiles = [
'images/logo.png',
'images/photo.jpg',
'images/banner.jpeg',
'icons/arrow.svg',
'images/hero.webp',
'images/animation.gif',
'favicon.ico',
];
foreach ($imageFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "Image file {$file} should be allowed");
}
}
/**
* 폰트 파일이 허용되는지 테스트
*/
public function test_allows_font_files(): void
{
$rule = new AllowedPluginFileType();
$fontFiles = [
'fonts/roboto.woff',
'fonts/roboto.woff2',
'fonts/arial.ttf',
'fonts/custom.otf',
'fonts/legacy.eot',
];
foreach ($fontFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->passes(), "Font file {$file} should be allowed");
}
}
/**
* PHP 파일이 차단되는지 테스트
*/
public function test_blocks_php_files(): void
{
$rule = new AllowedPluginFileType();
$phpFiles = ['malicious.php', 'index.phtml', 'shell.php3', 'backdoor.php4', 'exploit.php5', 'hack.phps'];
foreach ($phpFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "PHP file {$file} should be blocked");
}
}
/**
* 실행 파일이 차단되는지 테스트
*/
public function test_blocks_executable_files(): void
{
$rule = new AllowedPluginFileType();
$executableFiles = ['malware.exe', 'script.sh', 'run.bat', 'library.dll', 'module.so'];
foreach ($executableFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Executable file {$file} should be blocked");
}
}
/**
* 스크립트 파일이 차단되는지 테스트
*/
public function test_blocks_script_files(): void
{
$rule = new AllowedPluginFileType();
$scriptFiles = ['exploit.py', 'attack.rb', 'hack.pl', 'malicious.cgi'];
foreach ($scriptFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Script file {$file} should be blocked");
}
}
/**
* 서버 스크립트 파일이 차단되는지 테스트
*/
public function test_blocks_server_script_files(): void
{
$rule = new AllowedPluginFileType();
$serverScriptFiles = ['page.asp', 'app.aspx', 'index.jsp', 'api.jspx'];
foreach ($serverScriptFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Server script file {$file} should be blocked");
}
}
/**
* 설정 파일이 차단되는지 테스트
*/
public function test_blocks_config_files(): void
{
$rule = new AllowedPluginFileType();
$configFiles = ['.htaccess', '.htpasswd', '.env'];
foreach ($configFiles as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Config file {$file} should be blocked");
}
}
/**
* 대소문자 구분 없이 차단되는지 테스트
*/
public function test_case_insensitive_blocking(): void
{
$rule = new AllowedPluginFileType();
$caseVariations = ['MALICIOUS.PHP', 'Exploit.Php', 'SCRIPT.EXE', 'attack.PY'];
foreach ($caseVariations as $file) {
$validator = Validator::make(
['path' => $file],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Case variation {$file} should be blocked");
}
}
/**
* getAllowedExtensions() 메서드가 올바른 목록을 반환하는지 테스트
*/
public function test_get_allowed_extensions_returns_correct_list(): void
{
$extensions = AllowedPluginFileType::getAllowedExtensions();
$this->assertIsArray($extensions);
$this->assertContains('js', $extensions);
$this->assertContains('css', $extensions);
$this->assertContains('json', $extensions);
$this->assertContains('map', $extensions);
$this->assertContains('png', $extensions);
$this->assertContains('woff2', $extensions);
}
/**
* 문자열이 아닌 값 차단 테스트
*/
public function test_blocks_non_string_value(): void
{
$rule = new AllowedPluginFileType();
$validator = Validator::make(
['path' => ['array', 'value']],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\ExcludeCurrentUser;
use Illuminate\Support\Facades\Auth;
use Tests\TestCase;
class ExcludeCurrentUserTest extends TestCase
{
private ExcludeCurrentUser $rule;
protected function setUp(): void
{
parent::setUp();
$this->rule = new ExcludeCurrentUser;
}
/**
* 로그인한 사용자가 ID 목록에 포함된 경우 검증 실패
*/
public function test_fails_when_current_user_is_in_ids(): void
{
// DB 없이 테스트 - Auth::id()만 모킹
$userId = 123;
Auth::shouldReceive('id')->andReturn($userId);
$failCalled = false;
$failMessage = '';
$this->rule->validate('ids', [$userId, 2, 3], function ($message) use (&$failCalled, &$failMessage) {
$failCalled = true;
$failMessage = $message;
});
$this->assertTrue($failCalled);
$this->assertEquals(__('validation.exclude_current_user'), $failMessage);
}
/**
* 로그인한 사용자가 ID 목록에 포함되지 않은 경우 검증 성공
*/
public function test_passes_when_current_user_is_not_in_ids(): void
{
Auth::shouldReceive('id')->andReturn(999);
$failCalled = false;
$this->rule->validate('ids', [1, 2, 3], function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* 인증되지 않은 사용자의 경우 검증 통과
*/
public function test_passes_when_user_is_not_authenticated(): void
{
Auth::shouldReceive('id')->andReturn(null);
$failCalled = false;
$this->rule->validate('ids', [1, 2, 3], function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* 배열이 아닌 값의 경우 검증 통과
*/
public function test_passes_when_value_is_not_array(): void
{
Auth::shouldReceive('id')->andReturn(1);
$failCalled = false;
$this->rule->validate('ids', 'not an array', function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* 빈 배열의 경우 검증 통과
*/
public function test_passes_when_array_is_empty(): void
{
Auth::shouldReceive('id')->andReturn(1);
$failCalled = false;
$this->rule->validate('ids', [], function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* 문자열 ID와 정수 ID의 느슨한 비교 테스트
*/
public function test_fails_with_loose_comparison(): void
{
Auth::shouldReceive('id')->andReturn(1);
$failCalled = false;
// 문자열 '1'도 정수 1과 동일하게 처리
$this->rule->validate('ids', ['1', 2, 3], function () use (&$failCalled) {
$failCalled = true;
});
$this->assertTrue($failCalled);
}
}
@@ -0,0 +1,385 @@
<?php
namespace Tests\Unit\Rules;
use App\Models\Template;
use App\Models\TemplateLayout;
use App\Rules\ValidDataSourceMerge;
use App\Rules\ValidParentLayout;
use App\Rules\ValidSlotStructure;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class LayoutInheritanceValidationTest extends TestCase
{
use RefreshDatabase;
private Template $template;
protected function setUp(): void
{
parent::setUp();
// 한국어 로케일 설정
app()->setLocale('ko');
// 테스트용 템플릿 생성 - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
$this->template = Template::factory()->create([
'identifier' => 'test-template-'.uniqid(),
'type' => 'user',
'status' => 'active',
]);
}
/**
* ValidParentLayout: 존재하지 않는 부모 레이아웃 검증 실패
*/
public function test_valid_parent_layout_fails_when_parent_not_found(): void
{
$rule = new ValidParentLayout;
$rule->setData([
'template_id' => $this->template->id,
'layout_name' => 'child',
]);
$failed = false;
$message = '';
$rule->validate('content.extends', 'non_existent_parent', function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('non_existent_parent', $message);
}
/**
* ValidParentLayout: 순환 참조 검증 실패
*/
public function test_valid_parent_layout_fails_on_circular_reference(): void
{
// 부모 레이아웃 생성
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'extends' => 'child', // 순환 참조: parent → child
'components' => [],
]),
]);
// 자식 레이아웃에서 parent를 extends로 지정
$rule = new ValidParentLayout;
$rule->setData([
'template_id' => $this->template->id,
'layout_name' => 'child',
]);
$failed = false;
$message = '';
$rule->validate('content.extends', 'parent', function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('순환', $message);
}
/**
* ValidParentLayout: 최대 상속 깊이 초과 검증 실패
*/
public function test_valid_parent_layout_fails_on_max_depth_exceeded(): void
{
// 깊은 상속 체인 생성 (11단계)
$previousName = null;
for ($i = 1; $i <= 11; $i++) {
$layoutName = "layout_{$i}";
$content = [
'version' => '1.0.0',
'layout_name' => $layoutName,
'components' => [],
];
if ($previousName) {
$content['extends'] = $previousName;
}
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => json_encode($content),
]);
$previousName = $layoutName;
}
// 새 레이아웃에서 layout_11을 extends로 지정 (12단계가 됨)
$rule = new ValidParentLayout;
$rule->setData([
'template_id' => $this->template->id,
'layout_name' => 'child',
]);
$failed = false;
$message = '';
$rule->validate('content.extends', 'layout_11', function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('깊이', $message);
}
/**
* ValidParentLayout: 유효한 부모 레이아웃 검증 통과
*/
public function test_valid_parent_layout_passes_with_valid_parent(): void
{
// 부모 레이아웃 생성
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'components' => [],
]),
]);
$rule = new ValidParentLayout;
$rule->setData([
'template_id' => $this->template->id,
'layout_name' => 'child',
]);
$failed = false;
$rule->validate('content.extends', 'parent', function () use (&$failed) {
$failed = true;
});
$this->assertFalse($failed);
}
/**
* ValidSlotStructure: 부모에 없는 슬롯 검증 실패
*/
public function test_valid_slot_structure_fails_when_slot_not_in_parent(): void
{
// 부모 레이아웃 생성 (content 슬롯만 있음)
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'components' => [
[
'id' => 'slot_container',
'type' => 'layout',
'name' => 'Div',
'slot' => 'content',
'children' => [],
],
],
]),
]);
$rule = new ValidSlotStructure;
$rule->setData([
'template_id' => $this->template->id,
'content' => [
'extends' => 'parent',
],
]);
$failed = false;
$message = '';
// sidebar 슬롯은 부모에 정의되지 않음
$slots = [
'content' => [],
'sidebar' => [], // 존재하지 않는 슬롯
];
$rule->validate('content.slots', $slots, function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('sidebar', $message);
}
/**
* ValidSlotStructure: 유효한 슬롯 구조 검증 통과
*/
public function test_valid_slot_structure_passes_with_valid_slots(): void
{
// 부모 레이아웃 생성
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'components' => [
[
'id' => 'slot_content',
'type' => 'layout',
'name' => 'Div',
'slot' => 'content',
'children' => [],
],
[
'id' => 'slot_sidebar',
'type' => 'layout',
'name' => 'Div',
'slot' => 'sidebar',
'children' => [],
],
],
]),
]);
$rule = new ValidSlotStructure;
$rule->setData([
'template_id' => $this->template->id,
'content' => [
'extends' => 'parent',
],
]);
$failed = false;
$slots = [
'content' => [],
'sidebar' => [],
];
$rule->validate('content.slots', $slots, function () use (&$failed) {
$failed = true;
});
$this->assertFalse($failed);
}
/**
* ValidDataSourceMerge: 중복 ID 검증 실패 (현재 레이아웃 내)
*/
public function test_valid_data_source_merge_fails_on_duplicate_id_in_current(): void
{
$rule = new ValidDataSourceMerge;
$rule->setData([
'template_id' => $this->template->id,
]);
$failed = false;
$message = '';
$dataSources = [
['id' => 'users', 'type' => 'api', 'endpoint' => '/api/users'],
['id' => 'users', 'type' => 'api', 'endpoint' => '/api/admin/users'], // 중복 ID
];
$rule->validate('content.data_sources', $dataSources, function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('users', $message);
}
/**
* ValidDataSourceMerge: 부모와 중복 ID 검증 실패
*/
public function test_valid_data_source_merge_fails_on_duplicate_id_with_parent(): void
{
// 부모 레이아웃 생성 (stats data_source 포함)
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'data_sources' => [
['id' => 'stats', 'type' => 'api', 'endpoint' => '/api/stats'],
],
'components' => [],
]),
]);
$rule = new ValidDataSourceMerge;
$rule->setData([
'template_id' => $this->template->id,
'content' => [
'extends' => 'parent',
],
]);
$failed = false;
$message = '';
// 자식 레이아웃에서 stats ID 재사용 (중복)
$dataSources = [
['id' => 'stats', 'type' => 'api', 'endpoint' => '/api/admin/stats'],
];
$rule->validate('content.data_sources', $dataSources, function ($msg) use (&$failed, &$message) {
$failed = true;
$message = $msg;
});
$this->assertTrue($failed);
$this->assertStringContainsString('stats', $message);
}
/**
* ValidDataSourceMerge: 유효한 data_sources 검증 통과
*/
public function test_valid_data_source_merge_passes_with_unique_ids(): void
{
// 부모 레이아웃 생성
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'parent',
'content' => json_encode([
'version' => '1.0.0',
'layout_name' => 'parent',
'data_sources' => [
['id' => 'stats', 'type' => 'api', 'endpoint' => '/api/stats'],
],
'components' => [],
]),
]);
$rule = new ValidDataSourceMerge;
$rule->setData([
'template_id' => $this->template->id,
'content' => [
'extends' => 'parent',
],
]);
$failed = false;
// 자식 레이아웃에서 다른 ID 사용
$dataSources = [
['id' => 'users', 'type' => 'api', 'endpoint' => '/api/users'],
];
$rule->validate('content.data_sources', $dataSources, function () use (&$failed) {
$failed = true;
});
$this->assertFalse($failed);
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\NotSelfParent;
use Tests\TestCase;
class NotSelfParentTest extends TestCase
{
/**
* 자기 자신을 부모로 설정하려는 경우 검증 실패
*/
public function test_fails_when_parent_id_equals_current_id(): void
{
$rule = new NotSelfParent(5);
$failCalled = false;
$failMessage = '';
$rule->validate('parent_id', 5, function ($message) use (&$failCalled, &$failMessage) {
$failCalled = true;
$failMessage = $message;
});
$this->assertTrue($failCalled);
$this->assertEquals(__('validation.not_self_parent'), $failMessage);
}
/**
* 다른 ID를 부모로 설정하는 경우 검증 성공
*/
public function test_passes_when_parent_id_is_different(): void
{
$rule = new NotSelfParent(5);
$failCalled = false;
$rule->validate('parent_id', 10, function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* parent_id가 null인 경우 검증 성공
*/
public function test_passes_when_parent_id_is_null(): void
{
$rule = new NotSelfParent(5);
$failCalled = false;
$rule->validate('parent_id', null, function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* currentId가 null인 경우 (새 생성) 검증 성공
*/
public function test_passes_when_current_id_is_null(): void
{
$rule = new NotSelfParent(null);
$failCalled = false;
$rule->validate('parent_id', 5, function () use (&$failCalled) {
$failCalled = true;
});
$this->assertFalse($failCalled);
}
/**
* 문자열과 정수 비교 테스트
*/
public function test_fails_with_string_integer_comparison(): void
{
$rule = new NotSelfParent(5);
$failCalled = false;
// 문자열 '5'도 정수 5와 동일하게 처리
$rule->validate('parent_id', '5', function () use (&$failCalled) {
$failCalled = true;
});
$this->assertTrue($failCalled);
}
}
+228
View File
@@ -0,0 +1,228 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\SafeModulePath;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
class SafeModulePathTest extends TestCase
{
private string $basePath;
protected function setUp(): void
{
parent::setUp();
$this->basePath = base_path('modules/test-module');
// 테스트용 디렉토리 및 파일 생성 (realpath 검증을 위해 필요)
if (! file_exists($this->basePath.'/dist/js/components')) {
mkdir($this->basePath.'/dist/js/components', 0755, true);
}
// 테스트용 파일 생성
file_put_contents($this->basePath.'/dist/js/module.iife.js', 'test');
file_put_contents($this->basePath.'/dist/js/components/Button.js', 'test');
}
protected function tearDown(): void
{
// 테스트용 파일 및 디렉토리 정리
if (file_exists($this->basePath)) {
$this->deleteDirectory($this->basePath);
}
parent::tearDown();
}
/**
* 디렉토리 재귀 삭제 헬퍼
*/
private function deleteDirectory(string $dir): bool
{
if (! file_exists($dir)) {
return true;
}
if (! is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
return rmdir($dir);
}
/**
* 유효한 경로가 허용되는지 테스트
*/
public function test_allows_valid_path(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => 'dist/js/module.iife.js'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 중첩 경로가 허용되는지 테스트
*/
public function test_allows_nested_path(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => 'dist/js/components/Button.js'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 기본 Path Traversal 패턴 차단 테스트 (../)
*/
public function test_blocks_path_traversal(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => '../../../.env'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
$this->assertArrayHasKey('path', $validator->errors()->toArray());
}
/**
* 백슬래시 Path Traversal 패턴 차단 테스트 (..\)
*/
public function test_blocks_backslash_traversal(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => '..\\..\\..\\config.php'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* URL 인코딩된 Path Traversal 패턴 차단 테스트
*/
public function test_blocks_url_encoded_traversal(): void
{
$encodedPatterns = [
'%2e%2e%2f', // ../
'%2e%2e/', // ../
'%2e%2e%5c', // ..\
'..%2f', // ../
'..%5c', // ..\
'.%2e/', // ../
];
foreach ($encodedPatterns as $pattern) {
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => $pattern.'secret.txt'],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Pattern {$pattern} should be blocked");
}
}
/**
* 다중 URL 인코딩 공격 차단 테스트
*/
public function test_blocks_double_url_encoded(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => '%252e%252e%252f.env'], // Double encoded ../
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 절대 경로 차단 테스트 - Windows
*/
public function test_blocks_windows_absolute_path(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => 'C:\\Windows\\System32\\config.ini'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 절대 경로 차단 테스트 - Linux
*/
public function test_blocks_linux_absolute_path(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => '/etc/passwd'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* NULL 바이트 공격 차단 테스트
*/
public function test_blocks_null_byte(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => "malicious.php\0.js"],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 문자열이 아닌 값 차단 테스트
*/
public function test_blocks_non_string_value(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => ['array', 'value']],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 이중 슬래시 차단 테스트
*/
public function test_blocks_double_slash(): void
{
$rule = new SafeModulePath($this->basePath);
$validator = Validator::make(
['path' => '//etc/passwd'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
}
+228
View File
@@ -0,0 +1,228 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\SafePluginPath;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
class SafePluginPathTest extends TestCase
{
private string $basePath;
protected function setUp(): void
{
parent::setUp();
$this->basePath = base_path('plugins/test-plugin');
// 테스트용 디렉토리 및 파일 생성 (realpath 검증을 위해 필요)
if (! file_exists($this->basePath.'/dist/js/components')) {
mkdir($this->basePath.'/dist/js/components', 0755, true);
}
// 테스트용 파일 생성
file_put_contents($this->basePath.'/dist/js/plugin.iife.js', 'test');
file_put_contents($this->basePath.'/dist/js/components/PaymentForm.js', 'test');
}
protected function tearDown(): void
{
// 테스트용 파일 및 디렉토리 정리
if (file_exists($this->basePath)) {
$this->deleteDirectory($this->basePath);
}
parent::tearDown();
}
/**
* 디렉토리 재귀 삭제 헬퍼
*/
private function deleteDirectory(string $dir): bool
{
if (! file_exists($dir)) {
return true;
}
if (! is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
return rmdir($dir);
}
/**
* 유효한 경로가 허용되는지 테스트
*/
public function test_allows_valid_path(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => 'dist/js/plugin.iife.js'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 중첩 경로가 허용되는지 테스트
*/
public function test_allows_nested_path(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => 'dist/js/components/PaymentForm.js'],
['path' => $rule]
);
$this->assertTrue($validator->passes());
}
/**
* 기본 Path Traversal 패턴 차단 테스트 (../)
*/
public function test_blocks_path_traversal(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => '../../../.env'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
$this->assertArrayHasKey('path', $validator->errors()->toArray());
}
/**
* 백슬래시 Path Traversal 패턴 차단 테스트 (..\)
*/
public function test_blocks_backslash_traversal(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => '..\\..\\..\\config.php'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* URL 인코딩된 Path Traversal 패턴 차단 테스트
*/
public function test_blocks_url_encoded_traversal(): void
{
$encodedPatterns = [
'%2e%2e%2f', // ../
'%2e%2e/', // ../
'%2e%2e%5c', // ..\
'..%2f', // ../
'..%5c', // ..\
'.%2e/', // ../
];
foreach ($encodedPatterns as $pattern) {
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => $pattern.'secret.txt'],
['path' => $rule]
);
$this->assertTrue($validator->fails(), "Pattern {$pattern} should be blocked");
}
}
/**
* 다중 URL 인코딩 공격 차단 테스트
*/
public function test_blocks_double_url_encoded(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => '%252e%252e%252f.env'], // Double encoded ../
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 절대 경로 차단 테스트 - Windows
*/
public function test_blocks_windows_absolute_path(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => 'C:\\Windows\\System32\\config.ini'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 절대 경로 차단 테스트 - Linux
*/
public function test_blocks_linux_absolute_path(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => '/etc/passwd'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* NULL 바이트 공격 차단 테스트
*/
public function test_blocks_null_byte(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => "malicious.php\0.js"],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 문자열이 아닌 값 차단 테스트
*/
public function test_blocks_non_string_value(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => ['array', 'value']],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
/**
* 이중 슬래시 차단 테스트
*/
public function test_blocks_double_slash(): void
{
$rule = new SafePluginPath($this->basePath);
$validator = Validator::make(
['path' => '//etc/passwd'],
['path' => $rule]
);
$this->assertTrue($validator->fails());
}
}
@@ -0,0 +1,115 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\ValidExtensionIdentifier;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class ValidExtensionIdentifierTest extends TestCase
{
/**
* 유효한 식별자 목록을 반환합니다.
*
* @return array<string, array{string}>
*/
public static function validIdentifiersProvider(): array
{
return [
'기본 형식' => ['sirsoft-board'],
'언더스코어 포함' => ['sirsoft-daum_postcode'],
'숫자 포함' => ['sirsoft-board2'],
'다중 언더스코어' => ['sirsoft-my_fancy_module'],
'벤더에 언더스코어' => ['my_vendor-my_module'],
'긴 식별자' => ['some_vendor-very_long_module_name'],
'숫자가 단어 중간에' => ['sirsoft-module2test'],
'3단 하이픈' => ['sirsoft-sub-module'],
];
}
/**
* 유효한 식별자가 통과하는지 테스트
*/
#[DataProvider('validIdentifiersProvider')]
public function test_valid_identifiers_pass(string $identifier): void
{
$validator = Validator::make(
['name' => $identifier],
['name' => [new ValidExtensionIdentifier]]
);
$this->assertTrue($validator->passes(), "식별자 '{$identifier}'는 유효해야 합니다");
}
/**
* 무효한 식별자 목록을 반환합니다.
*
* @return array<string, array{string, string}>
*/
public static function invalidIdentifiersProvider(): array
{
return [
'하이픈 없음 (단일 단어)' => ['sirsoftboard', 'min_parts'],
'숫자로 시작하는 단어' => ['sirsoft-2shop', 'word_starts_with_digit'],
'대문자 포함' => ['Sirsoft-Board', 'invalid_characters'],
'특수문자 포함 (@)' => ['sirsoft-my@module', 'invalid_characters'],
'특수문자 포함 (.)' => ['sirsoft-my.module', 'invalid_characters'],
'연속 하이픈' => ['sirsoft--board', 'empty_part'],
'시작 하이픈' => ['-sirsoft-board', 'empty_part'],
'끝 하이픈' => ['sirsoft-board-', 'empty_part'],
'연속 언더스코어' => ['sirsoft-my__module', 'empty_word'],
'시작 언더스코어' => ['sirsoft-_module', 'empty_word'],
'끝 언더스코어' => ['sirsoft-module_', 'empty_word'],
'언더스코어 뒤 숫자 시작' => ['sirsoft-foo_2bar', 'word_starts_with_digit'],
'공백 포함' => ['sirsoft-my module', 'invalid_characters'],
];
}
/**
* 무효한 식별자가 거부되는지 테스트
*/
#[DataProvider('invalidIdentifiersProvider')]
public function test_invalid_identifiers_fail(string $identifier, string $expectedMessageKey): void
{
$validator = Validator::make(
['name' => $identifier],
['name' => [new ValidExtensionIdentifier]]
);
$this->assertFalse($validator->passes(), "식별자 '{$identifier}'는 무효해야 합니다");
// 에러 메시지가 예상 키를 포함하는지 확인
$errorMessage = $validator->errors()->first('name');
$expectedTranslation = __('validation.extension_identifier.'.$expectedMessageKey);
$this->assertSame($expectedTranslation, $errorMessage, "식별자 '{$identifier}'의 에러 메시지가 '{$expectedMessageKey}' 키와 일치해야 합니다");
}
/**
* 문자열이 아닌 값이 거부되는지 테스트
*/
public function test_non_string_value_fails(): void
{
$validator = Validator::make(
['name' => 123],
['name' => [new ValidExtensionIdentifier]]
);
$this->assertFalse($validator->passes());
}
/**
* 255자 초과 식별자가 거부되는지 테스트
*/
public function test_too_long_identifier_fails(): void
{
$longIdentifier = 'sirsoft-'.str_repeat('a', 250);
$validator = Validator::make(
['name' => $longIdentifier],
['name' => [new ValidExtensionIdentifier]]
);
$this->assertFalse($validator->passes());
}
}
@@ -0,0 +1,16 @@
<?php
namespace Tests\Unit\Rules;
use PHPUnit\Framework\TestCase;
class ValidLayoutStructureTest extends TestCase
{
/**
* A basic unit test example.
*/
public function test_example(): void
{
$this->assertTrue(true);
}
}
@@ -0,0 +1,242 @@
<?php
namespace Tests\Unit\Rules;
use App\Rules\ValidPermissionStructure;
use Tests\TestCase;
/**
* ValidPermissionStructure 검증 규칙 테스트
*
* flat array, 구조화 객체(or/and), 중첩 구조, 무효한 입력을 포함합니다.
*/
class ValidPermissionStructureTest extends TestCase
{
private ValidPermissionStructure $rule;
protected function setUp(): void
{
parent::setUp();
$this->rule = new ValidPermissionStructure;
}
/**
* 검증을 실행하고 실패 메시지를 반환합니다.
*
* @param mixed $value 검증 대상 값
* @return string|null 실패 메시지 (성공 시 null)
*/
private function validate(mixed $value): ?string
{
$failMessage = null;
$this->rule->validate('permissions', $value, function ($message) use (&$failMessage) {
$failMessage = $message;
});
return $failMessage;
}
// ================================================================
// B-1. 유효한 구조 (통과)
// ================================================================
/** @test #1 빈 배열 */
public function test_b1_empty_array(): void
{
$this->assertNull($this->validate([]));
}
/** @test #2 단일 식별자 */
public function test_b1_single_identifier(): void
{
$this->assertNull($this->validate(['a.b.c']));
}
/** @test #3 복수 식별자 */
public function test_b1_multiple_identifiers(): void
{
$this->assertNull($this->validate(['a.b', 'c.d']));
}
/** @test #4 OR 구조 */
public function test_b1_or_structure(): void
{
$this->assertNull($this->validate(['or' => ['a.b', 'c.d']]));
}
/** @test #5 AND 구조 */
public function test_b1_and_structure(): void
{
$this->assertNull($this->validate(['and' => ['a.b', 'c.d']]));
}
/** @test #6 AND>OR 중첩 */
public function test_b1_and_or_nested(): void
{
$this->assertNull($this->validate(['and' => ['a.b', ['or' => ['b.c', 'c.d']]]]));
}
/** @test #7 OR>[AND,AND] 중첩 */
public function test_b1_or_and_and_nested(): void
{
$this->assertNull($this->validate([
'or' => [
['and' => ['a.b', 'b.c']],
['and' => ['c.d', 'd.e']],
],
]));
}
/** @test #8 3단계 중첩 */
public function test_b1_depth3_nested(): void
{
$this->assertNull($this->validate([
'and' => ['a.b', ['or' => ['b.c', ['and' => ['c.d', 'd.e']]]]],
]));
}
// ================================================================
// B-2. 무효한 연산자
// ================================================================
/** @test #9 invalid 연산자 */
public function test_b2_invalid_operator(): void
{
$this->assertNotNull($this->validate(['invalid' => ['a.b', 'c.d']]));
}
/** @test #10 대문자 OR */
public function test_b2_uppercase_or(): void
{
$this->assertNotNull($this->validate(['OR' => ['a.b', 'c.d']]));
}
/** @test #11 not 연산자 */
public function test_b2_not_operator(): void
{
$this->assertNotNull($this->validate(['not' => ['a.b']]));
}
/** @test #12 xor 연산자 */
public function test_b2_xor_operator(): void
{
$this->assertNotNull($this->validate(['xor' => ['a.b', 'c.d']]));
}
/** @test #13 복수 키 (or + and) */
public function test_b2_multiple_keys(): void
{
$this->assertNotNull($this->validate(['or' => ['a.b'], 'and' => ['c.d']]));
}
// ================================================================
// B-3. 최소 항목 위반
// ================================================================
/** @test #14 or: 1개 */
public function test_b3_or_one_item(): void
{
$this->assertNotNull($this->validate(['or' => ['a.b']]));
}
/** @test #15 and: 1개 */
public function test_b3_and_one_item(): void
{
$this->assertNotNull($this->validate(['and' => ['a.b']]));
}
/** @test #16 or: 0개 */
public function test_b3_or_empty(): void
{
$this->assertNotNull($this->validate(['or' => []]));
}
// ================================================================
// B-4. 깊이 초과
// ================================================================
/** @test #17 4단계 중첩 */
public function test_b4_depth4(): void
{
$this->assertNotNull($this->validate([
'and' => ['a.b', ['or' => ['b.c', ['and' => ['c.d', ['or' => ['d.e', 'e.f']]]]]]],
]));
}
/** @test #18 5단계 중첩 */
public function test_b4_depth5(): void
{
$this->assertNotNull($this->validate([
'and' => ['a.b', ['or' => ['b.c', ['and' => ['c.d', ['or' => ['d.e', ['and' => ['e.f', 'f.g']]]]]]]]],
]));
}
// ================================================================
// B-5. 권한 식별자 형식 오류
// ================================================================
/** @test #19 공백 포함 식별자 */
public function test_b5_space_in_identifier(): void
{
$this->assertNotNull($this->validate(['invalid identifier']));
}
/** @test #20 빈 문자열 */
public function test_b5_empty_string(): void
{
$this->assertNotNull($this->validate(['']));
}
/** @test #21 정수 */
public function test_b5_integer_in_array(): void
{
$this->assertNotNull($this->validate([123]));
}
/** @test #22 null 항목 */
public function test_b5_null_in_array(): void
{
$this->assertNotNull($this->validate([null]));
}
/** @test #23 or 내 정수 */
public function test_b5_integer_in_or(): void
{
$this->assertNotNull($this->validate(['or' => ['a.b', 123]]));
}
/** @test #24 or 내 null */
public function test_b5_null_in_or(): void
{
$this->assertNotNull($this->validate(['or' => ['a.b', null]]));
}
// ================================================================
// B-6. 타입 오류
// ================================================================
/** @test #25 문자열 입력 */
public function test_b6_string_input(): void
{
$this->assertNotNull($this->validate('string'));
}
/** @test #26 정수 입력 */
public function test_b6_integer_input(): void
{
$this->assertNotNull($this->validate(123));
}
/** @test #27 null 입력 (ValidPermissionStructure에서는 통과 - nullable은 외부 규칙) */
public function test_b6_null_input(): void
{
// null은 nullable 규칙에서 처리되므로 ValidPermissionStructure에서는 통과
$this->assertNull($this->validate(null));
}
/** @test #28 or 값이 배열이 아닌 문자열 */
public function test_b6_or_value_not_array(): void
{
$this->assertNotNull($this->validate(['or' => 'a.b']));
}
}