from pathlib import Path from datetime import datetime,timezone import json,hashlib,csv,zipfile,re,shutil,collections csv.field_size_limit(10000000) OUT=Path(__file__).resolve().parent;ROOT=OUT.parents[1];DOC=ROOT/'docs/investmoz/v2/auditoria-portal' load=lambda p:json.loads(p.read_text(encoding='utf-8-sig'));sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() plan=load(OUT/'authoring-plan.json');author=load(OUT/'csv-authoring-proof.json') for f,r in zip(plan['files'],author['files']): actual=list(csv.reader(Path(f['path']).open(encoding='utf-8-sig',newline='')));assert actual==f['after'];ix=actual[0].index('ID') changed=[a[ix] for a,b in zip(actual[1:],f['before'][1:])if a!=b];assert changed==['AUD-PROFILE-26'] assert sha(Path(f['path']))==r['after_sha256'];assert len(actual)==3402 before=load(OUT/'C132-preflight.json');assert sha(ROOT/'config/inertia.php')=='80c68e12bf6cb64e39931e2467b43909893cea3eb6d04c3c1e68bdcb1236dfb7';assert sha(ROOT/'app/Services/OpportunityContacts.php')==before['C131_active_hash'];assert sha(ROOT/'public/build/manifest.json')==before['build_hash'] loc=Path(load(OUT/'C132-private-location.json')['private_directory']);evidence=load(loc/'evidence-manifest-private.json') assert all(sha(loc/'diagnostics'/r['name'])==r['sha256'] and sha(ROOT/'storage/inertia-devtools'/r['name'])==r['sha256'] for r in evidence['files']) assert {p.name for p in (ROOT/'storage/inertia-devtools').iterdir()if p.is_file()}=={r['name']for r in evidence['files']} guard=load(OUT/'C132-deployment-guard-proof.json');assert guard['result']=='passed';assert load(OUT/'C132-session-revocation-QA.json')['result']=='passed';assert all(x['status']==404 for x in load(OUT/'C132-http-contained.json')['checks'][:3]);assert load(OUT/'C132-handoff-status.json')['pending_access_confirmation_ids']==[14,15,16] allmatrix=list(csv.DictReader((DOC/'matriz-requisitos.csv').open(encoding='utf-8-sig',newline=''))) integrity={'at':datetime.now(timezone.utc).isoformat(),'result':'passed','requirements':3401,'source_occurrences':sum(int(r['Quantidade de linhas de origem'])for r in allmatrix),'new_ids':0,'only_changed_requirement_this_followup':'AUD-PROFILE-26','immutable_references_and_other_rows_preserved':True,'states':dict(collections.Counter(r['Estado']for r in allmatrix)), 'matrix_sha256':sha(DOC/'matriz-requisitos.csv'),'backlog_sha256':sha(DOC/'backlog-priorizado.csv'),'original_diagnostics_and_private_snapshot_unchanged':True,'no_new_diagnostics_after_handoff_and_manual_confirmation':True,'C131_not_applied':True,'COUNTRY02_AB_C37_preserved':True,'incident_closed':False,'confirmed_holder_access_ids':[17],'pending_holder_access_ids':[14,15,16]} (OUT/'C132-followup-integrity.json').write_text(json.dumps(integrity,ensure_ascii=False,indent=2),encoding='utf-8') paths=['tools/portal-diagnostics-deployment-guard.php','tools/portal_diagnostics_deployment_guard.py','tools/portal-owner-administration-release.py','tools/portal-workflow-activation-stage.py','tools/portal-stability-activation-stage.py','tools/portal-country-activation-stage.ps1','.github/workflows/tests.yml'] manifest={'case':'C132','scope':'Incident followup only; configuration containment already applied and preserved. Deployment gates added, historical deployments not rerun. Four individual MFA handoff messages sent under explicit owner authorization; only account17 manually confirmed.', 'additional_application_code_schema_services_flags_changes':0,'only_active_database_changes_this_followup':'Five append-only incident audit events; no accounts, roles, credentials or sessions changed again','process_files_sha256':{p:sha(ROOT/p)for p in paths},'active_inertia_sha256':sha(ROOT/'config/inertia.php'), 'reversal':'Keep containment OFF, HTTPS, encryption key, original evidence and new MFA. Do not restore compromised seeds or an enabled diagnostic configuration. Reversal of deployment-helper changes is separate from incident data and must retain mandatory pre/post verification. No complete data restore performed.', 'technical_gates_limit':'Supported helpers/CI enforce the check; manual bypass or unreviewed external tools are not covered. CI remote run remains unperformed. Anonymous list/real-detail 404 is mandatory after future deployment.', 'C131_code_or_activation_included':False,'incident_closed':False} (OUT/'C132-followup-manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8') review=OUT/'C132-followup-para-revisao';assert not review.exists();review.mkdir() copies={DOC/'C132-incidente-contido.md':'relatorio-C132.md',DOC/'relatorio-executivo.md':'relatorio-executivo.md',DOC/'backlog.md':'backlog.md',DOC/'matriz-requisitos.csv':'matriz-requisitos.csv',DOC/'backlog-priorizado.csv':'backlog-priorizado.csv',OUT/'C132-followup-manifest.json':'manifesto-C132-seguimento.json',ROOT/'tools/portal-diagnostics-deployment-guard.php':'guardas/portal-diagnostics-deployment-guard.php',ROOT/'tools/portal_diagnostics_deployment_guard.py':'guardas/portal_diagnostics_deployment_guard.py'} for name in ['C132-http-contained.json','C132-session-review.json','C132-session-revocation-QA.json','C132-handoff-status.json','C132-account17-manual-recovery.json','C132-access-review.json','C132-deployment-guard-proof.json','C132-followup-audit.json','C132-followup-integrity.json',*[f'C132-account{i}-email-receipt.json'for i in [14,15,16,17]]]:copies[OUT/name]='evidencias/'+name for source,target in copies.items(): p=review/target;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,p) # Compare against actual secrets only in local memory. Never write or print them. privateValues=[r['value']for r in load(loc/'secret-candidates-private.json')if isinstance(r['value'],str)and len(r['value'])>=12] for p in (loc/'handoff-affected-users').glob('conta-*-2fas-local.html'): privateValues+=re.findall(r'([A-Z2-7]{16,})',p.read_text(encoding='utf-8')) fileManifest=[] for p in sorted(review.rglob('*')): if not p.is_file():continue t=p.read_text(encoding='utf-8-sig');assert 'otpauth://'not in t and not re.search(r'QA-[a-f0-9]{32,}',t);assert all(v not in t for v in privateValues) fileManifest.append({'file':p.relative_to(review).as_posix(),'bytes':p.stat().st_size,'sha256':sha(p)}) zipPath=OUT/'investmoz-C132-seguimento-revisao-20261012.zip';assert not zipPath.exists() with zipfile.ZipFile(zipPath,'w',zipfile.ZIP_DEFLATED,compresslevel=8)as z: for r in fileManifest:z.write(review/r['file'],r['file']) z.writestr('inventario-pacote.json',json.dumps(fileManifest,ensure_ascii=False,indent=2)) with zipfile.ZipFile(zipPath)as z:assert z.testzip()is None;assert all(hashlib.sha256(z.read(r['file'])).hexdigest()==r['sha256']for r in fileManifest) # Refresh only exported review copies; original historical ZIPs and canonical IDs remain unchanged. for name in ['C132-incidente-contido.md','relatorio-executivo.md','backlog.md','matriz-requisitos.csv','backlog-priorizado.csv']:shutil.copyfile(DOC/name,OUT/'para-revisao'/name) delivery={'result':'passed','file':str(zipPath),'sha256':sha(zipPath),'bytes':zipPath.stat().st_size,'entries':len(fileManifest)+1,'actual_secret_scan_passed':True,'original_attachments_preserved':True,'C131_code_or_activation_included':False,'pending_holder_access_ids':[14,15,16],'incident_closed':False} (OUT/'C132-followup-delivery-proof.json').write_text(json.dumps(delivery,indent=2),encoding='utf-8');print(json.dumps(delivery))