first commit

This commit is contained in:
brusnitsyn
2026-06-24 17:20:43 +09:00
commit 43499acf1c
165 changed files with 25929 additions and 0 deletions

1
database/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.sqlite*

View File

@@ -0,0 +1,30 @@
<?php
namespace Database\Factories;
use App\Models\PersonalData;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<PersonalData>
*/
class PersonalDataFactory extends Factory
{
protected $model = PersonalData::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'last_name' => fake()->lastName(),
'first_name' => fake()->firstName(),
'middle_name' => fake()->firstName(),
'birth_date' => fake()->date(),
'passport' => fake()->numerify('#### ######'),
'snils' => fake()->numerify('###-###-### ##'),
'phone' => fake()->phoneNumber(),
];
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'password_changed_at' => now(),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
/**
* Пользователь с истёкшим сроком действия пароля (для тестов ИАФ.3).
*/
public function passwordExpired(): static
{
return $this->state(fn (array $attributes) => [
'password_changed_at' => now()->subDays((int) config('security.password.max_age_days') + 1),
]);
}
/**
* Пользователь с подтверждённым вторым фактором (для тестов ИАФ.4).
*/
public function withMfa(): static
{
return $this->state(fn (array $attributes) => [
'mfa_secret' => 'JBSWY3DPEHPK3PXP',
'mfa_confirmed_at' => now(),
]);
}
}

View File

@@ -0,0 +1,64 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
// Парольная политика (ИАФ.3): отметка времени последней смены пароля.
$table->timestamp('password_changed_at')->nullable();
// Многофакторная аутентификация (ИАФ.4). Секрет и резервные коды
// хранятся в зашифрованном виде (ЗНI) — поэтому text, не string.
$table->text('mfa_secret')->nullable();
$table->text('mfa_recovery_codes')->nullable();
$table->timestamp('mfa_confirmed_at')->nullable();
// Управление учётной записью (ИАФ.2, УПД.1).
$table->boolean('is_blocked')->default(false);
$table->timestamp('last_login_at')->nullable();
$table->rememberToken();
$table->softDeletes(); // Жизненный цикл идентификатора (ИАФ.2).
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->bigInteger('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->bigInteger('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedSmallInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->string('connection');
$table->string('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
$table->index(['connection', 'queue', 'failed_at']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* История паролей (мера ИАФ.3 запрет повтора последних N паролей).
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('password_histories', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('password_hash');
$table->timestamp('created_at')->nullable()->index();
});
}
public function down(): void
{
Schema::dropIfExists('password_histories');
}
};

View File

@@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* ПРИМЕР таблицы с персональными данными.
*
* Демонстрирует подход для УЗ-1: поля ПДн зашифрованы на уровне приложения
* (тип text, см. трейт HasPdnEncryption), хранится контрольная сумма для
* контроля целостности (мера ОЦЛ.2) и владелец записи для разграничения
* доступа (мера УПД.2 через PersonalDataPolicy).
*
* Адаптируйте/удалите под конкретный проект.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('personal_data', function (Blueprint $table) {
$table->id();
// Владелец/субъект записи — для разграничения доступа (УПД.2).
$table->foreignId('owner_id')->nullable()->constrained('users')->nullOnDelete();
// Псевдоним субъекта (HMAC) для аналитики без раскрытия ПДн.
$table->string('subject_pseudonym')->nullable()->index();
// Зашифрованные поля ПДн (ЗНИ). Хранятся как шифртекст -> text.
$table->text('last_name')->nullable();
$table->text('first_name')->nullable();
$table->text('middle_name')->nullable();
$table->text('birth_date')->nullable();
$table->text('passport')->nullable();
$table->text('snils')->nullable();
$table->text('phone')->nullable();
// Контроль целостности данных (ОЦЛ.2): HMAC по содержимому записи.
$table->string('checksum')->nullable();
$table->softDeletes(); // Минимизация/жизненный цикл данных.
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('personal_data');
}
};

View File

@@ -0,0 +1,137 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
/**
* See `docs/prerequisites.md` for suggested lengths on 'name' and 'guard_name' if "1071 Specified key was too long" errors are encountered.
*/
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
$table->id(); // permission id
$table->string('name');
$table->string('guard_name');
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
/**
* See `docs/prerequisites.md` for suggested lengths on 'name' and 'guard_name' if "1071 Specified key was too long" errors are encountered.
*/
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
$table->id(); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name');
$table->string('guard_name');
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->cascadeOnDelete();
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->cascadeOnDelete();
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->cascadeOnDelete();
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->cascadeOnDelete();
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::dropIfExists($tableNames['role_has_permissions']);
Schema::dropIfExists($tableNames['model_has_roles']);
Schema::dropIfExists($tableNames['model_has_permissions']);
Schema::dropIfExists($tableNames['roles']);
Schema::dropIfExists($tableNames['permissions']);
}
};

View File

