"""Follow dashboard destinations on the existing guarded QA server. No visual claim.""" import base64 import hashlib import hmac import http.cookiejar import json import re import struct import subprocess import sys import time import urllib.error import urllib.parse import urllib.request import uuid from datetime import datetime, timezone from pathlib import Path root = Path(__file__).resolve().parent.parent sys.stdout.reconfigure(encoding='utf-8') private = root / 'storage/app/private/investmoz-v2/portal-audit' php = Path.home() / '.config/investmoz/php-8.5.11/php.exe' target = json.loads((private.parent / 'opportunity-resources-backup-proof.json').read_text(encoding='utf-8-sig'))['restored_target'] assert re.fullmatch(r'desk_restore_\d{8}_\d{6}_test', target['database']) and int(target['port']) == 55441 expected = target['database'] + ':55441' manifest_path = root / 'public/build-qa-opportunities/manifest.json' manifest = json.loads(manifest_path.read_text(encoding='utf-8')) version = subprocess.check_output([str(php), '-r', "echo hash_file('xxh128','public/build-qa-opportunities/manifest.json');"], cwd=root, text=True).strip() actors = json.loads((private / 'resource-http-actors-private.json').read_text(encoding='utf-8-sig')) events = [] def snapshot(): return json.loads(subprocess.check_output([str(php), 'tools/portal-dashboard-qa-snapshot.php'], cwd=root, text=True)) def new_session(): global jar, opener jar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) def call(method, path, data=None, status=200, inertia=False, raw=False): assert path.startswith('/') and not path.startswith('//') headers = {'Accept': 'application/json' if inertia or data is not None else 'text/html', 'Content-Type': 'application/json'} for cookie in jar: if cookie.name == 'XSRF-TOKEN': headers['X-XSRF-TOKEN'] = urllib.parse.unquote(cookie.value) if inertia: headers.update({'X-Inertia': 'true', 'X-Inertia-Version': version}) request = urllib.request.Request('http://127.0.0.1:18097' + path, data=None if data is None else json.dumps(data).encode(), headers=headers, method=method) try: response = opener.open(request) except urllib.error.HTTPError as error: response = error assert response.headers.get('X-Investmoz-QA-Target') == expected, 'QA header mismatch; refused' body = response.read() assert response.status == status, f'{method} {path.split("?")[0]}: expected {status}, observed {response.status}; body withheld' events.append({'method': method, 'path': path.split('?')[0], 'status': response.status, 'qa_target_verified': True}) return body if raw else json.loads(body) if body else None def login(role): call('GET', '/login', raw=True) account = actors[role] result = call('POST', '/login', {k: account[k] for k in ['email', 'password']}) required = bool(result.get('two_factor')) if required: assert account['totp_secret'] digest = hmac.new(base64.b32decode(account['totp_secret']), struct.pack('>Q', int(time.time()) // 30), hashlib.sha1).digest() offset = digest[-1] & 15 code = f'{(struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7fffffff) % 1000000:06d}' call('POST', '/two-factor-challenge', {'code': code}, status=204) return required if '--report-access-only' in sys.argv: before = snapshot() new_session() login('manager') report = call('GET', '/qa-auditoria/pedidos-abertos', raw=True) assert hashlib.sha256(report).hexdigest() == hashlib.sha256((private / 'pedidos-abertos.html').read_bytes()).hexdigest() assert report.count(b'