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, re 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' proof_name = sys.argv[1] if len(sys.argv) > 1 else 'case32-editor-recovery-HTTP-QA-verified-props-20261014.json' assert re.fullmatch(r'case32-editor-recovery[-A-Za-z0-9]*-20261014\.json',proof_name) DEST = OUT/proof_name 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':21, 'user_statement':sys.argv[2] if len(sys.argv) > 2 else 'os campos tem todos mais de 100 caracteres, alguma coisa está a flhar', 'purpose':'Leitura do editor e resposta canónica; divergência entre conteúdo visível relatado e versão gravada.', 'requests':[],'active_changes':0,'business_data_changes':0,'visual_acceptance':False, 'credentials_codes_cookies_or_field_contents_persisted':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: response = client.open(request,timeout=20) except HTTPError as error: response = error status = response.code; location = response.headers.get('Location'); raw = response.read(); response.close() if location: redirect = urlparse(urljoin(BASE,location)); assert redirect.hostname == 'portal-investidor.test' and redirect.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'))['promoter']; assert actor['id'] == 21 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 = 'read_editor'; status, page = call('GET','/minhas-oportunidades/32/edit',inertia=True); assert status == 200 props = page['props']; assert props['auth']['user']['id'] == 21 and props['profileMode'] canonical = props['values']['canonical'] proof['editor'] = {'record_id':props['record']['id'], 'state':props['workflowState'],'can_edit':props['canEditDraft'], 'demand_statement_length':len(canonical.get('demand_statement','')), 'executive_summary_length':len(canonical.get('executive_summary','')), 'submission_limits':props['canonicalOptions']['submissionTextLimits']['demand_statement']} before = (props['etag'],hashlib.sha256(json.dumps(props['values'],sort_keys=True).encode()).hexdigest()) stage = 'read_canonical_response'; status, body = call('GET','/minhas-oportunidades/32/response'); assert status == 200 response_data = body['data']; response_statement = response_data['demand_statement'] # The adapter may expose inline metadata around the value. Never persist contents. if isinstance(response_statement,dict): response_statement = response_statement.get('value',response_statement.get('text')) assert isinstance(response_statement,str) proof['response'] = {'version':response_data['version'],'state':response_data['status'], 'demand_statement_length':len(response_statement), 'same_text_as_editor':response_statement == canonical['demand_statement'], 'validation_error_paths':list(response_data['validation_result']['errors'])} stage = 'check_compilation'; status, manifest = call('GET','/build/manifest.json'); assert status == 200 local_manifest = json.loads((QA/'public/build/manifest.json').read_text(encoding='utf-8')); assert manifest == local_manifest entry = manifest['resources/js/pages/management/opportunity-draft.tsx']['file']; assert '..' not in entry and entry.startswith('assets/') response = client.open(Request(BASE+'/build/'+entry),timeout=20); assert response.code == 200 bundle = response.read(); response.close() assert hashlib.sha256(bundle).digest() == hashlib.sha256((QA/'public/build'/entry).read_bytes()).digest() proof['served_editor_bundle_sha256'] = hashlib.sha256(bundle).hexdigest() proof['served_editor_bundle_matches_QA'] = True stage = 'verify_unchanged'; status, page = call('GET','/minhas-oportunidades/32/edit',inertia=True); assert status == 200 after = page['props']; assert before == (after['etag'],hashlib.sha256(json.dumps(after['values'],sort_keys=True).encode()).hexdigest()) proof.update(result='passed',business_values_and_ETag_unchanged=True, limits=['Leitura HTTP não identifica o valor atualmente digitado no navegador do responsável.', 'Conteúdos de formulários e corpos de pedidos não foram exportados.', 'Sem escrita de rascunho ou nova tentativa de submissão neste diagnóstico.']) except Exception as error: proof.update(result='stopped',stage=stage,error_type=type(error).__name__) if isinstance(error,KeyError) and error.args[0] in ['profileMode','management_version','demand_statement','data','validation_result']: proof['missing_expected_metadata_field'] = error.args[0] finally: if authenticated: try: proof['own_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)