Files
Investidor-V2/outputs/investmoz-audit-current-20261012/audit-http.py
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

100 lines
7.4 KiB
Python

"""Confined QA HTTP/API checks. Never browser proof, secrets or active writes."""
from pathlib import Path
from datetime import datetime,timezone
from urllib.request import Request,build_opener,HTTPCookieProcessor,HTTPRedirectHandler
from urllib.error import HTTPError
from urllib.parse import unquote,urlparse
from http.cookiejar import CookieJar
import base64,hashlib,hmac,html,json,re,struct,sys,time
ROOT=Path(__file__).resolve().parents[2];OUT=Path(__file__).resolve().parent;PRIVATE=ROOT/'storage/app/private/investmoz-v2/portal-audit'
BASE='https://portal-investidor.test:18445';TARGET='stability_consumers_20261011_084534_test:55441'
ROLE=sys.argv[1];assert ROLE in ['anonymous','promoter','validator','publisher','manager','public','colleague','outsider','auditor','multiple']
actors=json.loads((PRIVATE/'profiles-v1-actors-private.json').read_text())
if ROLE=='manager':
actors[ROLE]=json.loads((PRIVATE/'i0-qa-actor-private.json').read_text())
correspondence=json.loads((OUT/'QA-credential-correspondence.json').read_text())
matched=next(c for c in correspondence['candidates'] if c['source_file']=='i0-qa-actor-private.json')
assert matched['password_matches'] and matched['MFA_secret_matches'] and matched['can_manage_portal']
actors[ROLE]['id']=matched['user_id']
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self,req,fp,code,msg,headers,newurl):return None
class Session:
def __init__(self):self.cookies=CookieJar();self.client=build_opener(HTTPCookieProcessor(self.cookies),NoRedirect())
def request(self,method,path,data=None,accept='text/html',check_target=True):
assert path.startswith('/') and not path.startswith('//')
headers={'Accept':accept,'Accept-Encoding':'identity'}
if data is not None:
headers['Content-Type']='application/json';headers['X-XSRF-TOKEN']=next((unquote(c.value) for c in self.cookies if c.name=='XSRF-TOKEN'),'')
try:r=self.client.open(Request(BASE+path,data=None if data is None else json.dumps(data).encode(),headers=headers,method=method),timeout=30)
except HTTPError as error:r=error
with r:body=r.read();status=r.code;metadata=r.headers
if check_target:assert metadata.get('X-Investmoz-QA-Target')==TARGET,'Unexpected application target'
return status,metadata,body
def page(body):
text=body.decode('utf-8');m=re.search(r'<script\b[^>]*data-page="app"[^>]*>(.*?)</script>',text,re.S)
if m:return json.loads(m[1])
m=re.search(r'data-page="([^"]+)"',text)
return json.loads(html.unescape(m[1])) if m else None
def otp(secret):
key=base64.b32decode(secret.upper().rstrip('=')+'='*((8-len(secret.rstrip('='))%8)%8))
digest=hmac.new(key,struct.pack('>Q',int(time.time())//30),hashlib.sha1).digest();offset=digest[-1]&15
return str((struct.unpack('>I',digest[offset:offset+4])[0]&0x7fffffff)%1000000).zfill(6)
proof={'at':datetime.now(timezone.utc).isoformat(),'role':ROLE,'base':BASE,'target':TARGET,'active_writes':0,'browser_observed':False,'TLS_bypass':False,'credentials_or_codes_recorded':False,'routes':[],'criteria':{}}
s=Session();step='isolation';exit_code=0
try:
status,_,body=s.request('GET','/_qa/runtime',check_target=False)
runtime=json.loads(body);assert status==200 and runtime['target']=={'database':'stability_consumers_20261011_084534_test','port':'55441'} or status==200 and runtime['target']=={'database':'stability_consumers_20261011_084534_test','port':55441}
proof['runtime']={'target':runtime['target'],'php':runtime['php'],'sapi':runtime['sapi'],'session':runtime['session'],'cipher':runtime['cipher']}
if ROLE!='anonymous':
a=actors[ROLE];step='normal_login';assert s.request('GET','/login')[0]==200
status,_,body=s.request('POST','/login',{'email':a['email'],'password':a['password']},'application/json');assert status in [200,204,302]
step='MFA_page';assert s.request('GET','/two-factor-challenge')[0]==200
if time.time()%30>26:time.sleep(4)
secret=a.get('totp_secret',a.get('secret'));assert secret
step='MFA_response';status,_,_=s.request('POST','/two-factor-challenge',{'code':otp(secret)},'application/json');assert status in [200,204,302]
actor_id=a.get('id',a.get('actor_id',a.get('user_id')))
step='authenticated_dashboard';status,_,body=s.request('GET','/dashboard');p=page(body);assert status==200 and p['props']['auth']['user']['id']==actor_id
proof['authentication']='normal_Fortify_login_and_MFA';proof['actor_id']=actor_id
step='literal_GET_routes'
routes=json.loads((OUT/'runtime-qa18445.json').read_text())['routes']
excluded=['user/','auth/','oauth/','two-factor','sanctum/','login','register','forgot-password','confirm-password','up','_']
for r in routes:
uri=r['uri'];method=r['methods'];requires_auth=any(m.startswith('auth') for m in r['middleware'])
if 'GET' not in method or '{' in uri or any(uri.startswith(x) for x in excluded):continue
if ROLE=='anonymous' and requires_auth:continue
if ROLE!='anonymous' and not requires_auth:continue
if uri.startswith('management/') and ROLE not in ['manager','validator','publisher','promoter','auditor','multiple']:continue
path='/'+uri.lstrip('/');step='GET '+path
status,headers,body=s.request('GET',path)
result={'route':path,'status':status,'authenticated_route':requires_auth,'action':r['action'],'middleware':r['middleware']}
if status==200:
p=page(body) if 'text/html' in headers.get('Content-Type','') else None
if p:result.update(component=p.get('component'),prop_names=list(p.get('props',{})))
elif 'json' in headers.get('Content-Type',''):
try:data=json.loads(body);result['json_shape']=list(data) if isinstance(data,dict) else 'array'
except ValueError:result['json_shape']='invalid_json'
elif status in [301,302,303,307,308]:
location=headers.get('Location','');result['redirect_path']=urlparse(location).path
assert not location or location.startswith(BASE+'/') or location.startswith('/'),'External redirect refused'
elif status==422:
try:result['error_fields']=list(json.loads(body).get('errors',{}))
except ValueError:pass
proof['routes'].append(result)
if status>=500:proof.setdefault('server_failures',[]).append({'route':path,'status':status})
if ROLE=='promoter':
step='C131_HTTP_validation';record=json.loads((OUT/'contact-whitespace-after.json').read_text())['record_id']
status,_,body=s.request('GET',f'/minhas-oportunidades/{record}/edit');p=page(body);assert status==200
etag=p['props']['etag']
status,_,body=s.request('POST',f'/minhas-oportunidades/{record}/contacts',{'etag':etag,'full_name':' A ','email':'audit-invalid-short@example.invalid','phone':'+258840000009','investor_type':'domestic'},'application/json')
errors=json.loads(body).get('errors',{});assert status==422 and 'full_name' in errors
proof['criteria']['C131_normalized_short_name_rejected']={'status':status,'field':'full_name','record_id':record}
if ROLE!='anonymous':
step='logout';status,_,_=s.request('POST','/logout',{},'application/json');assert status in [200,204,302]
proof['result']='completed_HTTP_coverage' if not proof.get('server_failures') else 'server_failures_found'
except Exception as error:
proof.update(result='stopped',step=step,error_type=type(error).__name__);exit_code=1
finally:
(OUT/('http-'+ROLE+'.json')).write_text(json.dumps(proof,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps({'result':proof['result'],'role':ROLE,'step':step,'routes':len(proof['routes']),'server_failures':proof.get('server_failures',[]),'criteria':proof['criteria'],'active_writes':0,'browser_observed':False}))
sys.exit(exit_code)