53 lines
7.1 KiB
Python
53 lines
7.1 KiB
Python
from pathlib import Path
|
|
import urllib.request,urllib.error,urllib.parse,http.cookiejar,json,re,hashlib,subprocess,time,hmac,base64,struct
|
|
out=Path(__file__).resolve().parent;private=Path('C:/Users/macbook/.config/investmoz/documentos-publicos-QA-20261018');f=json.loads((private/'fixture-private.json').read_text('utf-8'));base='http://127.0.0.1:18546';checks=[];events=[];(out/'depois').mkdir(exist_ok=True)
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self,*args,**kwargs):return None
|
|
def session():
|
|
jar=http.cookiejar.CookieJar();return jar,urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar),NoRedirect())
|
|
def call(path,s=None,data=None,expected=200):
|
|
jar,op=s or session();headers={'Accept':'application/json' if path.startswith('/api/') or data is not None else 'text/html'};body=None
|
|
if data is not None:body=json.dumps(data).encode();headers.update({'Content-Type':'application/json','X-XSRF-TOKEN':next((urllib.parse.unquote(c.value) for c in jar if c.name=='XSRF-TOKEN'),'')})
|
|
try:r=op.open(urllib.request.Request(base+path,data=body,headers=headers),timeout=45)
|
|
except urllib.error.HTTPError as e:r=e
|
|
raw=r.read();assert r.headers.get('X-QA-Target')=='public_documents_20261018_test:55441';events.append({'path':path,'status':r.status,'sha256':hashlib.sha256(raw).hexdigest()})
|
|
assert r.status in ([expected] if isinstance(expected,int) else expected),(path,r.status,raw[:120]);return raw,r.headers
|
|
def props(path,s=None):
|
|
raw,_=call(path,s);text=raw.decode('utf-8');match=re.search(r'<script[^>]*data-page="app"[^>]*>(.*?)</script>',text,re.S);assert match,path;return json.loads(match.group(1))['props']
|
|
def check(label,ok,evidence):
|
|
checks.append({'criterion':label,'result':'observado' if ok else 'falhou','evidence':evidence});assert ok,label
|
|
def login(role):
|
|
s=session();a=f['actors'][role];call('/login',s);call('/login',s,{'email':a['email'],'password':a['password']},(200,204,302));digest=hmac.new(base64.b32decode(a['secret']),struct.pack('>Q',int(time.time()/30)),hashlib.sha1).digest();i=digest[-1]&15;code=str((struct.unpack('>I',digest[i:i+4])[0]&0x7fffffff)%1000000).zfill(6);call('/two-factor-challenge',s,{'code':code},(200,204,302));return s
|
|
forbidden={'links','documentary_evidence','basis_reference','source_reference','last_reviewed_by','last_reviewed_at','independent_review','metadata_version','document_id','file_name','sha256','relationship','applicability','review_status','target_key','version_no'}
|
|
def public(rows,label):
|
|
for r in rows:
|
|
assert not forbidden.intersection(r), (label,forbidden.intersection(r))
|
|
text=json.dumps(r,ensure_ascii=False)
|
|
assert not re.search(r'fiscal\.[\w.]+|theme\s*:|\b(?:supports|cites|evidence|SHA-?256)\b|docs/investmoz|outputs/|mantida em privado',text,re.I),(label,r['id'])
|
|
assert r['title'] and r['download_url'] and r['context_actions'] is not None
|
|
check(label,True,{'resources':len(rows),'technical_metadata_sent':False})
|
|
try:
|
|
for label,path in [('legislacao','/legislacao'),('documentos','/documentos')]:
|
|
p=props(path);rows=p['resources']['data'];public(rows,'Projeção pública '+label);old=json.loads((out/'antes'/f'{label}.json').read_text('utf-8'))['resources'];check('Identidades e contagens preservadas '+label,[r['id'] for r in rows]==[r['id'] for r in old['data']] and p['resources']['total']==old['total'],{'ids':[r['id'] for r in rows],'total':p['resources']['total']});(out/'depois'/f'{label}.json').write_text(json.dumps(p,ensure_ascii=False,indent=2),'utf-8')
|
|
laws=props('/legislacao')['resources']['data'];state=json.loads((out/'ESTADO-ANTES.json').read_text('utf-16'));docids=state['public_resources']
|
|
# Read expected public binary digests from the isolated database only.
|
|
cmd=['C:/Program Files/PostgreSQL/17/bin/psql.exe','-h','127.0.0.1','-p','55441','-U','postgres','-d',f['database'],'-Atc',"SELECT json_object_agg(id,sha256) FROM documents"]
|
|
digests=json.loads(subprocess.run(cmd,check=True,capture_output=True,text=True).stdout)
|
|
for r in laws:
|
|
p=props('/documentos/'+str(r['id']));public([p['resource']],'Ficha '+str(r['id']));assert p['resource']['context_actions']==r['context_actions'];(out/'depois'/f"ficha-{r['id']}.json").write_text(json.dumps(p,ensure_ascii=False,indent=2),'utf-8')
|
|
for action in ['view','download']:
|
|
binary,h=call(f"/documentos/{r['id']}/{action}");expected=digests[docids[str(r['id'])]].strip();check('Consulta/download íntegro '+str(r['id'])+' '+action,hashlib.sha256(binary).hexdigest()==expected and ('inline' if action=='view' else 'attachment') in h['Content-Disposition'],{'bytes':len(binary),'sha256':expected,'disposition':h['Content-Disposition']})
|
|
raw,_=call('/api/v1/documents/recommendations');rec=json.loads(raw)['data'];public(rec,'API de recomendações');old=json.loads((out/'antes/recomendacoes.json').read_text('utf-8'))['data'];check('Recomendações mantêm seleção',[r['id'] for r in rec]==[r['id'] for r in old],{'ids':[r['id'] for r in rec]});(out/'depois/recomendacoes.json').write_bytes(raw)
|
|
for path in ['/legislacao?q=22%2F2022','/legislacao?topic=iva','/documentos?module%5B0%5D=simulator','/documentos?document_type=legislation']:
|
|
p=props(path);public(p['resources']['data'],'Filtro '+path)
|
|
call('/management/portal-services',expected=302)
|
|
manager=login('authorized');managed=props('/management/portal-services',manager);check('Gestão autorizada preserva rastreabilidade',any(r['links'] for r in managed['resources']) and any('sha256' in d for d in managed['documents']),{'resources':len(managed['resources']),'relations_available':True,'hashes_available':True,'revisions_available':all('revisions' in r for r in managed['resources'])});(out/'depois/gestao-resumo.json').write_text(json.dumps({'relations':sum(len(r['links']) for r in managed['resources']),'revisions':sum(len(r['revisions']) for r in managed['resources']),'document_hashes':len(managed['documents'])}),'utf-8')
|
|
denied=login('unprivileged');call('/management/portal-services',denied,expected=403);check('Permissões de gestão',True,{'anonymous':302,'unprivileged':403,'authorized_with_MFA':200})
|
|
for resourceid in state['private_resource_ids'][:2]:
|
|
for suffix in ['', '/view','/download']:call('/documentos/'+str(resourceid)+suffix,expected=404)
|
|
check('Proteção de recursos não públicos em fixtures transacionais',all(c['result']=='observado' for c in json.loads((out/'PROVAS-ACESSO-PRIVADO-QA.json').read_text('utf-8'))['checks']),{'proof':'PROVAS-ACESSO-PRIVADO-QA.json','checks':16,'original_private_resource_count':len(state['private_resource_ids'])})
|
|
check('Ação contextual útil sem relação técnica',all(any(a['href']=='/simulador-fiscal' for a in r['context_actions']) for r in laws),{'action':'Abrir simulador fiscal'})
|
|
except Exception as e:
|
|
checks.append({'criterion':'Execução focada','result':'falhou','evidence':str(e)})
|
|
(out/'PROVAS-HTTP-QA.json').write_text(json.dumps({'scope':'apenas apresentação documental e consumidores afetados','target':f['database']+':55441','checks':checks,'events':events,'active_changes':0,'accepted_journeys_repeated':False},ensure_ascii=False,indent=2),'utf-8');print(json.dumps({'checks':len(checks),'failed':[c for c in checks if c['result']=='falhou']},ensure_ascii=True))
|