27 lines
7.1 KiB
PHP
27 lines
7.1 KiB
PHP
<?php
|
|
ini_set('zend.exception_ignore_args','1');
|
|
set_exception_handler(function(Throwable $e){fwrite(STDERR,'Preservation verification stopped: '.$e::class.' line '.$e->getLine().PHP_EOL);exit(1);});
|
|
$root=dirname(__DIR__,2);$phase=$argv[1]??'';if(!in_array($phase,['final'],true))throw new RuntimeException('Explicit phase');
|
|
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['database']!=='investemoz'||(int)$c['port']!==5432||!in_array($c['host'],['127.0.0.1','localhost'])||!empty($c['url']))throw new RuntimeException('Active identity');
|
|
$b=json_decode(file_get_contents(__DIR__.'/FRESH-BACKUP.json'),true,512,JSON_THROW_ON_ERROR);$cloneName=$b['restore_target']['database'];if(!preg_match('/^classification_before_\d{8}_\d{6}_test$/D',$cloneName))throw new RuntimeException('Clone guard');
|
|
$active=new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$clone=new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$cloneName,'postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
|
|
foreach([$active,$clone]as$db){$db->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');$db->exec("SET LOCAL TIME ZONE 'UTC'");}
|
|
try{
|
|
$technical=['sessions','cache','cache_locks','jobs','failed_jobs'];$tables=[];$differences=[];$allowedAudit=[];$businessIdentical=true;
|
|
foreach($clone->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){$n=$t['tablename'];$q='"'.str_replace('"','""',$t['schemaname']).'"."'.str_replace('"','""',$n).'"';$sql='SELECT row_to_json(t)::text FROM '.$q.' t ORDER BY row_to_json(t)::text';$before=$clone->query($sql)->fetchAll(PDO::FETCH_COLUMN);$after=$active->query($sql)->fetchAll(PDO::FETCH_COLUMN);$technicalTable=in_array($n,$technical,true);if($before!==$after&&!$technicalTable){$businessIdentical=false;$missing=array_values(array_diff($before,$after));$added=array_values(array_diff($after,$before));$expected=$n==='audit_events'&&!$missing&&count($added)>0;foreach($added as$line){$event=json_decode($line,true);$data=$event['after_data']??[];if(is_string($data))$data=json_decode($data,true);if(($event['source_system']??'')!=='portal-profiles-v1'||($event['action']??'')!=='request_denied'||($data['path']??'')!=='minhas-oportunidades/create'||($data['method']??'')!=='GET'||(int)($data['status']??0)!==403||(int)($event['actor_user_id']??0)!==2)$expected=false;}if($expected){foreach($added as$line){$e=json_decode($line,true);$allowedAudit[]=['id'=>$e['id'],'actor_user_id'=>$e['actor_user_id'],'action'=>$e['action'],'occurred_at'=>$e['occurred_at']];}}else $differences[]=$q;}$tables[$q]=['before_rows'=>count($before),'after_rows'=>count($after),'identical'=>$before===$after,'technical'=>$technicalTable,'before_sha256'=>hash('sha256',implode("\n",$before)),'after_sha256'=>hash('sha256',implode("\n",$after))];}
|
|
$release=$root.'/outputs/investmoz-classificacao-multidimensional-QA-20261015';$m=json_decode(file_get_contents($release.'/MANIFESTO-ENTREGA.json'),true);$pre=json_decode(file_get_contents(__DIR__.'/PREFLIGHT.json'),true);
|
|
foreach($pre['protected_files']as$n=>$h)if(hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Protected config changed');
|
|
$baseline=json_decode(file_get_contents($release.'/ATIVO-FICHEIROS-ANTES.json'),true);$allowed=$phase==='final'?array_column($m['sources'],'path'):[];
|
|
if($phase==='final')foreach($m['payload']as$f)if(str_starts_with($f['path'],'build/'))$allowed[]='public/'.$f['path'];
|
|
$protected=0;foreach($baseline as$n=>$h){if(in_array($n,$allowed,true))continue;if(!is_file($root.'/'.$n)||hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Protected source or asset changed');$protected++;}
|
|
foreach($m['sources']as$s){$f=$root.'/'.$s['path'];$expected=$phase==='final'?$s['candidate_sha256']:$s['previous_sha256'];if((is_file($f)?hash_file('sha256',$f):null)!==$expected)throw new RuntimeException('Source mismatch');}
|
|
if($phase==='final')foreach($m['payload']as$f)if(str_starts_with($f['path'],'build/')&&hash_file('sha256',$root.'/public/'.$f['path'])!==$f['sha256'])throw new RuntimeException('Build mismatch');
|
|
$private=json_decode(file_get_contents($b['private_directory'].'/backup-proof-private.json'),true);$verified=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 private/public file changed');$verified++;}
|
|
$documents=0;$preexistingMissing=0;$disk=config('filesystems.disks.local.root');foreach($clone->query('SELECT id,storage_key FROM documents WHERE storage_key IS NOT NULL')->fetchAll(PDO::FETCH_ASSOC)as$d){$key='storage-documents/'.$d['id'].'.stored';if(!isset($private['file_hashes'][$key])){$preexistingMissing++;continue;}if(!is_file($disk.'/'.$d['storage_key'])||hash_file('sha256',$disk.'/'.$d['storage_key'])!==$private['file_hashes'][$key])throw new RuntimeException('Original document bytes changed');$documents++;}
|
|
$migration=(int)$active->query("SELECT count(*) FROM migrations WHERE migration='2026_10_09_190000_prepare_investor_path'")->fetchColumn();$env=Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));if($migration!==1||!filter_var($env['INVESTOR_PATH_ENABLED']??false,FILTER_VALIDATE_BOOL)||!filter_var($env['PORTAL_LEGACY_CONTENT_ENABLED']??false,FILTER_VALIDATE_BOOL))throw new RuntimeException('B or flags changed');
|
|
$proof=['at'=>gmdate('c'),'candidate'=>$m['candidate'],'phase'=>$phase,'read_only'=>true,'fresh_restore_comparison'=>$b['restore_target'],'tables_compared'=>count($tables),'business_tables_identical'=>$businessIdentical,'business_records_and_prior_history_preserved'=>!$differences,'expected_access_denial_audit_rows_added'=>$allowedAudit,'business_table_differences'=>$differences,'technical_tables_excluded_from_business_comparison'=>$technical,'protected_config_files_unchanged'=>count($pre['protected_files']),'protected_source_build_files_unchanged'=>$protected,'source_hashes_verified'=>17,'candidate_build_hashes_verified'=>$phase==='final'?count(array_filter($m['payload'],fn($f)=>str_starts_with($f['path'],'build/'))):0,'managed_private_public_files_verified'=>$verified,'original_documents_verified'=>$documents,'preexisting_unavailable_document_count'=>$preexistingMissing,'B_190000_count'=>$migration,'flags_unchanged'=>true,'migrations_run'=>0,'business_writes'=>0,'functional_acceptance_repeated'=>false,'tables'=>$tables];
|
|
$file=__DIR__.'/PRESERVACAO-'.strtoupper($phase).'.json';if(is_file($file))throw new RuntimeException('Preserve proof');file_put_contents($file,json_encode($proof,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR).PHP_EOL);echo json_encode(array_diff_key($proof,array_flip(['tables'])),JSON_UNESCAPED_UNICODE).PHP_EOL;if($differences)exit(2);
|
|
}finally{foreach([$active,$clone]as$db)$db->exec('ROLLBACK');}
|