@@ -0,0 +1,50 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Журнал регистрации событий безопасности (меры РСБ.2, РСБ.3).
*
* Размещается в ОТДЕЛЬНОМ соединении (audit). Запускается командой:
* php artisan migrate --database=audit --path=database/migrations/audit
*
* В production учётной записи приложения выдаются права только INSERT/SELECT
* (см. database/sql/audit_grants.sql), что обеспечивает неизменяемость журнала.
*/
return new class extends Migration
{
public function getConnection(): ?string
{
return config('audit.connection', 'audit');
}
public function up(): void
{
Schema::connection($this->getConnection())->create(config('audit.table', 'audit_log'), function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('event_id')->index();
$table->string('event_type')->index();
$table->string('user_id')->nullable()->index();
$table->string('ip', 45)->nullable();
$table->string('user_agent', 512)->nullable();
$table->string('session_id')->nullable();
$table->string('resource')->nullable()->index();
$table->string('action');
$table->string('result', 16)->index();
$table->json('details')->nullable();
// Контроль целостности (РСБ.3): HMAC-подпись и хеш-цепочка.
$table->string('prev_hash')->nullable();
$table->string('signature');
$table->timestamp('created_at')->nullable()->index();
});
}
public function down(): void
{
Schema::connection($this->getConnection())->dropIfExists(config('audit.table', 'audit_log'));
}
};

View File

@@ -0,0 +1,21 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
public function run(): void
{
// Базовая ролевая модель (RBAC, мера УПД.4).
$this->call(RolesAndPermissionsSeeder::class);
// Учётную запись администратора создавайте командой (мера УПД.1):
// php artisan user:create-admin
// Тестовых пользователей в production не создаём.
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
/**
* Базовая ролевая модель (RBAC) по разделу 4.2 гайда.
*
* Меры ФСТЭК: УПД.4 (разделение ролей), УПД.5 (наименьшие привилегии),
* разделение обязанностей (оператор работает с ПДн, аудитор только журналы).
*/
class RolesAndPermissionsSeeder extends Seeder
{
public function run(): void
{
app(PermissionRegistrar::class)->forgetCachedPermissions();
$permissions = [
// Работа с персональными данными.
'pdn.view',
'pdn.create',
'pdn.update',
'pdn.delete',
'pdn.export',
// Администрирование пользователей и прав (УПД.13).
'users.manage',
'roles.manage',
// Просмотр журналов аудита.
'audit.view',
];
foreach ($permissions as $permission) {
Permission::findOrCreate($permission, 'web');
}
// super_admin — только для DBA, не выдаётся через веб-интерфейс.
$superAdmin = Role::findOrCreate('super_admin', 'web');
$superAdmin->givePermissionTo(Permission::all());
// admin — управление пользователями, полный доступ к ПДн.
$admin = Role::findOrCreate('admin', 'web');
$admin->givePermissionTo([
'pdn.view', 'pdn.create', 'pdn.update', 'pdn.delete', 'pdn.export',
'users.manage', 'roles.manage',
]);
// operator — работа с ПДн в рамках задач, без управления пользователями.
$operator = Role::findOrCreate('operator', 'web');
$operator->givePermissionTo(['pdn.view', 'pdn.create', 'pdn.update']);
// auditor — только чтение журналов (разделение обязанностей).
$auditor = Role::findOrCreate('auditor', 'web');
$auditor->givePermissionTo(['audit.view']);
// user — доступ только к своим данным.
$user = Role::findOrCreate('user', 'web');
$user->givePermissionTo(['pdn.view']);
}
}

View File

@@ -0,0 +1,32 @@
-- ============================================================================
-- Права доступа к БД журнала аудита (мера ФСТЭК РСБ.3)
-- Учётная запись приложения может ТОЛЬКО добавлять и читать записи журнала,
-- но не изменять и не удалять их — это обеспечивает неизменяемость журнала.
--
-- Применять в отдельной БД журнала (AUDIT_DB_DATABASE) под суперпользователем.
-- PostgreSQL.
-- ============================================================================
-- 1. Роль приложения для записи журнала (укажите пароль из секрет-хранилища).
-- CREATE ROLE app_audit_writer LOGIN PASSWORD '***';
-- 2. Подключение и схема.
GRANT CONNECT ON DATABASE app_audit TO app_audit_writer;
GRANT USAGE ON SCHEMA public TO app_audit_writer;
-- 3. Только добавление и чтение записей журнала (никаких UPDATE/DELETE/TRUNCATE).
GRANT INSERT, SELECT ON TABLE audit_log TO app_audit_writer;
GRANT USAGE, SELECT ON SEQUENCE audit_log_id_seq TO app_audit_writer;
-- 4. Явный запрет изменения и удаления (на случай наследуемых прав).
REVOKE UPDATE, DELETE, TRUNCATE ON TABLE audit_log FROM app_audit_writer;
-- 5. Очистку по сроку хранения (команда audit:purge, мера РСБ.8) выполняет
-- ОТДЕЛЬНАЯ привилегированная роль по регламенту, не роль приложения:
-- CREATE ROLE audit_retention LOGIN PASSWORD '***';
-- GRANT DELETE ON TABLE audit_log TO audit_retention;
--
-- В этом случае запускайте artisan audit:purge под соединением с этой ролью.
-- 6. Рекомендация (РСБ.3): включить аудит самой СУБД и физически выносить
-- журнал на отдельный сервер/хранилище с репликацией в SIEM.