Files
compras/scripts/verify-replenishment-task-backup.php
T
nala 96b30368bc
tests / ci (push) Canceled after 0s
commit compras5 2911
2026-11-29 19:49:19 +02:00

71 lines
4.1 KiB
PHP

<?php
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
if (count($argv) !== 2 || $argv[1] !== '--restore-private-copy') {
throw new LogicException('Explicit private restore required.');
}
$root = dirname(__DIR__);
$record = json_decode(file_get_contents($root.'/docs/proofs/replenishment-task-installation.json'), true, 32, JSON_THROW_ON_ERROR);
$directory = str_replace('\\', '/', $record['private_backup_directory']);
if (! preg_match('~^C:/laragon/data/compras/tasks/replenishment-[0-9]{8}-[0-9]{6}-[a-f0-9]{12}$~D', $directory)
|| ! hash_equals($record['database_backup_sha256'], hash_file('sha256', $directory.'/before.dump'))) {
throw new LogicException('Owned backup required.');
}
$source = json_decode(file_get_contents($directory.'/settings.private.json'), true, 32, JSON_THROW_ON_ERROR);
$settings = Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
if ($settings['DB_CONNECTION'] !== 'pgsql' || $settings['DB_HOST'] !== '127.0.0.1' || $source['DB_HOST'] !== '127.0.0.1'
|| $settings['DB_PORT'] !== $source['DB_PORT'] || $source['APP_ENV'] !== 'payable-testing'
|| realpath($source['HOST_ROOT']) !== realpath($root)) {
throw new LogicException('Own local recovery cluster required.');
}
$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]);
$admin = $connect('postgres', $settings['DB_USERNAME'], $settings['DB_PASSWORD']);
$id = bin2hex(random_bytes(6));
$role = 'compras_replenish_app_'.$id;
$database = 'compras_replenish_restore_'.$id;
$password = bin2hex(random_bytes(32));
$createdRole = $createdDatabase = false;
$copy = null;
try {
$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.'"');
$createdDatabase = true;
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--no-owner', '--no-acl', '--exit-on-error',
'--dbname='.$database, $directory.'/before.dump'], $root, ['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'],
'PGUSER' => $role, 'PGPASSWORD' => $password], timeout: 120);
$process->run();
if (! $process->isSuccessful()) {
throw new LogicException('Private replenishment backup restore failed.');
}
$copy = $connect($database, $role, $password);
$copy->exec('SET default_transaction_read_only=on');
$baseline = json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR);
$tables = $copy->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN);
if ($tables !== array_keys($baseline)) {
throw new LogicException('Restored table inventory differs.');
}
foreach ($baseline as $table => $before) {
$rows = $copy->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
if (count($rows) !== $before['rows'] || ! hash_equals($before['sha256'], hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)))) {
throw new LogicException('Restored replenishment backup data differs.');
}
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'restored_tables_identical' => count($baseline),
'source_database_or_settings_changed' => false, 'business_commands' => false];
} finally {
$copy = null;
if ($createdDatabase) {
$admin->exec('DROP DATABASE "'.$database.'" WITH (FORCE)');
}
if ($createdRole) {
$admin->exec('DROP ROLE "'.$role.'"');
}
}
$result['temporary_database_and_role_removed'] = true;
file_put_contents($root.'/docs/proofs/replenishment-task-recovery.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;