commit compras3 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 16:03:11 +02:00
parent 7da8d6c87a
commit 30bfb1a773
72 changed files with 10998 additions and 98 deletions
+169
View File
@@ -0,0 +1,169 @@
<?php
use App\Services\StandaloneArtifact;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (! in_array('--apply-authorized', $argv, true)) {
throw new LogicException('EXPLICIT_STANDALONE_ACTIVATION_REQUIRED');
}
$proposalPath = $root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json';
$plan = json_decode(file_get_contents($proposalPath), true, 512, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$resultPath = $root.'/docs/proofs/compras-standalone-pilot-activation.json';
if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== $plan['scope']
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $proposalPath)) || is_file($resultPath)) {
throw new LogicException('STANDALONE_ACTIVATION_AUTHORIZATION_OR_PREVIOUS_RESULT');
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$manifestPath = $root.'/public/build/manifest.json';
$before = file_get_contents($settingsPath);
$manifestBefore = file_get_contents($manifestPath);
$settings = json_decode($before, true, 32, JSON_THROW_ON_ERROR);
if (! hash_equals($plan['active_settings_sha256'], hash('sha256', $before))
|| ! hash_equals($plan['frontend']['previous_manifest_sha256'], hash('sha256', $manifestBefore))
|| $settings['APP_ENV'] !== 'payable-testing' || $settings['DB_HOST'] !== '127.0.0.1'
|| realpath($settings['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'], $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('STANDALONE_ACTIVATION_TARGET_CHANGED');
}
(new StandaloneArtifact)->verify($plan['runtime_directory'], $plan['runtime_manifest']);
$assets = $root.'/'.$plan['frontend']['candidate_root'];
$manifest = file_get_contents($assets.'/manifest.json');
if (! hash_equals($plan['frontend']['manifest_sha256'], hash('sha256', $manifest))) {
throw new LogicException('STANDALONE_ACTIVATION_FRONTEND_CHANGED');
}
foreach ($plan['frontend']['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('STANDALONE_ACTIVATION_ASSET_CONFLICT');
}
}
$after = [...$settings, ...$plan['proposed_runtime_settings']];
$protectedBefore = $settings;
$protectedAfter = $after;
foreach (array_keys($plan['proposed_runtime_settings']) as $key) {
unset($protectedBefore[$key], $protectedAfter[$key]);
}
if ($protectedBefore !== $protectedAfter || $settings['PAYABLE_SOURCE_INSTANCE'] !== $after['PAYABLE_SOURCE_INSTANCE']) {
throw new LogicException('STANDALONE_ACTIVATION_UNRELATED_SETTINGS');
}
$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
$directory = 'C:/laragon/data/compras/backups/activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($directory, 0700, true)) {
throw new LogicException('STANDALONE_ACTIVATION_BACKUP_UNAVAILABLE');
}
file_put_contents($directory.'/settings.before.private.json', $before, LOCK_EX);
file_put_contents($directory.'/manifest.before.json', $manifestBefore, LOCK_EX);
if (! hash_equals(hash('sha256', $before), hash_file('sha256', $directory.'/settings.before.private.json'))
|| ! hash_equals(hash('sha256', $manifestBefore), hash_file('sha256', $directory.'/manifest.before.json'))) {
throw new RuntimeException('STANDALONE_ACTIVATION_BACKUP_INCOMPLETE');
}
$envHash = hash_file('sha256', $root.'/.env');
$db = new PDO('pgsql:host=127.0.0.1;port='.(int) $settings['DB_PORT'].';dbname='.$settings['DB_DATABASE'],
$settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$frames = static function () use ($db): array {
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$result = [];
foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
$quoted = '"'.str_replace('"', '""', $table).'"';
$rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$result[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
$db->commit();
return $result;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
};
$baseline = $frames();
file_put_contents($directory.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
$replace = static function (string $path, string $bytes, string $expected): void {
if (! hash_equals($expected, hash_file('sha256', $path))) {
throw new LogicException('STANDALONE_ACTIVATION_CONCURRENT_EDIT');
}
$temporary = $path.'.standalone-'.bin2hex(random_bytes(6)).'.tmp';
$stream = fopen($temporary, 'x');
if ($stream === false) {
throw new RuntimeException('STANDALONE_ACTIVATION_STAGE_FAILED');
}
try {
if (fwrite($stream, $bytes) !== strlen($bytes) || ! fflush($stream)) {
throw new RuntimeException('STANDALONE_ACTIVATION_STAGE_INCOMPLETE');
}
} finally {
fclose($stream);
}
if (! hash_equals($expected, hash_file('sha256', $path)) || ! rename($temporary, $path)) {
throw new RuntimeException('STANDALONE_ACTIVATION_ATOMIC_REPLACE_FAILED');
}
};
$manifestChanged = $settingsChanged = false;
$report = ['date' => gmdate('c'), 'state' => 'in_progress', 'authorization' => 'compras-standalone-pilot-activation-authorization.json',
'target' => $plan['target'], 'backup_directory' => $directory, 'runtime_manifest' => $plan['runtime_manifest'],
'frontend_manifest' => $plan['frontend']['manifest_sha256'], 'new_grants_or_users' => false, 'business_commands' => false];
file_put_contents($directory.'/progress.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
try {
foreach ($plan['frontend']['files'] as $file => $hash) {
$destination = $root.'/public/build/'.$file;
if (! is_file($destination)) {
$out = fopen($destination, 'x');
if ($out === false) {
throw new RuntimeException('STANDALONE_ACTIVATION_ASSET_WRITE');
}
$bytes = file_get_contents($assets.'/'.$file);
try {
if (fwrite($out, $bytes) !== strlen($bytes)) {
throw new RuntimeException('STANDALONE_ACTIVATION_ASSET_INCOMPLETE');
}
} finally {
fclose($out);
}
}
if (! hash_equals($hash, hash_file('sha256', $destination))) {
throw new LogicException('STANDALONE_ACTIVATION_ASSET_COPY_CHANGED');
}
}
$replace($manifestPath, $manifest, hash('sha256', $manifestBefore));
$manifestChanged = true;
$replace($settingsPath, $encoded, hash('sha256', $before));
$settingsChanged = true;
$http = [];
foreach (['/avaliar', '/login'] as $path) {
$body = file_get_contents($plan['target'].$path, false, stream_context_create(['http' => ['timeout' => 5, 'follow_location' => 0, 'ignore_errors' => true]]));
if (! is_string($body) || ! preg_match('/^HTTP\/\S+ (200|302)\b/', $http_response_header[0] ?? '', $status)) {
throw new RuntimeException('STANDALONE_ACTIVATION_HTTP_FAILED');
}
$http[$path] = (int) $status[1];
}
if ($frames() !== $baseline || hash_file('sha256', $root.'/.env') !== $envHash
|| json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
throw new LogicException('STANDALONE_ACTIVATION_CONSERVATION_FAILED');
}
$report += ['capabilities_enabled' => count($plan['feature_names']), 'assets_verified' => count($plan['frontend']['files']),
'all_database_tables_preserved' => count($baseline), 'unrelated_settings_preserved' => true, 'source_instance_preserved' => true,
'public_env_preserved' => true, 'http' => $http, 'public_domain_runtime_activated' => false];
$report['state'] = 'passed';
} catch (Throwable $error) {
if ($settingsChanged) {
$replace($settingsPath, $before, hash('sha256', $encoded));
}
if ($manifestChanged) {
$replace($manifestPath, $manifestBefore, hash('sha256', $manifest));
}
$report['state'] = 'failed_configuration_and_manifest_restored';
$report['failure_class'] = get_class($error);
throw $error;
} finally {
file_put_contents($directory.'/result.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($resultPath, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
}
echo json_encode(['state' => $report['state'], 'capabilities_enabled' => $report['capabilities_enabled'],
'assets_verified' => $report['assets_verified'], 'database_tables_preserved' => $report['all_database_tables_preserved'],
'business_commands' => false, 'new_grants' => false], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,62 @@
<?php
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('READ_ONLY_ACTIVATION_PREFLIGHT_REQUIRED');
}
$root = dirname(__DIR__);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json'), true, 512, JSON_THROW_ON_ERROR);
$sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$source = json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR);
if (! hash_equals($plan['active_settings_sha256'], hash_file('sha256', $sourcePath))
|| $source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1'
|| realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| trim($source['PAYABLE_SOURCE_INSTANCE'] ?? '') === '') {
throw new LogicException('ACTIVATION_PREFLIGHT_SOURCE_CHANGED');
}
$assets = $root.'/'.$plan['frontend']['candidate_root'];
if (! hash_equals($plan['frontend']['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
|| ! hash_equals($plan['frontend']['previous_manifest_sha256'], hash_file('sha256', $root.'/public/build/manifest.json'))) {
throw new LogicException('ACTIVATION_PREFLIGHT_MANIFEST_CHANGED');
}
foreach ($plan['frontend']['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('ACTIVATION_PREFLIGHT_ASSET_MISMATCH');
}
}
$environment = [...$source, ...$plan['proposed_runtime_settings'], 'APP_ENV' => 'pilot-readonly', 'APP_DEBUG' => 'false',
'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-pilot-readonly-config.php', 'LOG_CHANNEL' => 'stderr'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
if ($db->selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('ACTIVATION_PREFLIGHT_DATABASE_NOT_READ_ONLY');
}
$runtime = app(StandaloneRuntime::class);
$runtime->configure($db);
$runtime->assertLoadedPackages();
if (! $runtime->enabled() || count(array_filter(StandaloneRuntime::FEATURES, fn ($name) => $runtime->requested($name))) !== 24) {
throw new LogicException('ACTIVATION_PREFLIGHT_CAPABILITIES_INCOMPLETE');
}
if (! hash_equals($plan['active_settings_sha256'], hash_file('sha256', $sourcePath))) {
throw new LogicException('ACTIVATION_PREFLIGHT_SETTINGS_CHANGED');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'database_enforced_read_only' => true,
'all_24_capabilities_start_with_pinned_installed_packages' => true, 'source_instance_preserved' => true,
'frontend_assets_verified' => count($plan['frontend']['files']), 'active_settings_changed' => false,
'assets_published' => false, 'new_grants_or_business_commands' => false];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-activation-preflight.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,70 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use App\Services\StandaloneSchema;
use Illuminate\Database\PostgresConnection;
use Illuminate\Support\Str;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('EXPLICIT_READ_ONLY_CHECK_REQUIRED');
}
$root = dirname(__DIR__);
$proof = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation.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);
if ($proof['state'] !== 'passed' || $proof['pilot_activation'] !== false || $source['APP_ENV'] !== 'payable-testing'
|| $source['DB_HOST'] !== '127.0.0.1' || realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('PILOT_INSTALLATION_READ_TARGET');
}
$pdo = new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$source['DB_DATABASE'],
$source['DB_USERNAME'], $source['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->beginTransaction();
try {
$pdo->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$db = new PostgresConnection($pdo, $source['DB_DATABASE'], '', ['driver' => 'pgsql', 'search_path' => 'public']);
$settings = ['enabled' => true, 'root' => $proof['runtime_directory'], 'manifest_sha256' => $proof['runtime_manifest'],
'installation_id' => $proof['installation_id'], 'features' => array_fill_keys(StandaloneRuntime::FEATURES, true)];
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->assertInstallation($db);
StandaloneSchema::verify($db->getSchemaBuilder(), $settings['features']);
if ((int) $pdo->query('SELECT count(*) FROM compras_runtime_installations')->fetchColumn() !== 1
|| filter_var($source['COMPRAS_RUNTIME_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
throw new LogicException('PILOT_INSTALLATION_RECEIPT_OR_ACTIVATION');
}
$wrong = $settings;
$wrong['installation_id'] = Str::uuid()->toString();
$rejected = false;
try {
(new StandaloneRuntime($wrong, new StandaloneArtifact))->assertInstallation($db);
} catch (LogicException $error) {
$rejected = $error->getMessage() === 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH';
}
if (! $rejected) {
throw new LogicException('PILOT_INSTALLATION_WRONG_ID_ACCEPTED');
}
$pdo->commit();
} finally {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
}
$http = [];
foreach (['/avaliar', '/login'] as $path) {
$headers = [];
$context = stream_context_create(['http' => ['timeout' => 5, 'follow_location' => 0, 'ignore_errors' => true]]);
$body = file_get_contents('http://127.0.0.1:8005'.$path, false, $context);
$headers = $http_response_header ?? [];
if (! is_string($body) || ! preg_match('/^HTTP\/\S+ (200|302)\b/', $headers[0] ?? '', $status)) {
throw new LogicException('PILOT_INSTALLATION_HTTP_UNAVAILABLE');
}
$http[$path] = (int) $status[1];
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'read_only_database_transaction' => true,
'receipt_and_non_elevated_binding_verified' => true, 'wrong_installation_id_refused' => true,
'all_24_module_schemas_verified' => true, 'runtime_activation_stays_disabled' => true, 'http' => $http,
'business_commands' => false, 'permission_changes' => false];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-installation-check.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+103
View File
@@ -0,0 +1,103 @@
<?php
// In-process GET validation only: existing actors, array sessions, pre-execution SQL write refusal.
// No routes, login shortcuts, users, grants or changes are installed by this checker.
use App\Models\User;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('READ_ONLY_PROFILE_CHECK_REQUIRED');
}
$root = dirname(__DIR__);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json'), true, 512, JSON_THROW_ON_ERROR);
$result = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation.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);
if ($result['state'] !== 'passed' || ($source['COMPRAS_RUNTIME_ENABLED'] ?? null) !== 'true'
|| $source['COMPRAS_RUNTIME_INSTALLATION_ID'] !== $plan['installation_id'] || $source['DB_HOST'] !== '127.0.0.1'
|| $source['APP_ENV'] !== 'payable-testing' || realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('ACTIVATED_PILOT_PROFILE_TARGET');
}
$environment = [...$source, 'PGOPTIONS' => '', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '',
'APP_DEBUG' => 'false', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null',
'MAIL_MAILER' => 'array', 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-profile-check.php', 'LOG_CHANNEL' => 'stderr'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$kernel->bootstrap();
$onlyReads = static function (string $sql): void {
if (! preg_match('/^\s*(SELECT\b|SHOW\b|SET\s+LOCAL\b|SET\s+CONSTRAINTS\b)/i', $sql)) {
throw new LogicException('PROFILE_CHECK_SQL_WRITE_REFUSED');
}
};
foreach (['UPDATE users SET name=name', 'DELETE FROM users', 'INSERT INTO users DEFAULT VALUES'] as $forbidden) {
$refused = false;
try {
$onlyReads($forbidden); // Test the guard without sending the statement to PostgreSQL.
} catch (LogicException $error) {
$refused = $error->getMessage() === 'PROFILE_CHECK_SQL_WRITE_REFUSED';
}
if (! $refused) {
throw new LogicException('PROFILE_CHECK_GUARD_REGRESSION');
}
}
DB::connection()->beforeExecuting($onlyReads);
$frames = static function (): array {
$out = [];
foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.str_replace('"', '""', $table->tablename).'" t ORDER BY row_to_json(t)::text');
$out[$table->tablename] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $out;
};
$before = $frames();
app(StandaloneRuntime::class)->assertLoadedPackages();
$results = [];
foreach (['admin', 'procurement', 'finance', 'warehouse'] as $role) {
$actor = User::query()->where('email', 'avaliacao-'.$role.'@example.test')->firstOrFail();
foreach (['/dashboard', '/requisicoes', '/projectos-imobilizado', '/ordens-operacionais', '/administracao/financeiro',
'/administracao/prazos-aprovacao', '/administracao/revisao-urgencias', '/requisicoes/urgencias/revisoes',
'/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa'] as $path) {
$app->forgetScopedInstances();
$request = Request::create('http://127.0.0.1:8005'.$path, 'GET', server: ['REMOTE_ADDR' => '127.0.0.1',
'HTTP_ACCEPT' => 'application/json', 'HTTP_X_INERTIA' => 'true']);
$app->instance('request', $request);
$request->headers->set('X-Inertia-Version', app(\App\Http\Middleware\HandleInertiaRequests::class)->version($request));
Auth::guard('web')->setUser($actor);
$session = app('session')->driver();
$session->start();
$session->put('work_context', ['user_id' => $actor->id, 'tenant_id' => $actor->tenant_id, 'key' => 'procurement.internal']);
$request->setLaravelSession($session);
$request->setUserResolver(fn () => $actor);
$response = $kernel->handle($request);
$status = $response->getStatusCode();
if (! in_array($status, [200, 403], true) || ($path === '/administracao/financeiro' && $status !== ($role === 'admin' ? 200 : 403))) {
throw new LogicException('PROFILE_CHECK_UNEXPECTED_STATUS:'.$role.':'.$path.':'.$status);
}
$page = json_decode($response->getContent(), true);
$navigation = $page['props']['commonFinanceNavigation'] ?? null;
if ($status === 200 && is_array($navigation) && $navigation['configuration'] !== ($role === 'admin')) {
throw new LogicException('PROFILE_CHECK_CONFIGURATION_VISIBILITY:'.$role);
}
$results[] = ['role' => $role, 'path' => $path, 'status' => $status, 'finance_navigation' => $navigation];
}
}
if ($frames() !== $before) {
throw new LogicException('PROFILE_CHECK_DATA_CHANGED');
}
$proof = ['date' => gmdate('c'), 'state' => 'passed', 'mode' => 'in_process_gets_existing_actors_array_sessions',
'sql_writes_refused_before_execution' => true, 'write_guard_regression_cases' => 3, 'all_tables_preserved' => count($before),
'new_grants_or_users' => false, 'business_commands' => false, 'results' => $results];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-profiles.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['state' => 'passed', 'profile_get_checks' => count($results), 'sql_write_guard_and_conservation' => true,
'new_grants_or_users' => false], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -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;
@@ -0,0 +1,53 @@
<?php
use App\Services\StandaloneComponentSchema;
use Illuminate\Database\PostgresConnection;
// Metadata only. No application bootstrap, migrations, business rows or configuration writes.
if (! in_array('--inspect-pilot-schema', $argv, true)) {
throw new LogicException('Explicit read-only pilot schema inspection required.');
}
$root = dirname(__DIR__);
require $root.'/vendor/autoload.php';
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|| ($settings['DB_USERNAME'] ?? '') !== 'payable_qa_'.$match[1]
|| ! is_scalar($settings['DB_PORT'] ?? null) || ! ctype_digit((string) $settings['DB_PORT'])
|| (int) $settings['DB_PORT'] < 1 || (int) $settings['DB_PORT'] > 65535) {
throw new LogicException('Pilot metadata target identity mismatch.');
}
$db = new PDO('pgsql:host=127.0.0.1;port='.(int) $settings['DB_PORT'].';dbname='.$settings['DB_DATABASE'],
$settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity = $db->query('SELECT current_database() AS database_name, current_user AS role_name')->fetch(PDO::FETCH_ASSOC);
if ($identity['database_name'] !== $settings['DB_DATABASE'] || $identity['role_name'] !== $settings['DB_USERNAME']) {
throw new LogicException('Pilot metadata connection identity mismatch.');
}
$tables = [];
foreach ($db->query("SELECT table_name,column_name,data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,ordinal_position")->fetchAll(PDO::FETCH_ASSOC) as $row) {
$tables[$row['table_name']][] = ['name' => $row['column_name'], 'type' => $row['data_type'], 'nullable' => $row['is_nullable'] === 'YES'];
}
$migrations = $db->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN);
$connection = new PostgresConnection($db, $settings['DB_DATABASE'], '', ['driver' => 'pgsql', 'search_path' => 'public']);
$profiles = [];
foreach (array_keys(StandaloneComponentSchema::GROUPS) as $group) {
$profiles[$group] = StandaloneComponentSchema::inspect($connection, $group);
}
$report = ['checked_at' => gmdate('c'), 'environment' => 'http://127.0.0.1:8005', 'inspection_only' => true,
'consistent_read_only' => true, 'business_values_read' => false, 'configuration_or_permission_changes' => false,
'tables' => $tables, 'applied_migrations' => $migrations, 'component_profiles' => $profiles];
$db->commit();
$output = $root.'/docs/proofs/standalone-pilot-schema-inventory.json';
file_put_contents($output, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['inspection_only' => true, 'table_count' => count($tables), 'migrations' => count($migrations),
'business_values_read' => false, 'component_profiles' => $profiles,
'proof' => 'docs/proofs/standalone-pilot-schema-inventory.json'], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
+51 -17
View File
@@ -9,12 +9,17 @@ import { createServer } from 'node:net';
const id = crypto.randomBytes(6).toString('hex');
const workspace = path.resolve('C:/laragon/www/compras');
const standaloneOnly = process.argv.includes('--standalone-runtime-only');
const standaloneBusiness = process.argv.includes('--standalone-business-only');
if (standaloneOnly && process.argv.slice(2).some(flag => flag !== '--standalone-runtime-only')) throw Error('Standalone composition requires its own isolated invocation');
if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== '--standalone-business-only')) throw Error('Standalone business regression requires its own isolated invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-3320fac5a70fe44e');
const standalonePin = '3320fac5a70fe44ed54e11af90385b5da6b204ef854984cd934882a4378211e1';
const standaloneArchivePin = 'a544d5930feb916c4d4941ed8ef0b453985c1629720e9d0224bdbf0d322fb536';
const financePreview = process.argv.includes('--standalone-finance-preview');
const componentProfile = process.argv.includes('--standalone-component-profile');
if (componentProfile && (!standaloneOnly || financePreview)) throw Error('Component profile requires its own standalone invocation');
if (financePreview && !standaloneOnly) throw Error('Finance preview requires the isolated standalone runtime');
const standaloneUpgrade = process.argv.includes('--standalone-upgrade-only');
const standaloneBusiness = process.argv.includes('--standalone-business-only') || standaloneUpgrade;
if (standaloneOnly && process.argv.slice(2).some(flag => !['--standalone-runtime-only', '--standalone-finance-preview', '--standalone-component-profile'].includes(flag))) throw Error('Standalone composition requires its own isolated invocation');
if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== (standaloneUpgrade ? '--standalone-upgrade-only' : '--standalone-business-only'))) throw Error('Standalone business regression requires its own isolated invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-80483320a54af6f1');
const standalonePin = '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7';
const standaloneArchivePin = 'bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76';
const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes='));
const reviewDurationMinutes = reviewDurationArgs.length === 0 ? 20 : Number(reviewDurationArgs[0].slice('--review-minutes='.length));
if (reviewDurationArgs.length > 1 || !Number.isInteger(reviewDurationMinutes) || reviewDurationMinutes < 1 || reviewDurationMinutes > 60 || (reviewDurationArgs.length > 0 && !process.argv.includes('--native-review'))) throw Error('Native review duration must be one explicit value from1to60minutes');
@@ -132,12 +137,19 @@ try {
if (fs.lstatSync(archive).isSymbolicLink() || crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== standaloneArchivePin) throw Error('Pinned standalone archive mismatch');
activeStandaloneRoot = path.join(root, 'runtime');
fs.mkdirSync(activeStandaloneRoot);
const code = '$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==67||!$z->extractTo($argv[2]))throw new LogicException("Owned candidate extraction failed");$z->close();echo "extracted";';
const code = '$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==68||!$z->extractTo($argv[2]))throw new LogicException("Owned candidate extraction failed");$z->close();echo "extracted";';
const extracted = spawnSync('php', ['-r', code, archive, activeStandaloneRoot], { windowsHide: true, encoding: 'utf8' });
if (extracted.status !== 0 || extracted.stdout !== 'extracted') throw Error('Owned standalone extraction failed');
verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 66);
verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 67);
const uiTest = spawnSync(process.execPath, ['--test', 'tests/Support/financial-preparation.test.mjs'], {
cwd: workspace, windowsHide: true, encoding: 'utf8',
env: { ...process.env, COMPRAS_FINANCE_UI_PACKAGE_ROOT: activeStandaloneRoot },
});
if (uiTest.status !== 0) throw Error('Pinned financial preparation UI regression failed: '+(uiTest.stdout || uiTest.stderr || ''));
console.log(JSON.stringify({ pinned_financial_preparation_tests: 10, result: 'passed', extracted_runtime: true }));
}
const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', APP_KEY: 'base64:'+crypto.randomBytes(32).toString('base64'), DB_CONNECTION: 'pgsql', DB_URL: '', DB_HOST: '127.0.0.1', DB_PORT: '55439',
const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', COMPRAS_RUNTIME_ENABLED: 'false', COMPRAS_RUNTIME_PREPARE_ONLY: 'false', COMPRAS_RUNTIME_SYNTHETIC_ONLY: 'true', APP_KEY: 'base64:'+crypto.randomBytes(32).toString('base64'), DB_CONNECTION: 'pgsql', DB_URL: '', DB_HOST: '127.0.0.1', DB_PORT: '55439',
DB_DATABASE: database, DB_USERNAME: role, DB_PASSWORD: password, CACHE_STORE: 'array', SESSION_DRIVER: 'array',
MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null',
COMMON_BUDGET_PATH: standaloneOnly || standaloneBusiness ? path.join(activeStandaloneRoot, 'budget-control') : frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control',
@@ -160,12 +172,14 @@ try {
delete environment.COMMON_FINANCE_BUNDLE_SHA256;
if (standaloneOnly || standaloneBusiness) {
environment.COMPRAS_RUNTIME_ENABLED = 'false';
environment.COMPRAS_RUNTIME_PREPARE_ONLY = 'true';
environment.COMMON_PAYABLES_PATH = path.join(activeStandaloneRoot, 'payables');
environment.COMMON_PURCHASING_PATH = path.join(activeStandaloneRoot, 'purchasing');
environment.COMPRAS_RUNTIME_ROOT = activeStandaloneRoot;
environment.COMPRAS_RUNTIME_SHA256 = standalonePin;
environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness ? '1' : '0';
environment.COMPRAS_STANDALONE_UPGRADE_QA = standaloneUpgrade ? '1' : '0';
}
if (frozenRuntime) {
environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot;
@@ -220,15 +234,23 @@ try {
if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition');
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=native expiry returns the same request');
}
if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/StandaloneBusinessCompositionTest.php');
if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', standaloneUpgrade ? 'tests/Feature/StandaloneComponentUpgradeTest.php' : 'tests/Feature/StandaloneBusinessCompositionTest.php');
const result = spawnSync('php', args, {
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
});
if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((result.stderr || '').replaceAll(password, '[private]'));
process.exitCode = result.status === 0 ? 0 : 1;
if (result.status === 0 && standaloneOnly) {
const standaloneEnvironment = { ...environment, APP_ENV: 'standalone-qa',
if (result.status === 0 && componentProfile) {
const profile = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, 'prepare-component-profile'], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'standalone-qa', SGC_STANDALONE_QA_ROOT: root },
});
process.stdout.write(profile.stdout || '');
process.stderr.write(profile.stderr || '');
if (profile.status !== 0 || !(profile.stdout || '').includes('synthetic_canonical_component_profiles')) throw Error('Canonical component profile fixture failed');
}
if (result.status === 0 && standaloneOnly && !componentProfile) {
const standaloneEnvironment = { ...environment, APP_ENV: 'standalone-qa', COMPRAS_RUNTIME_PREPARE_ONLY: 'false',
COMPRAS_RUNTIME_ROOT: activeStandaloneRoot, COMPRAS_RUNTIME_SHA256: standalonePin,
COMPRAS_RUNTIME_INSTALLATION_ID: crypto.randomUUID(), SGC_STANDALONE_QA_ROOT: root,
PAYABLE_SOURCE_INSTANCE: `standalone-synthetic-${id}`,
@@ -238,11 +260,11 @@ try {
for (const feature of ['BUDGET_DISTRIBUTIONS', 'REQUISITION_ACCOUNTS', 'REQUISITION_EXPIRY', 'EXPENSE_ALLOCATIONS',
'AGREEMENT_LIMITS', 'ORDER_PARTS', 'IMPORT_TARIFFS', 'IMPORT_LEGAL', 'IMPORT_DOSSIER', 'IMPORT_BANK_SUPPORT',
'IMPORT_READINESS', 'IMPORT_ESTIMATES', 'IMPORT_LANDED_COSTS', 'SUPPLIER_PAYABLES', 'GENERAL_LEDGER',
'SUPPLIER_SETTLEMENTS', 'GENERAL_LEDGER_CYCLE']) standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true';
'SUPPLIER_SETTLEMENTS', 'GENERAL_LEDGER_CYCLE', 'FINANCE_CONFIGURATION']) standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true';
for (const mode of ['prepare', 'verify']) {
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: mode === 'verify' ? 'true' : 'false' },
env: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: mode === 'verify' ? 'true' : 'false', COMPRAS_RUNTIME_PREPARE_ONLY: mode === 'prepare' ? 'true' : 'false' },
});
process.stdout.write((check.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(password, '[private]'));
@@ -252,9 +274,10 @@ try {
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
}
if (process.exitCode === 0) {
for (const mode of ['reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old']) {
for (const mode of ['reject-foreign', 'reject-pin', 'reject-prepare-pin', 'reject-dependency', 'reject-old']) {
const invalid = { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' };
if (mode === 'reject-pin') invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64);
if (mode === 'reject-prepare-pin') { invalid.COMPRAS_RUNTIME_ENABLED = 'false'; invalid.COMPRAS_RUNTIME_PREPARE_ONLY = 'true'; }
if (mode === 'reject-pin' || mode === 'reject-prepare-pin') invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64);
if (mode === 'reject-dependency') invalid.COMPRAS_IMPORT_DOSSIER_ENABLED = 'false';
if (mode === 'reject-old') {
invalid.COMPRAS_RUNTIME_ROOT = path.join(workspace, 'storage/framework/testing/compras-standalone-730845de0bddd000');
@@ -289,7 +312,7 @@ try {
if (mode === 'rebind') restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', restoreDatabase, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...restored, COMPRAS_RUNTIME_ENABLED: mode === 'rebind' ? 'false' : 'true' },
env: { ...restored, COMPRAS_RUNTIME_ENABLED: mode === 'rebind' ? 'false' : 'true', COMPRAS_RUNTIME_PREPARE_ONLY: mode === 'rebind' ? 'true' : 'false' },
});
process.stdout.write((check.stdout || '').replaceAll(restoredPassword, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(restoredPassword, '[private]'));
@@ -299,6 +322,17 @@ try {
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
}
}
if (process.exitCode === 0) {
const { verifyConfigurationConcurrency } = await import('./standalone-configuration-race.mjs');
await verifyConfigurationConcurrency(workspace, root, database, { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' });
}
if (process.exitCode === 0 && financePreview) {
const { reviewStandaloneFinance } = await import('./standalone-finance-preview.mjs');
await reviewStandaloneFinance({ workspace, root, database,
environment: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' },
assets: path.join(privateParent, 'sgc-standalone-finance-help-qa-20261129'),
manifestPin: '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b' });
}
}
if (result.status === 0 && raceOnly) {
const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], {
+50
View File
@@ -0,0 +1,50 @@
import fs from 'node:fs';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
export async function verifyConfigurationConcurrency(workspace, root, database, environment) {
if (environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false') throw Error('Verified standalone configuration required');
const worker = (mode, round) => {
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode, round], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment,
});
if (result.status !== 0) throw Error('Standalone configuration fixture/read worker failed');
return JSON.parse(result.stdout.trim());
};
for (const round of ['same', 'different']) {
if (worker('prepare-configuration-race', round).prepared !== true) throw Error('Race fixture not prepared');
const children = [0, 1].map(index => {
const child = spawn('php', ['tests/Support/standalone-runtime-worker.php', database, 'run-configuration-race', round, String(index)], {
cwd: workspace, windowsHide: true, env: environment,
});
let output = '';
child.stdout.on('data', chunk => { output += chunk.toString(); });
child.stderr.on('data', () => {});
const complete = new Promise(resolve => child.on('close', code => resolve({ code, output })));
return { child, complete };
});
try {
const until = Date.now() + 15000;
while (![0, 1].every(index => fs.existsSync(path.join(root, `configuration-${round}-${index}.ready`)))) {
if (Date.now() > until || children.some(({ child }) => child.exitCode !== null)) throw Error('Concurrent candidate workers did not reach the gate');
await new Promise(resolve => setTimeout(resolve, 20));
}
fs.writeFileSync(path.join(root, `configuration-${round}.go`), 'go', { flag: 'wx' });
const results = await Promise.race([
Promise.all(children.map(({ complete }) => complete)),
new Promise((_, reject) => { const timer = setTimeout(() => reject(Error('Concurrent candidate writers timed out')), 20000); timer.unref(); }),
]);
if (results.some(result => result.code !== 0)) throw Error('Concurrent candidate writer failed');
const outcomes = results.map(result => JSON.parse(result.output.trim()));
if (outcomes.filter(result => result.state === 'saved' && result.replayed === false).length !== 1
|| (round === 'same' ? outcomes.filter(result => result.state === 'saved' && result.replayed === true).length !== 1
: outcomes.filter(result => result.state === 'stale').length !== 1)) throw Error('Unexpected concurrent configuration outcome');
const proof = worker('read-configuration-race', round);
if (proof.verified !== true) throw Error('Concurrent configuration conservation missing');
console.log(JSON.stringify({ standalone_configuration_concurrency: true, ...proof, outcomes }));
} finally {
for (const { child } of children) if (child.exitCode === null) child.kill();
await Promise.all(children.map(({ complete }) => complete));
}
}
}
+69
View File
@@ -0,0 +1,69 @@
// Called only by the owned standalone QA runner after package/schema/recovery checks.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { createServer } from 'node:net';
export async function reviewStandaloneFinance({ workspace, root, database, environment, assets, manifestPin }) {
const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
const owned = fs.realpathSync(root);
const match = /^compras_standalone_qa_([a-f0-9]{12})$/.exec(database);
if (!match || path.dirname(owned) !== parent || path.basename(owned) !== `rq01-ledger-qa-${match[1]}`
|| environment.DB_DATABASE !== database || environment.DB_USERNAME !== `compras_standalone_app_${match[1]}`
|| environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false'
|| environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned synthetic standalone preview required');
const worker = mode => {
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment, maxBuffer: 1024 * 1024,
});
if (result.status !== 0) throw Error('Standalone UI fixture/conservation failed');
return JSON.parse(result.stdout.trim());
};
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) {
fs.mkdirSync(path.join(root, relative), { recursive: true });
}
const fixture = worker('prepare-ui');
if (fixture.ui_prepared !== true || fixture.no_initial_financial_grants !== true) throw Error('UI setup inherited grants');
const bytes = fs.readFileSync(path.join(assets, 'manifest.json'));
if (crypto.createHash('sha256').update(bytes).digest('hex') !== manifestPin) throw Error('Pinned UI build required');
for (const entry of Object.values(JSON.parse(bytes))) {
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('UI build entry missing');
}
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) {
fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
}
const port = await new Promise((resolve, reject) => {
const socket = createServer(); socket.on('error', reject);
socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
});
const url = `http://localhost:${port}`;
const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-qa-http-router.php'], {
cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
env: { ...environment, APP_URL: url, SGC_STANDALONE_QA_PORT: String(port), SESSION_DRIVER: 'file', SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false' },
});
try {
let ready = false;
for (let attempt = 0; attempt < 20 && !ready; attempt++) {
try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
}
if (!ready) throw Error('Standalone UI did not start');
const stop = path.join(root, 'stop-finance-review');
console.log(JSON.stringify({ standalone_finance_preview: true, url, stop_file: stop, manifest_sha256: manifestPin, ...fixture }));
const until = Date.now() + 20 * 60 * 1000;
while (!fs.existsSync(stop) && Date.now() < until) {
if (server.exitCode !== null) throw Error('Standalone UI stopped unexpectedly');
await new Promise(resolve => setTimeout(resolve, 200));
}
const proof = worker('read-ui');
if (proof.ui_conservation_verified !== true) throw Error('UI conservation not verified');
console.log(JSON.stringify(proof));
} finally {
if (server.exitCode === null) {
const closed = new Promise(resolve => server.once('exit', resolve));
server.kill(); await closed;
}
}
}