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, urljoin, urlparse from http.cookiejar import CookieJar import base64 import hashlib import hmac import json import ssl import struct import subprocess import sys import time OUT = Path(__file__).resolve().parent ROOT = OUT.parents[1] BASE = 'https://portal-investidor.test:18445' reauth_check = '--reauth-20261014' in sys.argv DEST = OUT / ('case32-reauth-HTTP-QA-20261014.json' if reauth_check else 'case32-feedback-HTTP-QA-verified-props-20261013.json' if '--verified-props' in sys.argv else 'case32-feedback-HTTP-QA-protocol-corrected-20261013.json' if '--protocol-corrected' in sys.argv else 'case32-feedback-HTTP-QA-20261013.json') assert not DEST.exists(), 'No repeated targeted HTTP probe' QA = ROOT / 'storage/app/private/investmoz-v2/portal-audit/portal-stability-source-20261011_083742' asset_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() assert len(asset_version) == 32 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', 'base': BASE, 'QA_account': 24, 'purpose': 'Targeted error-response regression, no successful workflow transition', 'requests': [], 'active_changes': 0, 'password_or_MFA_changes': 0, 'visual_acceptance': False, 'previous_manual_failure_field_unknown': True, 'credentials_or_codes_persisted': False, 'cookie_values_persisted': False} def call(method, path, data=None, inertia=False, native=False): headers = {'Accept': 'text/html' if native else 'application/json'} if inertia: headers['X-Inertia'] = 'true' headers['X-Inertia-Version'] = asset_version if method != 'GET': tokens = [cookie.value for cookie in jar if cookie.name == 'XSRF-TOKEN'] assert len(tokens) == 1, 'QA CSRF cookie required' headers['X-XSRF-TOKEN'] = unquote(tokens[0]) headers['Content-Type'] = 'application/json' req = Request(BASE + path, data=json.dumps(data).encode() if data is not None else None, headers=headers, method=method) try: response = client.open(req, timeout=20) except HTTPError as error: response = error status = response.code location = response.headers.get('Location') raw = response.read() response.close() if location: parsed = urlparse(urljoin(BASE, location)) assert parsed.hostname == 'portal-investidor.test' and parsed.port == 18445, 'QA redirect guard' 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 = 'runtime_guard' try: status, runtime = call('GET', '/_qa/runtime') assert status == 200 and 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 = 'synthetic_QA_login' 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') is True stage = 'synthetic_QA_MFA' secret = actor.get('totp_secret', actor.get('secret')) normalized = secret.replace(' ', '').upper() key = base64.b32decode(normalized + '=' * ((8 - len(normalized) % 8) % 8)) digest = hmac.new(key, struct.pack('>Q', int(time.time()) // 30), hashlib.sha1).digest() offset = digest[-1] & 15 otp = str((struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7FFFFFFF) % 1000000).zfill(6) status, _ = call('POST', '/two-factor-challenge', {'code': otp}) assert status in [200, 204, 302, 303] authenticated = True del otp, key, secret, normalized, digest stage = 'authorized_QA_page' status, page = call('GET', '/minhas-oportunidades/32/view', inertia=True) assert status == 200 and page['props']['auth']['user']['id'] == 24 props = page['props'] if reauth_check: assert props['profileReauthenticationRequired'] is False proof['fresh_session_page_has_no_reauthentication_block'] = True assert props['workflowState'] == 'submitted' and 'start_review' in props['profileActions'] # Internal model version is deliberately hidden from the page; compare its ETag. before = (props['workflowState'], props['etag'], hashlib.sha256(json.dumps(props['values'], sort_keys=True).encode()).hexdigest()) stage = 'validation_exception_response' status, body = call('POST', '/minhas-oportunidades/32/workflow', { 'etag': props['etag'], 'action': 'start_review', 'reason': '', 'correction_items': []}) assert status == 422 and 'reason' in body.get('errors', {}) proof['structured_422_reason_errors_returned'] = True proof['structured_422_field_names'] = list(body['errors']) stage = 'HTTP_exception_response' status, body = call('POST', '/minhas-oportunidades/32/workflow', { 'etag': props['etag'], 'action': 'request_correction', 'reason': 'Ensaio técnico QA: resposta a indicação de correção ausente.', 'correction_items': []}) assert status == 422 and 'Indique campos e documentos a corrigir' in body.get('message', '') proof['422_without_field_map_has_actionable_message'] = True stage = 'unchanged_workflow_recovery' status, page_after = call('GET', '/minhas-oportunidades/32/view', inertia=True) assert status == 200 after_props = page_after['props'] assert before == (after_props['workflowState'], after_props['etag'], hashlib.sha256(json.dumps(after_props['values'], sort_keys=True).encode()).hexdigest()) proof.update(result='passed', business_state_and_version_unchanged=True, no_successful_workflow_transition=True, session_and_restricted_denial_audit_only=True) except Exception as error: proof.update(result='stopped', stage=stage, error_type=type(error).__name__) finally: if authenticated: try: status, _ = call('POST', '/logout', {}, native=reauth_check) proof['own_test_session_logout_status'] = status proof['own_authenticated_test_session_logout_confirmed'] = status in [200, 204, 302, 303] if reauth_check and status in [200, 204, 302, 303]: status, _ = call('GET', '/minhas-oportunidades/32/view', native=True) proof['protected_return_URL_redirects_to_login_in_same_client'] = status in [302, 303] and proof['requests'][-1]['redirect_path'] == '/login' assert proof['protected_return_URL_redirects_to_login_in_same_client'] 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)