from pathlib import Path from datetime import datetime, timezone from urllib.request import Request, build_opener, HTTPSHandler, HTTPCookieProcessor, HTTPRedirectHandler from urllib.error import HTTPError from urllib.parse import unquote, urlparse, urljoin from http.cookiejar import CookieJar import json, ssl, subprocess, hashlib, hmac, struct, base64, time, sys OUT=Path(__file__).resolve().parent; ROOT=OUT.parents[1] QA=ROOT/'storage/app/private/investmoz-v2/portal-audit/portal-stability-source-20261011_083742' BASE='https://portal-investidor.test:18445' metadata_only='--metadata-only' in sys.argv DEST=OUT/'case32-C148-stale-condition-HTTP-QA-20261014.json' assert not DEST.exists() version=subprocess.check_output(['C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe','-r',"echo hash_file('xxh128', 'public/build/manifest.json');"],cwd=QA,text=True).strip() class NoRedirect(HTTPRedirectHandler): def redirect_request(self,*args,**kwargs): return None jar=CookieJar(); client=build_opener(HTTPSHandler(context=ssl.create_default_context()),HTTPCookieProcessor(jar),NoRedirect()) proof={'at':datetime.now(timezone.utc).isoformat(),'base_review':'396c691930bc','URL':BASE,'QA_account':24, 'purpose':'C148: stale resolved condition generated by the previous component; backend refusal preserved','requests':[],'active_changes':0, 'credentials_codes_cookies_or_bodies_persisted':False,'no_successful_transition_or_save':True,'visual_acceptance':False} def call(method,path,data=None,inertia=False,native=False): headers={'Accept':'text/html' if native else 'application/json'} if inertia: headers.update({'X-Inertia':'true','X-Inertia-Version':version}) if method!='GET': tokens=[c.value for c in jar if c.name=='XSRF-TOKEN']; assert len(tokens)==1 headers.update({'Content-Type':'application/json','X-XSRF-TOKEN':unquote(tokens[0])}) request=Request(BASE+path,data=json.dumps(data).encode() if data is not None else None,headers=headers,method=method) try:r=client.open(request,timeout=20) except HTTPError as e:r=e status=r.code;location=r.headers.get('Location');raw=r.read();r.close() if location: dest=urlparse(urljoin(BASE,location));assert dest.hostname=='portal-investidor.test' and dest.port==18445 proof['requests'].append({'method':method,'path':path,'status':status,'redirect_path':urlparse(location).path if location else None}) try:body=json.loads(raw) except (ValueError,UnicodeDecodeError):body={} return status,body authenticated=False;stage='QA_guard' try: status,runtime=call('GET','/_qa/runtime');assert status==200 assert runtime['target']['database']=='stability_consumers_20261011_084534_test' and int(runtime['target']['port'])==55441 proof['target']=runtime['target'] actor=json.loads((ROOT/'storage/app/private/investmoz-v2/portal-audit/profiles-v1-actors-private.json').read_text(encoding='utf-8'))['validator'];assert actor['id']==24 stage='own_synthetic_session';assert call('GET','/login')[0]==200 status,body=call('POST','/login',{'email':actor['email'],'password':actor['password'],'remember':False});assert status==200 and body.get('two_factor') secret=actor.get('totp_secret',actor.get('secret')).replace(' ','').upper() key=base64.b32decode(secret+'='*((8-len(secret)%8)%8));digest=hmac.new(key,struct.pack('>Q',int(time.time())//30),hashlib.sha1).digest();offset=digest[-1]&15 code=str((struct.unpack('>I',digest[offset:offset+4])[0]&0x7FFFFFFF)%1000000).zfill(6) assert call('POST','/two-factor-challenge',{'code':code})[0] in [200,204,302,303] authenticated=True;del code,key,secret,digest stage='current_review_context';status,page=call('GET','/minhas-oportunidades/32/view',inertia=True);assert status==200 props=page['props'];assert props['auth']['user']['id']==24 and props['workflowState']=='in_review' conditions=props['profileContext']['conditions'];condition=next(c for c in conditions.values()if c['gate']=='land_legal_review') assert condition['status']=='resolved' assert props['profileContext']['reviews']['land_legal_review']['decision']=='approved' before=(props['etag'],hashlib.sha256(json.dumps(props['profileContext'],sort_keys=True).encode()).hexdigest()) stage='reject_stale_condition' status,body=call('POST','/minhas-oportunidades/32/workflow',{'etag':props['etag'],'action':'review_gate', 'reason':'Ensaio técnico QA: recusar a condição legal já resolvida numa revisão diferente.', 'gate':'cadastral_screening','gate_decision':'approved','evidence_document_ids':props['values']['canonical']['documents'], 'resolve_condition_ids':[condition['id']]}) assert status==422 and 'resolve_condition_ids'in body.get('errors',{}) proof['controlled_reproduction']={'status':status,'reused_condition_gate':'land_legal_review','reused_condition_status':'resolved', 'next_gate':'cadastral_screening','validation_fields':list(body['errors']), 'source':'Actual previous component callbacks reproduce this stale request; not a manual failure.'} stage='recover_unchanged';status,page=call('GET','/minhas-oportunidades/32/view',inertia=True);assert status==200 after=page['props'];assert before==(after['etag'],hashlib.sha256(json.dumps(after['profileContext'],sort_keys=True).encode()).hexdigest()) proof.update(result='passed',workflow_context_and_ETag_unchanged=True,legal_review_and_resolved_condition_preserved=True, remaining_reviews_not_written=True,server_authorization_and_condition_validation_not_relaxed=True) except Exception as error:proof.update(result='stopped',stage=stage,error_type=type(error).__name__) finally: if authenticated: try:proof['own_test_session_logout_status']=call('POST','/logout',{},native=True)[0] except Exception as error:proof['logout_error_type']=type(error).__name__ jar.clear();DEST.write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');print(json.dumps(proof,ensure_ascii=False)) raise SystemExit(0 if proof['result']=='passed' else 1)