Files
Investidor-V2/outputs/investmoz-audit-current-20261012/C132-backup.php
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

31 lines
5.1 KiB
PHP

<?php
// Incident backup: active source read only; restore and recovery rehearsal exclusively on isolated 55441 *_test.
ini_set('zend.exception_ignore_args','1');set_exception_handler(function(Throwable $e){fwrite(STDERR,'C132 backup stopped: '.$e::class.' '.basename($e->getFile()).':'.$e->getLine());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'||!empty($c['url'])||(int)$c['port']!==5432||$c['database']!=='investemoz'||!in_array($c['host'],['localhost','127.0.0.1'],true))throw new RuntimeException('Source refused');
$source=new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$source->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity=$source->query('SELECT current_database() as database,inet_server_port() as port')->fetch(PDO::FETCH_ASSOC);if($identity['database']!=='investemoz'||(int)$identity['port']!==5432)throw new RuntimeException('Identity refused');
$location=json_decode(ltrim(file_get_contents(__DIR__.'/C132-private-location.json'),"\xEF\xBB\xBF"),true,512,JSON_THROW_ON_ERROR)['private_directory'];
$dir=$location.'/recovery';if(is_dir($dir))throw new RuntimeException('Existing recovery path; inspect first');mkdir($dir,0700,true);
$clone='c132_incident_'.gmdate('Ymd_His').'_test';$dump=$dir.'/active-before-credential-response.dump';$snapshot=$source->query('SELECT pg_export_snapshot()')->fetchColumn();
$run=function(array $args,string $password){$p=new Symfony\Component\Process\Process($args,null,['PGPASSWORD'=>$password]);$p->setTimeout(240);$p->run();if(!$p->isSuccessful())throw new RuntimeException('Backup process failed');};
$bin='C:/Program Files/PostgreSQL/17/bin/';$run([$bin.'pg_dump.exe','-h',$c['host'],'-p','5432','-U',$c['username'],'-d','investemoz','-Fc','--snapshot='.$snapshot,'-f',$dump],$c['password']);
$maintenance=new PDO('pgsql:host=127.0.0.1;port=55441;dbname=postgres','postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
if((int)$maintenance->query('SELECT inet_server_port()')->fetchColumn()!==55441||!preg_match('/^c132_incident_\d{8}_\d{6}_test$/',$clone))throw new RuntimeException('Restore target refused');
$maintenance->exec('CREATE DATABASE "'.$clone.'"');$run([$bin.'pg_restore.exe','-h','127.0.0.1','-p','55441','-U','postgres','-d',$clone,'--exit-on-error','--no-owner','--no-privileges',$dump],'');
$restored=new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$clone,'postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$restored->exec('BEGIN READ ONLY');
$tables=[];
foreach($source->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC)as$t){
$name='"'.str_replace('"','""',$t['schemaname']).'"."'.str_replace('"','""',$t['tablename']).'"';$sql='SELECT row_to_json(t)::text FROM '.$name.' t ORDER BY row_to_json(t)::text';
$a=$source->query($sql)->fetchAll(PDO::FETCH_COLUMN);$b=$restored->query($sql)->fetchAll(PDO::FETCH_COLUMN);if($a!==$b)throw new RuntimeException('Restored table differs');$tables[$name]=['rows'=>count($a),'sha256'=>hash('sha256',implode("\n",$a))];
}
$seq="SELECT * FROM pg_sequences WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY schemaname,sequencename";
$sequences=$source->query($seq)->fetchAll(PDO::FETCH_ASSOC);if($sequences!==$restored->query($seq)->fetchAll(PDO::FETCH_ASSOC))throw new RuntimeException('Sequence mismatch');
$source->exec('ROLLBACK');$restored->exec('ROLLBACK');
$fileHashes=[];foreach(['.env','config/inertia.php','public/build/manifest.json','app/Services/OpportunityContacts.php']as$rel){$name=str_replace('/','__',$rel);$dest=$dir.'/'.$name;copy($root.'/'.$rel,$dest);$fileHashes[$rel]=hash_file('sha256',$dest);if($fileHashes[$rel]!==hash_file('sha256',$root.'/'.$rel))throw new RuntimeException('Recovery file differs');}
$private=['at'=>gmdate('c'),'target'=>$identity,'restore_target'=>['database'=>$clone,'port'=>55441],'dump'=>$dump,'dump_sha256'=>hash_file('sha256',$dump),'tables'=>$tables,'sequence_count'=>count($sequences),'recovery_file_hashes'=>$fileHashes,'restore_verified'=>true,'c132_disabled_in_recovery'=>true,'active_writes'=>0];
file_put_contents($dir.'/backup-proof-private.json',json_encode($private,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
$safe=['at'=>$private['at'],'target'=>$identity,'restore_target'=>$private['restore_target'],'tables'=>count($tables),'sequences'=>count($sequences),'all_table_rows_and_hashes_equal'=>true,'restore_verified'=>true,'active_writes'=>0,'dump_sha256'=>$private['dump_sha256'],'recovery_config_preserves_DevTools_OFF'=>true,'key_not_rotated'=>true,'private_snapshot_outside_webroot'=>true];
file_put_contents(__DIR__.'/C132-backup-restoration.json',json_encode($safe,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($safe,JSON_THROW_ON_ERROR);