Files
Investidor-V2/outputs/investmoz-parques-ativacao-20261016/verify-preservation.php
T
nala cef6e201c7
tests / ci (push) Canceled after 0s
versao nrgocios 2
2026-10-16 20:11:05 +02:00

57 lines
7.5 KiB
PHP

<?php
ini_set('zend.exception_ignore_args','1');
set_exception_handler(function(Throwable $e){fwrite(STDERR,'Preservation check stopped: '.$e::class.' line '.$e->getLine().PHP_EOL);exit(1);});
$root=dirname(__DIR__,2);require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';
(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
$c=config('database.connections.'.config('database.default'));
if($c['driver']!=='pgsql'||$c['database']!=='investemoz'||(int)$c['port']!==5432||!in_array($c['host'],['127.0.0.1','localhost'])||!empty($c['url']))throw new RuntimeException('Active identity guard');
$b=json_decode(file_get_contents(__DIR__.'/FRESH-BACKUP.json'),true,512,JSON_THROW_ON_ERROR);$restore=$b['restore_target']['database'];
if(!preg_match('/^parks_before_\d{8}_\d{6}_test$/D',$restore))throw new RuntimeException('Restored clone guard');
$a=new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$q=new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$restore,'postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
foreach([$a,$q]as$db){$db->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');$db->exec("SET LOCAL TIME ZONE 'UTC'");}
try{
$migration='2026_10_16_130000_add_investment_zone_editorial_draft';
$shape=$a->query("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='editorial_draft'")->fetch(PDO::FETCH_ASSOC);
if($shape!==['data_type'=>'text','is_nullable'=>'YES'])throw new RuntimeException('Installed column mismatch');
if((int)$a->query("SELECT count(*) FROM investment_zones WHERE editorial_draft IS NOT NULL")->fetchColumn()!==0)throw new RuntimeException('Unexpected actual park preparation; do not overwrite');
if((int)$a->query("SELECT count(*) FROM migrations WHERE migration='$migration'")->fetchColumn()!==1)throw new RuntimeException('Nominal ledger mismatch');
$technical=['sessions','cache','cache_locks','jobs','failed_jobs','password_reset_tokens'];$diff=[];$technicalDiff=[];$tables=[];
foreach($q->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname<>'information_schema' ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC)as$t){
$name=$t['tablename'];$n='"'.str_replace('"','""',$t['schemaname']).'"."'.str_replace('"','""',$name).'"';
$cols=$q->prepare('SELECT column_name FROM information_schema.columns WHERE table_schema=? AND table_name=? ORDER BY ordinal_position');$cols->execute([$t['schemaname'],$name]);
$projection=implode(',',array_map(fn($v)=>'"'.str_replace('"','""',$v).'"',$cols->fetchAll(PDO::FETCH_COLUMN)));
$where='';
if($t['schemaname']==='public'&&$name==='migrations')$where=" WHERE migration <> '$migration'";
if($t['schemaname']==='public'&&$name==='audit_events')$where=" WHERE source_system IS DISTINCT FROM 'investment-zone-profile-installation'";
$sql='SELECT row_to_json(t)::text FROM (SELECT '.$projection.' FROM '.$n.$where.') t ORDER BY row_to_json(t)::text';
$x=$q->query($sql)->fetchAll(PDO::FETCH_COLUMN);$y=$a->query($sql)->fetchAll(PDO::FETCH_COLUMN);
if($x!==$y){if($t['schemaname']==='public'&&in_array($name,$technical,true))$technicalDiff[]=$name;else $diff[]=$n;}
$tables[$n]=['previous_rows'=>count($x),'current_previous_rows'=>count($y),'previous_data_identical'=>$x===$y,
'previous_sha256'=>hash('sha256',implode("\n",$x)),'current_previous_sha256'=>hash('sha256',implode("\n",$y))];
}
$events=$a->query("SELECT action,actor_user_id,correlation_id,after_data->'result' AS result FROM audit_events WHERE source_system='investment-zone-profile-installation' ORDER BY occurred_at,id")->fetchAll(PDO::FETCH_ASSOC);
if(count($events)!==1||$events[0]['action']!=='schema')throw new RuntimeException('Unexpected installation audit count');
$event=$events[0];$event['result']=json_decode($event['result'],true,512,JSON_THROW_ON_ERROR);
$m=json_decode(file_get_contents($root.'/outputs/investmoz-parques-QA-20261016/para-revisao/MANIFESTO-CANDIDATA.json'),true,512,JSON_THROW_ON_ERROR);
if($event['result']['migration']!==$migration||$event['result']['code_hash']!==$m['code_hash']||$event['result']['business_records_changed']!==0)throw new RuntimeException('Unexpected installation receipt');
$base=json_decode(file_get_contents($root.'/outputs/investmoz-parques-QA-20261016/ATIVO-ANTES.json'),true);$changed=array_column($m['sources'],'path');$count=0;
foreach(array_merge($base['files'],$base['protected'])as$n=>$h){if(in_array($n,$changed,true)||str_starts_with($n,'public/build/'))continue;if(!is_file($root.'/'.$n)||hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Unrelated protected file differs');$count++;}
foreach($m['sources']as$s)if(hash_file('sha256',$root.'/'.$s['path'])!==$s['candidate_sha256'])throw new RuntimeException('Candidate source hash differs');
foreach($m['build']as$n=>$h)if(hash_file('sha256',$root.'/public/build/'.$n)!==$h)throw new RuntimeException('Candidate asset hash differs');
$private=json_decode(file_get_contents($b['private_directory'].'/backup-proof-private.json'),true);$files=0;$docs=0;
foreach($private['file_hashes']as$n=>$h){if(!str_starts_with($n,'storage/app/'))continue;if(!is_file($root.'/'.$n)||hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Managed file differs');$files++;}
$disk=config('filesystems.disks.local.root');foreach($q->query('SELECT id,storage_key FROM documents WHERE storage_key IS NOT NULL')->fetchAll(PDO::FETCH_ASSOC)as$d){$n='storage-documents/'.$d['id'].'.stored';if(!isset($private['file_hashes'][$n]))continue;if(!is_file($disk.'/'.$d['storage_key'])||hash_file('sha256',$disk.'/'.$d['storage_key'])!==$private['file_hashes'][$n])throw new RuntimeException('Library bytes differ');$docs++;}
$sql="SELECT schemaname,sequencename,data_type,start_value,min_value,max_value,increment_by,cycle,cache_size,last_value FROM pg_sequences WHERE schemaname NOT LIKE 'pg_%' AND schemaname<>'information_schema' ORDER BY schemaname,sequencename";
$sx=$q->query($sql)->fetchAll(PDO::FETCH_ASSOC);$sy=$a->query($sql)->fetchAll(PDO::FETCH_ASSOC);$sequenceDiff=[];
foreach($sx as$i=>$row){if($row!==$sy[$i]){$v=$sy[$i];$want=$row;$want['last_value']=(int)$row['last_value']+1;if($row['sequencename']!=='migrations_id_seq'||$want!==$v)throw new RuntimeException('Unexpected sequence difference');$sequenceDiff[]=['sequence'=>$row['sequencename'],'increment'=>1];}}
$result=['at'=>gmdate('c'),'candidate'=>$m['candidate'],'read_only'=>true,'tables_compared'=>count($tables),'unexpected_business_history_differences'=>$diff,
'technical_table_differences'=>$technicalDiff,'schema'=>['migration'=>$migration,'ledger'=>1,'column'=>$shape,'all_private_drafts_null'=>true],
'operation'=>$event,'protected_unrelated_files'=>$count,'candidate_application_verified'=>16,'candidate_build_verified'=>162,
'managed_files_verified'=>$files,'original_documents_verified'=>$docs,'sequence_differences'=>$sequenceDiff,
'B_COUNTRY02_roles_classifications_content_history_preserved'=>!$diff,'business_records_unchanged'=>!$diff,'tables'=>$tables];
$path=__DIR__.'/PRESERVACAO-FINAL.json';if(is_file($path))throw new RuntimeException('Preserve receipt');
file_put_contents($path,json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(array_diff_key($result,['tables'=>true,'operation'=>true])).PHP_EOL;if($diff)exit(2);
}finally{foreach([$a,$q]as$db)$db->exec('ROLLBACK');}