Files
compras/tests/Support/standalone-pilot-recovery-worker.php
T
nala 30bfb1a773
tests / ci (push) Canceled after 0s
commit compras3 2911
2026-11-29 16:03:11 +02:00

115 lines
6.9 KiB
PHP

<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = getenv('DB_DATABASE');
$pilot = in_array('--install-authorized-pilot', $argv, true);
$root = dirname(__DIR__, 2);
$destinationValid = preg_match('/^compras_private_restore_([a-f0-9]{12})$/D', $database ?: '', $match)
&& getenv('DB_USERNAME') === 'compras_private_app_'.$match[1];
if ($pilot) {
$approval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
$destinationValid = ($approval['state'] ?? null) === 'approved' && ($approval['scope'] ?? null) === 'pilot_schema_and_pinned_runtime_only'
&& hash_equals($approval['proposal_sha256'], hash_file('sha256', $root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'))
&& ($source['APP_ENV'] ?? null) === 'payable-testing' && realpath($source['HOST_ROOT']) === realpath($root)
&& preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database ?: '', $sourceMatch)
&& $database === $source['DB_DATABASE'] && getenv('DB_USERNAME') === 'payable_qa_'.$sourceMatch[1]
&& getenv('DB_USERNAME') === $source['DB_USERNAME'] && getenv('DB_PORT') === $source['DB_PORT']
&& realpath(getenv('COMPRAS_RUNTIME_ROOT')) === realpath($plan['runtime']['private_installation_directory'])
&& getenv('COMPRAS_RUNTIME_SHA256') === $plan['runtime']['manifest_sha256'];
}
if (! $destinationValid || getenv('DB_HOST') !== '127.0.0.1'
|| getenv('APP_ENV') !== 'private-recovery' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'false'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'true' || getenv('QUEUE_CONNECTION') !== 'null') {
throw new LogicException('PRIVATE_RECOVERY_DESTINATION_REQUIRED');
}
$proposal = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-recovery-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$identity = $db->selectOne('SELECT current_database() AS database_name,current_user AS role_name');
if ($identity->database_name !== $database || $identity->role_name !== getenv('DB_USERNAME')) {
throw new LogicException('PRIVATE_RECOVERY_IDENTITY_MISMATCH');
}
$baseline = null;
if (getenv('COMPRAS_INSTALLATION_BASELINE') !== false) {
$baselinePath = realpath(getenv('COMPRAS_INSTALLATION_BASELINE') ?: '');
$boundary = realpath('C:/laragon/data/sgf-tempo/backups');
if ($baselinePath === false || $boundary === false || ! str_starts_with(str_replace('\\', '/', $baselinePath), str_replace('\\', '/', $boundary).'/')) {
throw new LogicException('PILOT_INSTALLATION_PRIVATE_BASELINE_REQUIRED');
}
$baseline = json_decode(file_get_contents($baselinePath), true, 128, JSON_THROW_ON_ERROR);
$db->beginTransaction();
$db->statement("SET LOCAL lock_timeout = '5s'");
$tables = array_keys($baseline['columns']);
$tables = array_values(array_diff($tables, ['tenants']));
array_unshift($tables, 'tenants');
$db->statement('LOCK TABLE '.implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $tables)).' IN SHARE ROW EXCLUSIVE MODE');
}
$frames = static function () use ($db, $baseline): array {
$out = [];
foreach ($baseline['columns'] as $table => $names) {
$quoted = implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = array_column($db->select('SELECT row_to_json(t)::text AS row FROM (SELECT '.$quoted.' FROM "'.str_replace('"', '""', $table).'") t ORDER BY row_to_json(t)::text'), 'row');
$out[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
}
return $out;
};
if ($baseline !== null && $frames() !== $baseline['frames']) {
throw new LogicException('PILOT_CHANGED_AFTER_VERIFIED_BACKUP');
}
$paths = array_keys($proposal['selected_normal_migrations_in_restored_copy_only']);
foreach ($proposal['selected_normal_migrations_in_restored_copy_only'] as $path => $hash) {
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$path))) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_CHANGED');
}
}
if (Artisan::call('migrate', ['--path' => $paths, '--force' => true, '--no-interaction' => true]) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_FAILED');
}
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Authorised private recovery verification', '--reason' => 'Owner authorised upgrade rehearsal on private restored copy only',
'--reuse-components' => true];
$invoke = static function (array $arguments): array {
if (Artisan::call('compras:runtime:prepare', $arguments) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_PREPARATION_FAILED');
}
return json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
};
$preview = $invoke($arguments);
$applied = $invoke($arguments + ['--apply' => true]);
$repeated = $invoke($arguments + ['--apply' => true]);
if ($preview['written'] !== false || $applied['state'] !== 'prepared' || $repeated['state'] !== 'already_prepared'
|| $repeated['written'] !== false || $db->table('compras_runtime_installations')->count() !== 1) {
throw new LogicException('PRIVATE_RECOVERY_REPLAY_FAILED');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->configure($db);
if ($baseline !== null) {
$after = $frames();
$before = $baseline['frames'];
unset($after['migrations'], $before['migrations']);
$expected = [...$baseline['migrations'], ...array_map(static fn ($path) => basename($path, '.php'), $paths)];
sort($expected, SORT_STRING);
if ($before !== $after || $db->table('migrations')->orderBy('migration')->pluck('migration')->all() !== $expected) {
throw new LogicException('PILOT_INSTALLATION_CONSERVATION_FAILED');
}
$db->commit();
}
echo json_encode(['verified' => true, 'selected_migrations' => count($paths), 'available_modules' => count(StandaloneRuntime::FEATURES),
'one_receipt_replay_without_write' => true, 'configuration_stays_disabled' => config('standalone-runtime.enabled') === false,
'existing_components' => $preview['existing_components']], JSON_THROW_ON_ERROR).PHP_EOL;