@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
use App\Services\ReplenishmentTaskDefinition;
|
||||
use App\Services\WindowsTaskXml;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
$planPath = $root.'/docs/proofs/replenishment-task-proposal.json';
|
||||
$plan = json_decode(file_get_contents($planPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
$apply = in_array('--apply-authorized', $argv, true);
|
||||
if (realpath($root) !== realpath('C:/laragon/www/compras') || $plan['task_name'] !== 'Compras-Pilot-Replenishment'
|
||||
|| str_replace('\\', '/', dirname(PHP_BINARY)) !== dirname($plan['php_executable'])) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_INSTALLATION_TARGET');
|
||||
}
|
||||
foreach ($plan['source_sha256'] as $file => $hash) {
|
||||
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_SOURCE_CHANGED');
|
||||
}
|
||||
}
|
||||
if (! hash_equals($plan['php_sha256'], hash_file('sha256', $plan['php_executable']))) {
|
||||
throw new LogicException('REPLENISHMENT_GUI_EXECUTABLE_CHANGED');
|
||||
}
|
||||
$run = static function (array $command, int $timeout = 15) use ($root): string {
|
||||
$process = new Process($command, $root, timeout: $timeout);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('REPLENISHMENT_TASK_NATIVE_COMMAND_FAILED');
|
||||
}
|
||||
|
||||
return $process->getOutput();
|
||||
};
|
||||
$scheduler = getenv('SystemRoot').'/System32/schtasks.exe';
|
||||
$tasks = $run([$scheduler, '/Query', '/FO', 'CSV', '/NH']);
|
||||
foreach (preg_split('/\r?\n/', trim($tasks)) as $row) {
|
||||
$name = str_getcsv($row, escape: '')[0] ?? '';
|
||||
if ($name === '\\'.$plan['task_name']) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_ALREADY_EXISTS_NEVER_OVERWRITE');
|
||||
}
|
||||
}
|
||||
$health = json_decode(trim($run([PHP_BINARY, 'scripts/replenishment-pilot-task.php', '--check'])), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($health['state'] !== 'ready' || $health['database_enforced_read_only'] !== true) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_PILOT_NOT_READY');
|
||||
}
|
||||
$identity = str_getcsv(trim($run([getenv('SystemRoot').'/System32/whoami.exe', '/user', '/fo', 'csv', '/nh'])), escape: '');
|
||||
$sid = $identity[1] ?? '';
|
||||
if (! preg_match('/^S-1-\d+(?:-\d+)+$/D', $sid)) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_CURRENT_USER_UNAVAILABLE');
|
||||
}
|
||||
$escape = static fn (string $value) => htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
|
||||
$start = (new DateTimeImmutable('now', new DateTimeZone('Africa/Johannesburg')))->modify('+1 minute')->format('c');
|
||||
$php = $escape($plan['php_executable']);
|
||||
$arguments = $escape('"'.$root.'/scripts/replenishment-pilot-task.php" --once');
|
||||
$directory = 'C:/laragon/data/compras/tasks/replenishment-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_PRIVATE_STORAGE');
|
||||
}
|
||||
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
|
||||
$settings = json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($apply) {
|
||||
// Private recovery material; no settings, credentials or business rows are published.
|
||||
copy($settingsPath, $directory.'/settings.private.json');
|
||||
$dump = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$directory.'/before.dump',
|
||||
'--dbname='.$settings['DB_DATABASE']], $root, ['PGHOST' => $settings['DB_HOST'], 'PGPORT' => $settings['DB_PORT'],
|
||||
'PGUSER' => $settings['DB_USERNAME'], 'PGPASSWORD' => $settings['DB_PASSWORD']], timeout: 120);
|
||||
$dump->run();
|
||||
if (! $dump->isSuccessful() || ! is_file($directory.'/before.dump')) {
|
||||
throw new LogicException('REPLENISHMENT_PRIVATE_BACKUP_FAILED');
|
||||
}
|
||||
$connection = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$connection->beginTransaction();
|
||||
$connection->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$baseline = [];
|
||||
foreach ($connection->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
|
||||
$rows = $connection->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$baseline[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
$connection->commit();
|
||||
file_put_contents($directory.'/baseline.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
$working = $escape($root);
|
||||
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.
|
||||
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'.
|
||||
'<RegistrationInfo><Description>Compras pilot: native replenishment under existing approved policies only.</Description></RegistrationInfo>'.
|
||||
'<Triggers><TimeTrigger><StartBoundary>'.$start.'</StartBoundary><Enabled>true</Enabled><Repetition><Interval>PT1M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger>'.
|
||||
'<LogonTrigger><Enabled>true</Enabled><UserId>'.$sid.'</UserId></LogonTrigger></Triggers>'.
|
||||
'<Principals><Principal id="CurrentUser"><UserId>'.$sid.'</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>'.
|
||||
'<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>true</StartWhenAvailable><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT1M</ExecutionTimeLimit></Settings>'.
|
||||
'<Actions Context="CurrentUser"><Exec><Command>'.$php.'</Command><Arguments>'.$arguments.'</Arguments><WorkingDirectory>'.$working.'</WorkingDirectory></Exec></Actions></Task>';
|
||||
$document = WindowsTaskXml::parse($xml);
|
||||
$xpath = new DOMXPath($document);
|
||||
$xpath->registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
|
||||
if ($xpath->query('//t:Exec')->length !== 1 || $xpath->evaluate('string(//t:LogonType)') !== 'InteractiveToken'
|
||||
|| $xpath->evaluate('string(//t:RunLevel)') !== 'LeastPrivilege' || $xpath->query('//t:Triggers/*')->length !== 2) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_XML_SCOPE');
|
||||
}
|
||||
$xmlPath = $directory.'/task.private.xml';
|
||||
$fileBytes = WindowsTaskXml::encode($xml);
|
||||
file_put_contents($xmlPath, $fileBytes);
|
||||
$record = ['date' => gmdate('c'), 'state' => 'preview', 'task_name' => $plan['task_name'], 'current_user_only' => true,
|
||||
'credentials_stored' => false, 'run_level' => 'Limited', 'poll_interval' => 'PT1M', 'overlap' => 'IgnoreNew', 'time_limit' => 'PT1M',
|
||||
'private_definition' => $xmlPath, 'xml_sha256' => hash('sha256', $fileBytes), 'pilot_ready' => true,
|
||||
'eligible_requests' => $health['health']['work']['pending'], 'native_command' => $plan['command'],
|
||||
'task_installed_or_started' => false, 'powershell_execution_policy_changed' => false];
|
||||
if ($apply) {
|
||||
$record['private_backup_directory'] = $directory;
|
||||
$record['database_backup_sha256'] = hash_file('sha256', $directory.'/before.dump');
|
||||
$record['baseline_tables'] = count($baseline);
|
||||
}
|
||||
if (! $apply) {
|
||||
file_put_contents($root.'/docs/proofs/replenishment-task-preflight.json', json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit;
|
||||
}
|
||||
$approvalPath = $root.'/docs/proofs/replenishment-task-authorization.json';
|
||||
$approval = is_file($approvalPath) ? json_decode(file_get_contents($approvalPath), true, 32, JSON_THROW_ON_ERROR) : [];
|
||||
if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== $plan['scope']
|
||||
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_NOT_AUTHORIZED');
|
||||
}
|
||||
$resultPath = $root.'/docs/proofs/replenishment-task-installation.json';
|
||||
if (is_file($resultPath)) {
|
||||
throw new LogicException('REPLENISHMENT_TASK_PREVIOUS_RESULT');
|
||||
}
|
||||
$run([$scheduler, '/Create', '/TN', $plan['task_name'], '/XML', $xmlPath]); // No /F: never replace another task.
|
||||
$installed = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
|
||||
file_put_contents($directory.'/installed.private.xml', $installed);
|
||||
ReplenishmentTaskDefinition::assertMatches($xml, $installed);
|
||||
$record['state'] = 'installed';
|
||||
$record['task_installed_or_started'] = true;
|
||||
file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
$run([$scheduler, '/Run', '/TN', $plan['task_name']]);
|
||||
$record['initial_pass_requested'] = true;
|
||||
$record['state'] = 'awaiting_passage_verification';
|
||||
file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
Reference in New Issue
Block a user