commit compras2 3011
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-30 23:04:25 +02:00
parent 318b62f458
commit c9bd6db90b
39 changed files with 2235 additions and 42 deletions
+160 -21
View File
@@ -72,6 +72,85 @@ final class CodeDeployment
}
}
private function fileHash(string $relative): ?string
{
$path = $this->path($relative);
if (! file_exists($path)) {
return null;
}
if (! is_file($path)) {
throw new \RuntimeException('O destino não é um ficheiro regular.');
}
return hash_file('sha256', $path);
}
private static function v2Path(string $file, bool $overlay): bool
{
if (str_contains($file, '..') || preg_match('~(^|/)(\.|vendor/|node_modules/|storage/)~i', $file)) {
return false;
}
$host = '~^(app/[A-Za-z0-9_/-]+\.php|config/[A-Za-z0-9_-]+\.php|routes/web\.php|database/(migrations/[A-Za-z0-9_]+\.php|sql/[A-Za-z0-9_-]+\.sql)|resources/views/[A-Za-z0-9_/-]+\.blade\.php|resources/js/[A-Za-z0-9_./-]+\.(jsx?|tsx?)|public/([A-Za-z0-9_-]+\.mjs|build/manifest\.json)|packages/[a-z0-9-]+/(bootstrap\.php|module\.json|README\.md|(src|ui)/[A-Za-z0-9_/-]+\.php))$~D';
if (preg_match($host, $file)) {
return true;
}
return ! $overlay && (bool) preg_match('~^(bootstrap\.php|(integrations|scripts|packages)/[A-Za-z0-9_/-]+\.(php|json|jsx?|mjs|css|md))$~D', $file);
}
private function v2Transition(array $manifest, ?array $old, ?array $previous, string $hash): ?string
{
$transition = $manifest['composition_transition'];
if ($transition['from_manifest_sha256'] !== ($previous['manifest_sha256'] ?? null)) {
throw new \RuntimeException('A transição não corresponde à entrega anterior.');
}
$oldFiles = $old['host_overlays'] ?? [];
if (array_diff_key($oldFiles, $manifest['host_overlays']) || array_diff_key($old['support_files'] ?? [], $manifest['support_files'])) {
throw new \RuntimeException('A transição não pode retirar ficheiros da composição anterior.');
}
$added = [];
foreach (array_diff_key($manifest['host_overlays'], $oldFiles) as $file => $entry) {
$added[$file] = $entry['before_sha256'];
}
$declared = $transition['added_files'];
ksort($added);
ksort($declared);
if ($added !== $declared) {
throw new \RuntimeException('Ampliação da composição não declarada exactamente.');
}
$schema = [];
foreach ($manifest['support_files'] as $file => $after) {
if ((str_starts_with($file, 'database/') || preg_match('~Schema\.php$~D', $file)
|| in_array($file, ['integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json'], true))
&& ($old['support_files'][$file] ?? null) !== $after) {
$schema[$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $after];
}
}
$declared = $transition['schema_files'];
ksort($schema);
ksort($declared);
if ($schema !== $declared) {
throw new \RuntimeException('Alterações de schema não declaradas exactamente.');
}
if (! $schema) {
return null;
}
$receiptPath = $this->path('storage/app/private/module-deployments/schema-transition-'.$hash.'.json');
$receipt = is_file($receiptPath) ? json_decode(file_get_contents($receiptPath), true, 32, JSON_THROW_ON_ERROR) : [];
$changes = $receipt['changes'] ?? [];
if (! is_array($changes)) {
throw new \RuntimeException('Recibo de schema inválido.');
}
ksort($changes);
if (($receipt['from_manifest_sha256'] ?? null) !== ($previous['manifest_sha256'] ?? null)
|| ($receipt['to_manifest_sha256'] ?? null) !== $hash || ($receipt['host'] ?? null) !== $this->host
|| ($receipt['schema_verified'] ?? false) !== true || $changes !== $schema) {
throw new \RuntimeException('Transição de schema exige recibo exacto e verificado do destino.');
}
return hash_file('sha256', $receiptPath);
}
private function manifest(string $bundle, string $expected): array
{
if (trim($bundle) === '') {
@@ -83,9 +162,30 @@ final class CodeDeployment
throw new \RuntimeException('Manifesto divergente.');
}
$manifest = json_decode($text, true, 32, JSON_THROW_ON_ERROR);
if (($manifest['format'] ?? '') !== 'tempo.operational-review.v1') {
$v2 = ($manifest['format'] ?? '') === 'tempo.operational-review.v2';
if (! $v2 && ($manifest['format'] ?? '') !== 'tempo.operational-review.v1') {
throw new \RuntimeException('Formato de entrega desconhecido.');
}
if ($v2) {
$keys = array_keys($manifest);
sort($keys);
$transition = $manifest['composition_transition'] ?? null;
if ($keys !== ['composition_transition', 'format', 'host_overlays', 'support_files']
|| ! is_array($transition) || ! is_array($manifest['support_files']) || ! is_array($manifest['host_overlays'])
|| ! $manifest['support_files'] || ! $manifest['host_overlays'] || count($manifest['support_files']) > 10000) {
throw new \RuntimeException('Contrato v2 inválido.');
}
$keys = array_keys($transition);
sort($keys);
if ($keys !== ['added_files', 'from_manifest_sha256', 'schema_files'] || ! is_array($transition['added_files']) || ! is_array($transition['schema_files'])
|| ($transition['from_manifest_sha256'] !== null && (! is_string($transition['from_manifest_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $transition['from_manifest_sha256'])))) {
throw new \RuntimeException('Plano de composição v2 inválido.');
}
$names = array_map('strtolower', array_keys($manifest['support_files']));
if (count($names) !== count(array_unique($names))) {
throw new \RuntimeException('Caminhos equivalentes recusados.');
}
}
$expectedFiles = array_fill_keys([...array_keys($manifest['support_files']), 'manifest.json'], true);
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($bundle, \FilesystemIterator::SKIP_DOTS)) as $entry) {
$relative = str_replace('\\', '/', substr($entry->getPathname(), strlen($bundle) + 1));
@@ -95,13 +195,19 @@ final class CodeDeployment
}
foreach ($manifest['support_files'] as $file => $hash) {
$resolved = str_replace('\\', '/', realpath($bundle.'/'.$file) ?: '');
if (str_contains($file, '..') || ! preg_match('~^(bootstrap\.php|(app|packages|integrations|scripts)/[A-Za-z0-9_./-]+|resources/js/(app|PurchasingHome)\.jsx|public/build/manifest\.json)$~D', $file)
$allowed = $v2 ? self::v2Path($file, false) : (bool) preg_match('~^(bootstrap\.php|(app|packages|integrations|scripts)/[A-Za-z0-9_./-]+|resources/js/(app|PurchasingHome)\.jsx|public/build/manifest\.json)$~D', $file);
if (str_contains($file, '..') || ! $allowed || ! is_string($hash) || ! preg_match('/^[a-f0-9]{64}$/D', $hash)
|| ! str_starts_with(strtolower($resolved), strtolower(str_replace('\\', '/', $bundle)).'/') || is_link($bundle.'/'.$file) || ! is_file($bundle.'/'.$file) || ! hash_equals($hash, hash_file('sha256', $bundle.'/'.$file))) {
throw new \RuntimeException('Integridade do bundle divergente.');
}
}
foreach ($manifest['host_overlays'] as $file => $hashes) {
if ((! str_starts_with($file, 'app/') && ! in_array($file, ['resources/js/app.jsx', 'resources/js/PurchasingHome.jsx', 'public/build/manifest.json'], true)) || ($manifest['support_files'][$file] ?? null) !== $hashes['after_sha256']) {
if ($v2 && (! is_array($hashes) || count($hashes) !== 2 || ! array_key_exists('before_sha256', $hashes) || ! isset($hashes['after_sha256'])
|| ($hashes['before_sha256'] !== null && (! is_string($hashes['before_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $hashes['before_sha256']))))) {
throw new \RuntimeException('Baseline v2 inválida.');
}
$allowed = $v2 ? self::v2Path($file, true) : (str_starts_with($file, 'app/') || in_array($file, ['resources/js/app.jsx', 'resources/js/PurchasingHome.jsx', 'public/build/manifest.json'], true));
if (! $allowed || ($manifest['support_files'][$file] ?? null) !== $hashes['after_sha256']) {
throw new \RuntimeException('Sobreposição inválida.');
}
$this->path($file);
@@ -114,6 +220,7 @@ final class CodeDeployment
{
$this->cachePaths();
[, $manifest] = $this->manifest($bundle, $manifestHash);
$v2 = $manifest['format'] === 'tempo.operational-review.v2';
$pointer = $this->path('packages/purchasing/current.json');
$pointerHash = hash_file('sha256', $pointer);
$previous = $this->current();
@@ -128,14 +235,17 @@ final class CodeDeployment
}
$this->verifyApplied($journal, $previous['deployment_id']);
[, $oldManifest] = $this->manifest($this->path('packages/internal-requisitions'), $previous['manifest_sha256']);
if (array_keys($oldManifest['host_overlays']) !== array_keys($manifest['host_overlays'])) {
if (! $v2 && $oldManifest['format'] === 'tempo.operational-review.v2') {
throw new \RuntimeException('Uma composição v2 exige transição v2 explícita.');
}
if (! $v2 && array_keys($oldManifest['host_overlays']) !== array_keys($manifest['host_overlays'])) {
throw new \RuntimeException('Mudança de composição do host exige plano próprio.');
}
foreach (['integrations/sgf/operational/BudgetSchema.php', 'integrations/sgf/operational/BudgetUiSchema.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json', 'integrations/sgf/internal-requisitions/Schema.php', 'integrations/sgf/access/AccessOverlay.php'] as $file) {
foreach ($v2 ? [] : ['integrations/sgf/operational/BudgetSchema.php', 'integrations/sgf/operational/BudgetUiSchema.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json', 'integrations/sgf/internal-requisitions/Schema.php', 'integrations/sgf/access/AccessOverlay.php'] as $file) {
if (($oldManifest['support_files'][$file] ?? null) !== ($manifest['support_files'][$file] ?? null)) {
$receiptPath=$this->path('storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json');
$receipt=is_file($receiptPath)?json_decode(file_get_contents($receiptPath),true,32,JSON_THROW_ON_ERROR):[];
if(($receipt['from_manifest_sha256']??null)!==$previous['manifest_sha256']||($receipt['to_manifest_sha256']??null)!==$manifestHash||($receipt['host']??null)!==$this->host||($receipt['changes'][$file]['before']??null)!==($oldManifest['support_files'][$file]??null)||($receipt['changes'][$file]['after']??null)!==($manifest['support_files'][$file]??null)||($receipt['schema_verified']??false)!==true){
$receiptPath = $this->path('storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json');
$receipt = is_file($receiptPath) ? json_decode(file_get_contents($receiptPath), true, 32, JSON_THROW_ON_ERROR) : [];
if (($receipt['from_manifest_sha256'] ?? null) !== $previous['manifest_sha256'] || ($receipt['to_manifest_sha256'] ?? null) !== $manifestHash || ($receipt['host'] ?? null) !== $this->host || ($receipt['changes'][$file]['before'] ?? null) !== ($oldManifest['support_files'][$file] ?? null) || ($receipt['changes'][$file]['after'] ?? null) !== ($manifest['support_files'][$file] ?? null) || ($receipt['schema_verified'] ?? false) !== true) {
throw new \RuntimeException('Transição de schema exige migração própria e recibo exacto do destino.');
}
}
@@ -143,11 +253,13 @@ final class CodeDeployment
} elseif ($previous !== null) {
throw new \RuntimeException('Registo activo sem bundle; recuperar a implantação anterior.');
}
$schemaReceipt = $v2 ? $this->v2Transition($manifest, $oldManifest, $previous, $manifestHash) : null;
$before = [];
foreach ($manifest['host_overlays'] as $file => $hashes) {
$hash = hash_file('sha256', $this->path($file));
$expected = $oldManifest === null ? $hashes['before_sha256'] : $oldManifest['host_overlays'][$file]['after_sha256'];
if ($oldManifest !== null && $hashes['before_sha256'] !== $oldManifest['host_overlays'][$file]['before_sha256']) {
$hash = $this->fileHash($file);
$prior = $oldManifest['host_overlays'][$file] ?? null;
$expected = $prior === null ? $hashes['before_sha256'] : $prior['after_sha256'];
if ($prior !== null && $hashes['before_sha256'] !== ($v2 ? $prior['after_sha256'] : $prior['before_sha256'])) {
throw new \RuntimeException('Baseline do host mudou entre versões.');
}
if ($hash !== $expected) {
@@ -155,7 +267,11 @@ final class CodeDeployment
}
$before[$file] = $hash;
}
$target = hash('sha256', json_encode([$this->host, $pointerHash, $before, $previous], JSON_THROW_ON_ERROR));
$identity = [$this->host, $pointerHash, $before, $previous];
if ($v2) {
$identity[] = [$manifestHash, $schemaReceipt];
}
$target = hash('sha256', json_encode($identity, JSON_THROW_ON_ERROR));
return ['target_sha256' => $target, 'pointer_sha256' => $pointerHash, 'host_files' => $before, 'manifest_sha256' => $manifestHash, 'previous' => $previous, 'deployment_id' => $this->attempt($manifestHash), 'writes' => false];
}
@@ -357,7 +473,9 @@ final class CodeDeployment
'previous' => $plan['previous'],
'pointer_sha256' => $plan['pointer_sha256'], 'files' => [], 'cache_files' => [], 'bundle_files' => $manifest['support_files']];
foreach ($manifest['host_overlays'] as $file => $hashes) {
self::write($this->path($prefix.'/before/'.$file), file_get_contents($this->path($file)));
if ($plan['host_files'][$file] !== null) {
self::write($this->path($prefix.'/before/'.$file), file_get_contents($this->path($file)));
}
$hashes['before_sha256'] = $plan['host_files'][$file];
$data['files'][$file] = $hashes;
}
@@ -371,9 +489,17 @@ final class CodeDeployment
$data['cache_files'][$relative] = hash_file('sha256', $cache);
}
foreach ($manifest['support_files'] as $file => $hash) {
self::write($this->path($prefix.'/staged/'.$file), file_get_contents($bundle.'/'.$file));
$body = file_get_contents($bundle.'/'.$file);
if (! hash_equals($hash, hash('sha256', $body))) {
throw new \RuntimeException('Fonte da candidata mudou durante a preparação.');
}
self::write($this->path($prefix.'/staged/'.$file), $body);
}
self::write($this->path($prefix.'/staged/manifest.json'), file_get_contents($bundle.'/manifest.json'));
$manifestBody = file_get_contents($bundle.'/manifest.json');
if (! hash_equals($manifestHash, hash('sha256', $manifestBody))) {
throw new \RuntimeException('Manifesto mudou durante a preparação.');
}
self::write($this->path($prefix.'/staged/manifest.json'), $manifestBody);
$this->journal($id, $data);
$checkpoint && $checkpoint('prepared');
$data['state'] = 'applying';
@@ -388,10 +514,14 @@ final class CodeDeployment
}
$checkpoint && $checkpoint('caches-cleared');
foreach ($data['files'] as $file => $hashes) {
if (! hash_equals($hashes['before_sha256'], hash_file('sha256', $this->path($file)))) {
if ($hashes['before_sha256'] !== $this->fileHash($file)) {
throw new \RuntimeException('Ficheiro mudou durante implantação.');
}
self::write($this->path($file), file_get_contents($bundle.'/'.$file));
$body = file_get_contents($this->path($prefix.'/staged/'.$file));
if (! hash_equals($hashes['after_sha256'], hash('sha256', $body))) {
throw new \RuntimeException('Cópia preparada da candidata divergiu.');
}
self::write($this->path($file), $body);
$checkpoint && $checkpoint('file:'.$file);
}
// Both resolved paths are checked within the host before this directory move.
@@ -428,7 +558,7 @@ final class CodeDeployment
}
$this->manifest($this->path('packages/internal-requisitions'), $data['manifest_sha256']);
foreach ($data['files'] as $file => $hashes) {
if (! hash_equals($hashes['after_sha256'], hash_file('sha256', $this->path($file)))) {
if ($hashes['after_sha256'] !== $this->fileHash($file)) {
throw new \RuntimeException('Código aplicado alterado.');
}
}
@@ -471,10 +601,10 @@ final class CodeDeployment
throw new \RuntimeException('Cache mudou após compilação registada.');
}
foreach ($data['files'] as $file => $hashes) {
if (! in_array(hash_file('sha256', $this->path($file)), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
if (! in_array($this->fileHash($file), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
throw new \RuntimeException('Código local alterado; recuperação recusada.');
}
if (! hash_equals($hashes['before_sha256'], hash_file('sha256', $this->path($prefix.'/before/'.$file)))) {
if ($hashes['before_sha256'] !== $this->fileHash($prefix.'/before/'.$file)) {
throw new \RuntimeException('Backup de código divergente.');
}
}
@@ -518,7 +648,16 @@ final class CodeDeployment
$data['state'] = 'rolling-back';
$this->journal($id, $data);
foreach ($data['files'] as $file => $hashes) {
self::write($this->path($file), file_get_contents($this->path($prefix.'/before/'.$file)));
if (! in_array($this->fileHash($file), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
throw new \RuntimeException('Código mudou durante a recuperação.');
}
if ($hashes['before_sha256'] === null) {
if ($this->fileHash($file) !== null && ! unlink($this->path($file))) {
throw new \RuntimeException('Falha ao repor ausência anterior.');
}
} else {
self::write($this->path($file), file_get_contents($this->path($prefix.'/before/'.$file)));
}
}
if ($rebuilt) {
foreach ($data['built_cache_files'] as $file => $hash) {