from pathlib import Path from datetime import datetime, timezone from hashlib import sha256 import importlib.util, json, sys, uuid, copy OUT=Path(__file__).resolve().parent;phase=sys.argv[1];assert phase in ['upload','workflow'] dest=OUT/f'option-B3-project-{phase}-HTTP.json';resume='--resume-scan'in sys.argv if resume: assert phase=='workflow';prior=json.loads(dest.read_text(encoding='utf-8')) assert prior['result']=='stopped'and prior['step']=='own_document_access' assert prior['requests'][-2]['status']==423 archived=OUT/'option-B3-project-workflow-HTTP.scan-pending.json';assert not archived.exists();archived.write_bytes(dest.read_bytes()) else:assert not dest.exists(),'Inspect saved attempt before repeating' spec=importlib.util.spec_from_file_location('transport',OUT/'consumer-lot-lib.py');lib=importlib.util.module_from_spec(spec);spec.loader.exec_module(lib) state_path=OUT/'option-B3-project-progress.json' state=json.loads(state_path.read_text(encoding='utf-8'))if state_path.exists()else{'opportunity_id':30,'creation_key':str(uuid.uuid4())} fixture=json.loads((OUT/'option-B3-PDF-fixture.json').read_text(encoding='utf-8')) assert fixture['target']=={'database':'stability_consumers_20261011_084534_test','port':55441} proof={'at':datetime.now(timezone.utc).isoformat(),'target':lib.TARGET,'scope':'B unchanged','phase':phase, 'opportunity_id':30,'active_writes':0,'browser_observed':False,'criteria':{}} clients=[];step='login';exit_code=1 def checkpoint():state_path.write_text(json.dumps(state,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') def view(c):return c.call('GET','/minhas-oportunidades/30/view',json_response=False) def action(c,kind,expected=200,**extra): return c.call('POST','/minhas-oportunidades/30/workflow',{'etag':view(c)['etag'],'action':kind, 'reason':'SIMULAÇÃO QA B: licença e documento fictícios; decisão interna não concede licença externa',**extra},expected=expected) def download(c,expected=200): route=f"/minhas-oportunidades/30/resources/documents/{state['resource_id']}/download" status,headers,body=c.request('GET',route,accept='application/json') lib.events.append({'method':'GET','route':route,'status':status,'expected':expected}) assert status==expected if expected==200:assert 'application/pdf'in headers.get('Content-Type','')and sha256(body).hexdigest()==fixture['sha256'] try: owner=lib.Client().login('promoter');clients.append(owner);x=view(owner) if phase=='upload': assert x['workflowState']=='published';state['baseline_reviews']=copy.deepcopy(x['profileContext']['reviews']);checkpoint() action(owner,'request_revision');step='upload' metadata={'title':'SIMULAÇÃO QA - licença aplicável do projeto 30, sem validade jurídica', 'category':'license','issuer':'Entidade fictícia de licenciamento QA','edition':'QA 20261013', 'source_date':'2026-10-13','valid_until':'2027-10-13','classification':'restricted','visibility':'internal', 'section':'Projeto 30 - identificação da licença e evidência', 'supported_statement':'Exemplar sintético. Não representa ato externo nem direito real.'} data={'etag':view(owner)['etag'],'creation_key':state['creation_key'], 'reason':'SIMULAÇÃO QA: documento próprio da licença, original preservado e divulgação restrita', 'payload':json.dumps(metadata,ensure_ascii=False)} uploaded=owner.call('POST','/minhas-oportunidades/30/resources/documents',data,expected=201,file=fixture['path']) state['resource_id']=uploaded['id'];checkpoint() row=next(d for d in owner.call('GET','/minhas-oportunidades/30/resources',json_response=False)['resources']['documents']if d['id']==state['resource_id']) state['document_id']=row['document_id'];checkpoint() assert row['file']['sha256'].strip()==fixture['sha256'] download(owner,423) # Preserve the same operation key after retry, with a fresh concurrency token. data['etag']=view(owner)['etag'];owner.call('POST','/minhas-oportunidades/30/resources/documents',data,expected=409,file=fixture['path']) data['etag']=view(owner)['etag'];data['creation_key']=str(uuid.uuid4()) owner.call('POST','/minhas-oportunidades/30/resources/documents',data,expected=422,file=fixture['path']) assert 'file'in lib.events[-1]['error_fields'] proof['criteria']['upload_quarantine_replays']={'upload':201,'download_before_scan':423, 'same_creation_key':409,'same_bytes_new_key':422,'sha256':fixture['sha256'],'restricted':True} proof['result']='awaiting_own_scan';exit_code=0 else: assert x['workflowState']=='needs_information';step='own_document_access';download(owner) outsider=lib.Client().login('outsider');clients.append(outsider);download(outsider,403) download(lib.Client(),401) canonical=x['values']['canonical'];canonical['licenses'][0]={ 'name':'Licença aplicável - SIMULAÇÃO QA, sem validade jurídica', 'authority':'Entidade fictícia de licenciamento QA','status':'issued', 'number':'SIM-QA-B3-LIC-30','issued_at':'2026-10-13','expires_at':'2027-10-13'} canonical['documents']=list(dict.fromkeys([*canonical['documents'],state['resource_id']])) canonical['evidences'].append({'title':'SIMULAÇÃO QA - evidência própria da licença do projeto 30', 'evidence_type':'license','document_id':state['resource_id'], 'description':'PDF sintético restrito; não é licença externa real.'}) owner.call('PUT','/minhas-oportunidades/30/draft',{'etag':view(owner)['etag'],'canonical':canonical, 'reason':'SIMULAÇÃO QA: aplicabilidade e referência explícita do documento próprio'}) action(owner,'submit');x=view(owner);mat=x['profileContext']['materiality'] assert set(mat['reopened'])=={'legal_territorial_review'}and mat['retained']==['technical_review'] for k in ['hash','actor_id','at']:assert x['profileContext']['reviews']['technical_review'][k]==state['baseline_reviews']['technical_review'][k] proof['criteria']['materiality']={'reopened':mat['reopened'],'retained':mat['retained'],'retained_hash_actor_time_preserved':True} step='independent_decision';validator=lib.Client().login('validator');clients.append(validator);download(validator) action(validator,'start_review');action(validator,'approve',expected=422) action(validator,'review_gate',gate='legal_territorial_review',gate_decision='approved',evidence_document_ids=[state['resource_id']]) action(validator,'approve');publisher=lib.Client().login('publisher');clients.append(publisher);download(publisher) action(publisher,'publish',confirm_publication=True,preview_hash=view(publisher)['profileContext']['approval']['hash']) owner.logout();clients.remove(owner);owner=lib.Client().login('promoter');clients.append(owner);final=view(owner) assert final['workflowState']=='published'and final['profileContext']['publication']['visibility']=='internal' assert final['values']['canonical']['licenses']==canonical['licenses'] assert any(e['document_id']==state['resource_id']for e in final['values']['canonical']['evidences']) assert final['profileContext']['reviews']['legal_territorial_review']['evidence_document_ids']==[state['resource_id']] download(owner) proof['criteria']['own_licensed_evidence']={'resource_id':state['resource_id'],'document_id':state['document_id'], 'sha256':fixture['sha256'],'promoter_validator_publisher_access':200,'other_organization':403,'anonymous':401, 'review_binds_specific_resource':True,'new_session_download_hash_matches':True} proof['criteria']['workflow_recovery']={'approved_by':24,'published_by':25,'visibility':'internal', 'license_status':'issued','synthetic_explicit':True,'new_session':True,'license_and_reference_preserved':True, 'no_external_right_or_authority_decision_claimed':True} proof['result']='passed';exit_code=0 except Exception as error: proof.update(result='stopped',step=step,error_type=type(error).__name__) finally: for c in clients: try:c.logout() except Exception:pass proof['requests']=lib.events;dest.write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') print(json.dumps({k:v for k,v in proof.items()if k!='requests'},ensure_ascii=False)) raise SystemExit(exit_code)