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

107 lines
6.3 KiB
PHP

<?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\Http\Middleware\HandleInertiaRequests;
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)
&& strcasecmp(trim($sql), 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY') !== 0) {
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 = [];
$extraPaths = config('order_cancellation.enabled') === true ? ['/ordens/cancelamentos'] : [];
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', ...$extraPaths] 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(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;