Core 모듈 개요
📝 초안 (Draft)
이 문서는 검토 중입니다. 내용이 변경될 수 있습니다.
Multi-SaaS Kit의 Core 모듈 아키텍처와 구조를 설명합니다.
개요
Core 모듈은 Multi-SaaS Kit의 핵심 기능을 제공하는 내부 라이브러리입니다. 모든 프로젝트에서 공통으로 사용되는 권한, 테넌트, 인증, 보안 기능을 제공합니다.
packages/core/ # Core 모듈 (중앙 관리)
├── Base/ # 필수 모듈 (모든 프로젝트)
│ ├── Permission/ # 권한 시스템 (Level 0~6, ADR-058)
│ ├── Tenant/ # 멀티테넌시 격리
│ ├── Auth/ # 인증/토큰 관리
│ ├── Audit/ # 감사 로그
│ ├── Security/ # 보안 (XSS, 헤더)
│ ├── Database/ # DB 안전장치
│ └── Plugin/ # 플러그인 시스템
│
├── Extensions/ # 선택적 모듈
│ ├── Guardian/ # 후견인 관계 (LMS, 교육)
│ └── Impersonate/ # 사용자 전환
│
├── Contracts/ # Interface 정의
├── Integrations/ # 외부 연동
├── Providers/ # CoreServiceProvider
└── config/ # core.php 설정
모듈 분류
Base 모듈 (7개)
모든 프로젝트에서 기본 활성화되는 필수 모듈입니다.
| 모듈 | 역할 | 주요 기능 |
|---|---|---|
| Permission | 권한 시스템 (Level 0~6, ADR-058) | UserLevel enum, 권한 검사, Policy |
| Tenant | 멀티테넌시 | TenantScope, 테넌트 컨텍스트, 격리 |
| Auth | 인증 관리 | Sanctum 토큰, 세션, 인증 서비스 |
| Audit | 감사 로그 | 모델 변경 추적, 활동 기록 |
| Security | 보안 | XSS 방지, 보안 헤더, 입력 검증 |
| Database | DB 안전장치 | 파괴적 Artisan DB 명령 차단, 1회성 unlock token |
| Filament | Filament 공통 액션 | SafeDeleteAction ("DELETE {대상명}" 확인 삭제) |
| Plugin | 플러그인 관리 | 플러그인 탐색, 활성화, 부팅 |
Extensions 모듈 (2개)
필요한 프로젝트에서만 활성화하는 선택적 모듈입니다.
| 모듈 | 역할 | 활성화 조건 | 사용 예 |
|---|---|---|---|
| Guardian | 후견인 관계 | config('core.guardian.enabled') | LMS, 교육 플랫폼 |
| Impersonate | 사용자 전환 | config('core.impersonate.enabled') | 관리자 CS 지원 |
모듈 간 의존성
Permission ◄───────────────────────┐
│ │
▼ │
Tenant ────────► Auth ────────► Security
│ │
▼ ▼
Audit Database
│
▼
Plugin (Optional)
| 의존 관계 | 설명 |
|---|---|
| Tenant → Permission | 테넌트 격리 시 권한 레벨 확인 필요 |
| Tenant → Auth | 테넌트 컨텍스트 설정 시 인증 사용자 필요 |
| Audit → Tenant | 감사 로그에 테넌트 정보 포함 |
| All → Security | 모든 모듈에서 보안 규칙 적용 |
CoreServiceProvider
모든 Core 모듈은 CoreServiceProvider에서 통합 등록됩니다.
// packages/core/Providers/CoreServiceProvider.php
class CoreServiceProvider extends ServiceProvider
{
public function register(): void
{
// Config 병합
$this->mergeConfigFrom(__DIR__.'/../config/core.php', 'core');
// Service 싱글톤 등록
$this->app->singleton(PermissionServiceInterface::class, PermissionService::class);
$this->app->singleton(TenantResolverInterface::class, TenantRouteService::class);
$this->app->singleton(AuthServiceInterface::class, AuthService::class);
$this->app->singleton(SecurityServiceInterface::class, SecurityService::class);
$this->app->singleton(PluginManagerInterface::class, PluginManager::class);
// Extensions 조건부 등록
$this->registerExtensions();
}
public function boot(): void
{
// Policy 등록
$this->registerPolicies();
// Middleware 별칭 등록
$router = $this->app['router'];
$router->aliasMiddleware('level', EnsureUserLevel::class);
$router->aliasMiddleware('tenant.context', SetTenantContext::class);
$router->aliasMiddleware('security.headers', SecurityHeaders::class);
}
}
등록되는 서비스
| Interface | Implementation | 용도 |
|---|---|---|
PermissionServiceInterface | PermissionService | 권한 검사 |
TenantResolverInterface | TenantRouteService | 테넌트 식별 |
AuthServiceInterface | AuthService | 인증 처리 |
SecurityServiceInterface | SecurityService | 보안 검사 |
PluginManagerInterface | PluginManager | 플러그인 관리 |
등록되는 미들웨어
| 별칭 | 클래스 | 용도 |
|---|---|---|
level | EnsureUserLevel | 권한 레벨 체크 |
tenant.context | SetTenantContext | 테넌트 컨텍스트 설정 |
tenant.identify | IdentifyTenant | 테넌트 식별 |
security.headers | SecurityHeaders | 보안 헤더 추가 |
security.xss | PreventXSS | XSS 방지 |
설정 (config/core.php)
Core 모듈은 config/core.php에서 중앙 설정됩니다.
Permission 설정
'permission' => [
'enabled' => env('CORE_PERMISSION_ENABLED', true),
// Level 0~6 계층 레벨 정의
'levels' => [
0 => 'Platform Admin',
1 => 'SaaS Admin',
2 => 'Tenant Admin',
3 => 'Organization Admin',
4 => 'Workspace Admin',
5 => 'Group Leader',
6 => 'Member',
],
'default_level' => 6,
// 패널별 접근 허용 레벨
'panel_access' => [
'platform' => [0],
'saas' => [0, 1],
'tenant' => [0, 1, 2],
// ...
],
],
Tenant 설정
'tenant' => [
'enabled' => env('CORE_TENANT_ENABLED', true),
// PostgreSQL RLS 활성화
'rls_enabled' => env('CORE_RLS_ENABLED', false),
// 테넌트 컬럼명
'column' => 'tenant_id',
// 격리 우회 가능 레벨 (Platform/SaaS Admin)
'bypass_levels' => [0, 1],
],
Audit 설정
'audit' => [
'enabled' => env('CORE_AUDIT_ENABLED', true),
// 감사 로그 테이블
'table' => 'audit_logs',
// 기록할 이벤트
'events' => ['created', 'updated', 'deleted'],
// 제외할 민감 속성
'exclude_attributes' => [
'password',
'remember_token',
'two_factor_secret',
],
],
Security 설정
'security' => [
'enabled' => env('CORE_SECURITY_ENABLED', true),
// XSS 보호
'xss_protection' => env('CORE_XSS_PROTECTION', true),
// 보안 헤더
'headers' => [
'x_frame_options' => true,
'x_content_type_options' => true,
'x_xss_protection' => true,
'hsts' => false, // HTTPS 환경에서 활성화
],
],
Model 바인딩
'models' => [
'user' => \App\Models\User::class,
'tenant' => \App\Models\Tenant::class,
'organization' => \App\Models\Organization::class,
],
커스텀 모델 사용
프로젝트에서 커스텀 User 모델을 사용하려면 config/core.php에서 변경하세요.
Extension 활성화
Guardian 활성화
Guardian은 후견인-피후견인 관계를 관리합니다 (부모-자녀, 교사-학생 등).
// .env
CORE_GUARDIAN_ENABLED=true
// config/core.php
'guardian' => [
'enabled' => env('CORE_GUARDIAN_ENABLED', false),
// Guardian 전용 설정...
],
Impersonate 활성화
Impersonate는 관리자가 다른 사용자로 전환하는 기능입니다.
// .env
CORE_IMPERSONATE_ENABLED=true
// config/core.php
'impersonate' => [
'enabled' => env('CORE_IMPERSONATE_ENABLED', false),
// Impersonate 전용 설정...
],
Contracts (Interface)
Core 모듈은 Interface 기반 설계로 확장성을 보장합니다.
// 주요 Contracts
App\Core\Contracts\UserInterface // User 모델 인터페이스
App\Core\Contracts\TenantInterface // Tenant 모델 인터페이스
// Base 모듈 Contracts
App\Core\Base\Permission\Contracts\PermissionServiceInterface
App\Core\Base\Tenant\Contracts\TenantResolverInterface
App\Core\Base\Auth\Contracts\AuthServiceInterface
App\Core\Base\Security\Contracts\SecurityServiceInterface
App\Core\Base\Plugin\Contracts\PluginManagerInterface
Interface 기반 설계 이점
| 이점 | 설명 |
|---|---|
| 테스트 용이 | Mock 객체로 쉽게 대체 가능 |
| 확장성 | 커스텀 구현체로 교체 가능 |
| 의존성 역전 | 구현이 아닌 추상에 의존 |
| 패키지화 대비 | 향후 Composer 패키지로 분리 용이 |
프로젝트에서 Core 사용
심볼릭 링크 구조
workspace/{project}/web/app/Core → ../../../../packages/core
직접 복사 방식 (독립 운영)
프로젝트별 독립 운영이 필요한 경우:
# 심볼릭 링크 제거
rm workspace/myproject/web/app/Core
# 실제 복사
cp -r packages/core workspace/myproject/web/app/Core
Service 주입 사용
use App\Core\Base\Permission\Contracts\PermissionServiceInterface;
class UserController extends Controller
{
public function __construct(
private PermissionServiceInterface $permissionService
) {}
public function index()
{
if ($this->permissionService->canManageUsers(auth()->user())) {
// 사용자 관리 가능
}
}
}
패키지화 대비 원칙
Core 모듈은 향후 Composer 패키지로 분리할 수 있도록 설계되었습니다.
필수 원칙
| 원칙 | 설명 | 예시 |
|---|---|---|
| Interface 추상화 | 프로젝트 모델 직접 참조 금지 | UserInterface 사용 |
| Config 기반 설정 | 하드코딩 금지 | config('core.xxx') |
| Event 기반 확장 | 직접 호출 대신 이벤트 발행 | TenantCreated event |
| 의존성 주입 | 경로 하드코딩 금지 | Service Container 활용 |
피해야 할 패턴
// ❌ 잘못된 예: 프로젝트 모델 직접 참조
use App\Models\User;
$user = User::find(1);
// ✅ 올바른 예: Interface 사용
use App\Core\Contracts\UserInterface;
$userClass = config('core.models.user');
$user = $userClass::find(1);
// ❌ 잘못된 예: 하드코딩
$bypassLevels = [0, 1];
// ✅ 올바른 예: Config 사용
$bypassLevels = config('core.tenant.bypass_levels');
관련 문서
- Permission 모듈 - 권한 분류 (Level 0~6) 상세
- Tenant 모듈 - 테넌트 격리 상세
- Auth 모듈 - 인증 상세
- Audit 모듈 - 감사 로그 상세
- DB 안전 가드 - 파괴적 DB 명령 차단 정책
- Guardian 모듈 - 후견인 관계
- Impersonate 모듈 - 사용자 전환