@@ -0,0 +1,215 @@
|
||||
<?php
|
||||
|
||||
use App\Services\StandaloneArtifact;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
$install = in_array('--install-authorized-pilot', $argv, true);
|
||||
if (! in_array('--run-authorized-private-copy', $argv, true) && ! $install) {
|
||||
throw new LogicException('EXPLICIT_PRIVATE_RECOVERY_REQUIRED');
|
||||
}
|
||||
$proposalPath = $root.'/docs/proofs/compras-standalone-pilot-recovery-proposal.json';
|
||||
$authorization = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-recovery-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($authorization['state'] ?? null) !== 'approved' || ($authorization['private_local_restore_only'] ?? null) !== true
|
||||
|| ! hash_equals($authorization['proposal_sha256'], hash_file('sha256', $proposalPath))) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_AUTHORIZATION_MISMATCH');
|
||||
}
|
||||
$proposal = json_decode(file_get_contents($proposalPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($install) {
|
||||
$installPlan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$installApproval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($installApproval['state'] ?? null) !== 'approved' || ($installApproval['scope'] ?? null) !== 'pilot_schema_and_pinned_runtime_only'
|
||||
|| ! hash_equals($installApproval['proposal_sha256'], hash_file('sha256', $root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'))
|
||||
|| is_file($root.'/docs/proofs/compras-standalone-pilot-installation.json')) {
|
||||
throw new LogicException('PILOT_INSTALLATION_AUTHORIZATION_OR_PREVIOUS_RESULT');
|
||||
}
|
||||
}
|
||||
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$adminSettings = Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
|
||||
if (($source['APP_ENV'] ?? null) !== 'payable-testing' || realpath($source['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ($source['DB_HOST'] ?? null) !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'] ?? '', $sourceMatch)
|
||||
|| $source['DB_USERNAME'] !== 'payable_qa_'.$sourceMatch[1] || ($adminSettings['DB_CONNECTION'] ?? null) !== 'pgsql'
|
||||
|| ($adminSettings['DB_HOST'] ?? null) !== '127.0.0.1' || $adminSettings['DB_PORT'] !== $source['DB_PORT']) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_SOURCE_IDENTITY');
|
||||
}
|
||||
$connect = static fn (string $database, string $user, string $password) => new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$database,
|
||||
$user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$db = $connect($source['DB_DATABASE'], $source['DB_USERNAME'], $source['DB_PASSWORD']);
|
||||
$admin = $connect('postgres', $adminSettings['DB_USERNAME'], $adminSettings['DB_PASSWORD']);
|
||||
$identity = $db->query('SELECT current_database() AS database_name,current_user AS role_name')->fetch(PDO::FETCH_ASSOC);
|
||||
if ($identity['database_name'] !== $source['DB_DATABASE'] || $identity['role_name'] !== $source['DB_USERNAME']) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_SOURCE_MISMATCH');
|
||||
}
|
||||
$id = bin2hex(random_bytes(6));
|
||||
$database = 'compras_private_restore_'.$id;
|
||||
$role = 'compras_private_app_'.$id;
|
||||
$password = bin2hex(random_bytes(32));
|
||||
$installation = Str::uuid()->toString();
|
||||
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-standalone-recovery-'.gmdate('Ymd-His').'-'.$id;
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_STORAGE_UNAVAILABLE');
|
||||
}
|
||||
$runtime = $root.'/storage/framework/testing/compras-standalone-80483320a54af6f1';
|
||||
$artifact = new StandaloneArtifact;
|
||||
$artifact->verify($runtime, $proposal['target']['runtime_manifest_sha256']);
|
||||
if ($install) {
|
||||
$archive = $runtime.'.zip';
|
||||
if (! hash_equals($installPlan['runtime']['archive_sha256'], hash_file('sha256', $archive))) {
|
||||
throw new LogicException('PILOT_INSTALLATION_ARCHIVE_CHANGED');
|
||||
}
|
||||
$target = $installPlan['runtime']['private_installation_directory'];
|
||||
if ($target !== 'C:/laragon/data/compras/runtime/80483320a54af6f1') {
|
||||
throw new LogicException('PILOT_INSTALLATION_PACKAGE_DESTINATION');
|
||||
}
|
||||
if (! is_dir($target)) {
|
||||
if (! mkdir($target, 0700, true)) {
|
||||
throw new LogicException('PILOT_INSTALLATION_PACKAGE_STORAGE');
|
||||
}
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($archive) !== true || ! $zip->extractTo($target)) {
|
||||
throw new LogicException('PILOT_INSTALLATION_PACKAGE_EXTRACTION');
|
||||
}
|
||||
$zip->close();
|
||||
}
|
||||
$artifact->verify($target, $installPlan['runtime']['manifest_sha256']);
|
||||
$runtime = $target;
|
||||
}
|
||||
$protectedFiles = [$root.'/.env', $root.'/public/build/manifest.json', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'];
|
||||
$protectedHashes = array_map(static fn ($path) => hash_file('sha256', $path), $protectedFiles);
|
||||
$fingerprint = static function (PDO $connection, array $columns): array {
|
||||
$frames = [];
|
||||
foreach ($columns as $table => $names) {
|
||||
$quoted = implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
|
||||
$rows = $connection->query('SELECT row_to_json(t)::text AS row FROM (SELECT '.$quoted.' FROM "'.str_replace('"', '""', $table).'") t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$frames[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
return $frames;
|
||||
};
|
||||
$pg = static function (string $binary, array $arguments, string $user, string $password) use ($source): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||
['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'], 'PGUSER' => $user, 'PGPASSWORD' => $password], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('PRIVATE_RECOVERY_'.$binary.'_FAILED');
|
||||
}
|
||||
};
|
||||
$createdRole = $createdDatabase = false;
|
||||
$report = ['date' => gmdate('c'), 'state' => 'in_progress', 'source_read_only' => true, 'source_writes' => false,
|
||||
'private_backup_directory' => $directory, 'temporary_database' => $database, 'temporary_role' => $role,
|
||||
'runtime_manifest' => $proposal['target']['runtime_manifest_sha256'], 'pilot_installation_or_activation' => false];
|
||||
file_put_contents($directory.'/ownership.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$columns = [];
|
||||
foreach ($db->query("SELECT table_name,column_name FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,ordinal_position")->fetchAll(PDO::FETCH_ASSOC) as $row) {
|
||||
$columns[$row['table_name']][] = $row['column_name'];
|
||||
}
|
||||
$before = $fingerprint($db, $columns);
|
||||
$originalMigrations = $db->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$baseline = ['columns' => $columns, 'frames' => $before, 'migrations' => $originalMigrations];
|
||||
file_put_contents($directory.'/baseline.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
|
||||
$snapshot = $db->query('SELECT pg_export_snapshot()')->fetchColumn();
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$directory.'/before.dump', '--dbname='.$source['DB_DATABASE']], $source['DB_USERNAME'], $source['DB_PASSWORD']);
|
||||
$db->commit();
|
||||
$report['backup_sha256'] = hash_file('sha256', $directory.'/before.dump');
|
||||
$admin->exec('CREATE ROLE "'.$role.'" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD '.$admin->quote($password));
|
||||
$createdRole = true;
|
||||
$admin->exec('CREATE DATABASE "'.$database.'" OWNER "'.$role.'" TEMPLATE template0');
|
||||
$createdDatabase = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='.$database, $directory.'/before.dump'], $role, $password);
|
||||
$copy = $connect($database, $role, $password);
|
||||
if ($fingerprint($copy, $columns) !== $before) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_INITIAL_DATA_MISMATCH');
|
||||
}
|
||||
$report['initial_tables_preserved'] = count($before);
|
||||
$environment = ['APP_ENV' => 'private-recovery', 'APP_DEBUG' => 'false', 'APP_KEY' => 'base64:'.base64_encode(random_bytes(32)),
|
||||
'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => $source['DB_PORT'],
|
||||
'DB_DATABASE' => $database, 'DB_USERNAME' => $role, 'DB_PASSWORD' => $password,
|
||||
'COMPRAS_RUNTIME_ROOT' => $runtime, 'COMPRAS_RUNTIME_SHA256' => $proposal['target']['runtime_manifest_sha256'],
|
||||
'COMPRAS_RUNTIME_INSTALLATION_ID' => $installation, 'COMPRAS_RUNTIME_ENABLED' => 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY' => 'true',
|
||||
'COMPRAS_RUNTIME_SYNTHETIC_ONLY' => 'false', 'COMMON_FINANCE_BUNDLE_ROOT' => '(null)', 'COMMON_FINANCE_BUNDLE_SHA256' => '(null)',
|
||||
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'false', 'SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED' => 'false',
|
||||
'COMMON_PAYABLES_PATH' => $runtime.'/payables', 'COMMON_BUDGET_PATH' => $runtime.'/budget-control', 'COMMON_PURCHASING_PATH' => $runtime.'/purchasing',
|
||||
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array', 'BROADCAST_CONNECTION' => 'null',
|
||||
'APP_CONFIG_CACHE' => $directory.'/absent-config.php', 'LOG_CHANNEL' => 'stderr',
|
||||
'COMPRAS_INSTALLATION_BASELINE' => $directory.'/baseline.private.json'];
|
||||
$process = new Process(['php', 'tests/Support/standalone-pilot-recovery-worker.php'], $root, $environment, timeout: 120);
|
||||
$process->run();
|
||||
file_put_contents($directory.'/worker.private.log', $process->getOutput().$process->getErrorOutput());
|
||||
if (! $process->isSuccessful()) {
|
||||
file_put_contents($directory.'/worker.private.log', $process->getOutput().$process->getErrorOutput());
|
||||
throw new RuntimeException('PRIVATE_RECOVERY_WORKER_FAILED_PRIVATE_DIAGNOSTIC_SAVED');
|
||||
}
|
||||
$output = json_decode(trim($process->getOutput()), true);
|
||||
if (! is_array($output) || ($output['verified'] ?? false) !== true) {
|
||||
throw new RuntimeException('PRIVATE_RECOVERY_WORKER_INVALID_RESULT_PRIVATE_DIAGNOSTIC_SAVED');
|
||||
}
|
||||
$report['upgrade'] = $output;
|
||||
$expectedMigrations = [...$originalMigrations, ...array_map(static fn ($path) => basename($path, '.php'),
|
||||
array_keys($proposal['selected_normal_migrations_in_restored_copy_only']))];
|
||||
sort($expectedMigrations, SORT_STRING);
|
||||
if ($copy->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN) !== $expectedMigrations) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_HISTORY_CHANGED');
|
||||
}
|
||||
$report['historical_migration_records_preserved'] = true;
|
||||
$after = $fingerprint($copy, $columns);
|
||||
unset($after['migrations'], $before['migrations']);
|
||||
if ($after !== $before) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_ORIGINAL_COLUMNS_CHANGED');
|
||||
}
|
||||
$report['original_business_tables_preserved'] = count($before);
|
||||
if ($install) {
|
||||
$pilotEnvironment = [...$environment, 'DB_DATABASE' => $source['DB_DATABASE'], 'DB_USERNAME' => $source['DB_USERNAME'],
|
||||
'DB_PASSWORD' => $source['DB_PASSWORD'], 'COMPRAS_RUNTIME_INSTALLATION_ID' => Str::uuid()->toString(),
|
||||
'COMPRAS_INSTALLATION_BASELINE' => $directory.'/baseline.private.json'];
|
||||
$process = new Process(['php', 'tests/Support/standalone-pilot-recovery-worker.php', '--install-authorized-pilot'], $root, $pilotEnvironment, timeout: 120);
|
||||
$process->run();
|
||||
file_put_contents($directory.'/installation.private.log', $process->getOutput().$process->getErrorOutput());
|
||||
$output = json_decode(trim($process->getOutput()), true);
|
||||
if (! $process->isSuccessful() || ! is_array($output) || ($output['verified'] ?? false) !== true) {
|
||||
throw new RuntimeException('PILOT_INSTALLATION_FAILED_PRIVATE_DIAGNOSTIC_SAVED');
|
||||
}
|
||||
$report['pilot_upgrade'] = $output;
|
||||
$report['pilot_installation_or_activation'] = 'installation_only';
|
||||
$report['pilot_activation'] = false;
|
||||
$report['source_read_only'] = false;
|
||||
$report['source_writes'] = 'five_selected_migrations_and_runtime_schema_receipt_only';
|
||||
$report['runtime_directory'] = $runtime;
|
||||
$report['installation_id'] = $pilotEnvironment['COMPRAS_RUNTIME_INSTALLATION_ID'];
|
||||
if ($protectedHashes !== array_map(static fn ($path) => hash_file('sha256', $path), $protectedFiles)) {
|
||||
throw new LogicException('PILOT_INSTALLATION_PROTECTED_FILES_CHANGED');
|
||||
}
|
||||
$report['active_settings_env_and_asset_manifest_preserved'] = true;
|
||||
}
|
||||
$report['state'] = 'passed';
|
||||
} catch (Throwable $error) {
|
||||
$report['state'] = 'failed';
|
||||
$report['failure_class'] = get_class($error);
|
||||
throw $error;
|
||||
} finally {
|
||||
if ($db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
$copy = null;
|
||||
if ($createdDatabase) {
|
||||
// Exact generated identifier, separately recorded before creation; never the source.
|
||||
if ($database === $source['DB_DATABASE'] || ! preg_match('/^compras_private_restore_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('PRIVATE_RECOVERY_CLEANUP_TARGET');
|
||||
}
|
||||
$admin->exec('DROP DATABASE "'.$database.'"');
|
||||
$report['temporary_database_removed'] = true;
|
||||
}
|
||||
if ($createdRole) {
|
||||
$admin->exec('DROP ROLE "'.$role.'"');
|
||||
$report['temporary_role_removed'] = true;
|
||||
}
|
||||
file_put_contents($directory.'/result.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
file_put_contents($root.'/docs/proofs/'.($install ? 'compras-standalone-pilot-installation.json' : 'compras-standalone-pilot-recovery.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
}
|
||||
echo json_encode(['state' => $report['state'], 'initial_tables_preserved' => $report['initial_tables_preserved'],
|
||||
'original_business_tables_preserved' => $report['original_business_tables_preserved'], 'temporary_resources_removed' => true,
|
||||
'source_writes' => $report['source_writes']], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
Reference in New Issue
Block a user