60 lines
10 KiB
Python
60 lines
10 KiB
Python
from pathlib import Path
|
|
import json,hashlib,csv,io,zipfile,difflib,datetime
|
|
root=Path(__file__).resolve().parents[2];out=Path(__file__).resolve().parent;qa=Path('C:/Users/macbook/.config/investmoz/promotor-contexto-QA-20261015/source')
|
|
sha=lambda b:hashlib.sha256(b).hexdigest();encode=lambda v:(json.dumps(v,ensure_ascii=False,indent=2)+'\n').encode('utf-8')
|
|
assert not (out/'RECIBO-INTEGRIDADE.json').exists()
|
|
# Include the new authorization error view in the existing fingerprint catalogue.
|
|
path=qa/'app/Services/PortalProfileAccess.php';s=path.read_text('utf-8');needle="resource_path('views/app.blade.php'),";assert s.count(needle)==1;s=s.replace(needle,needle+" resource_path('views/profiles/creation-unavailable.blade.php'),");path.write_text(s,'utf-8')
|
|
baseline=json.loads((out/'ATIVO-ANTES.json').read_text('utf-8'))
|
|
for n,h in {**baseline['files'],**baseline['protected']}.items():assert (root/n).is_file() and sha((root/n).read_bytes())==h,n
|
|
paths=json.loads((out/'DELTA-QA.json').read_text('utf-8'))['paths'];sources=[];payload={};patch=[]
|
|
for n in paths:
|
|
before=(root/n).read_bytes() if (root/n).is_file() else None;after=(qa/n).read_bytes();assert before!=after
|
|
sources.append({'path':n,'previous_sha256':sha(before) if before is not None else None,'candidate_sha256':sha(after),'operation':'replace' if before is not None else 'new'})
|
|
payload['fontes/'+n]=after
|
|
if before is not None:payload['reversao-anterior/'+n]=before
|
|
patch+=list(difflib.unified_diff((before or b'').decode('utf-8').splitlines(True),after.decode('utf-8').splitlines(True),fromfile='DOC01/'+n,tofile='QA/'+n))
|
|
candidate='promotor-contexto-QA-'+sha(encode(sources))[:12]
|
|
(out/'DELTA-FONTES.patch').write_bytes(''.join(patch).encode('utf-8'))
|
|
interface={'target':'http://127.0.0.1:18520','session':'synthetic QA dual Promotor/Superutilizador, existing restored assignments','login':'normal Fortify and MFA observed','route':'/minhas-oportunidades/create','visible':'Nova oportunidade; Promotor real e categoria autorizada; canonical fields; four dimensions','screenshot':'QA-EDITOR-ABERTO.jpg','filled_or_saved':False,'active_opening_observed':False,'active_changed':False}
|
|
(out/'INTERFACE-QA.json').write_bytes(encode(interface))
|
|
# Prove the exceptional approval service and the MFA/elevation branch unchanged.
|
|
before=(root/'app/Services/PortalProfileAccess.php').read_text('utf-8');after=(qa/'app/Services/PortalProfileAccess.php').read_text('utf-8')
|
|
tail=lambda text:text[text.index(' if (! $this->mfa($actor))'):text.index(' public function canCreate')]
|
|
assert tail(before)==tail(after)
|
|
for n in ['app/Services/PortalSuperusers.php','app/Services/PortalProfileAdministration.php','app/Http/Middleware/PortalProfileSession.php','app/Services/OpportunityClassification.php','app/Services/OpportunityProfileWorkflow.php']:
|
|
assert (root/n).read_bytes()==(qa/n).read_bytes(),n
|
|
verification={'protected_active_files':len(baseline['files']),'protected_active_files_unchanged':True,'active_configuration_unchanged':True,'exceptional_elevation_and_MFA_branch_sha256':sha(tail(after).encode('utf-8')),'exceptional_service_and_independence_unchanged':True,'build_changed':False,'migrations':0,'role_or_pair_changes':0,'HTTP_business_saves':0,'accepted_tests_repeated':False}
|
|
(out/'PRESERVACAO-ATIVO-E-EXCECIONAL.json').write_bytes(encode(verification))
|
|
# Append evidence to two existing requirements only, without changing acceptance/state.
|
|
matrix=root/'docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv';prior=matrix.read_bytes();text=prior.decode('utf-8');lines=text.splitlines(keepends=True);reader=csv.reader(io.StringIO(text,newline=''));csv.field_size_limit(10000000);parts=[];cols=None;start=0;old=[]
|
|
for vals in reader:
|
|
end=reader.line_num;raw=''.join(lines[start:end]);start=end
|
|
if cols is None:cols=vals.copy();cols[0]=cols[0].lstrip('\ufeff');parts.append(raw);continue
|
|
if vals[0] not in ['AUD-PROFILE-10','AUD-PROFILE-14']:parts.append(raw);continue
|
|
row=dict(zip(cols,vals));old.append(row.copy())
|
|
row['Fundamento do estado atual']+=' | 15/10/2026 — revisão pontual do original v1 §3.2/§5 e orientação atual da Tempo: elevação excecional não é imposta à atuação normal de Promotor só por acumular Superutilizador. A primazia indiscriminada anterior era interpretação de implementação. Corrigida apenas em QA; atuação excecional e independência preservadas.'
|
|
row['Evidências atuais verificadas']+=' | outputs/investmoz-promotor-contexto-QA-20261015/RELATORIO-E-DECISAO.md; FONTE-V1-E-CONDICAO.json; HTTP-BEFORE.json (8); HTTP-AFTER.json (15); SCOPES-QA.json (23); INTERFACE-QA.json; PRESERVACAO-ATIVO-E-EXCECIONAL.json'
|
|
row['Critérios restantes atuais']+=' | Complemento pontual '+candidate+': três fontes QA verificadas; disponibilização no ativo exige decisão específica. Abertura do editor observada em QA, não no ativo; sem repetir a aceitação DOC01 ou conceder grants.'
|
|
tmp=io.StringIO(newline='');csv.writer(tmp,lineterminator='\n').writerow([row[c]for c in cols]);parts.append(tmp.getvalue())
|
|
assert len(old)==2;matrix.write_bytes(''.join(parts).encode('utf-8'))
|
|
(out/'MATRIZ-ANTES.json').write_bytes(encode(old));(out/'ATUALIZACAO-MESMA-MATRIZ.json').write_bytes(encode({'before_sha256':sha(prior),'after_sha256':sha(matrix.read_bytes()),'changed_ids':['AUD-PROFILE-10','AUD-PROFILE-14'],'other_raw_rows_preserved':3400,'acceptance_or_historical_state_changed':False,'global_audit_reopened':False}))
|
|
note='\n\n## 15/10/2026 — acesso normal de Promotor com Superutilizador acumulado\n\nA leitura direta da v1 §3.2/§5 distingue a atuação de Promotor da elevação excecional de Superutilizador. O diagnóstico anterior de falta de elevação explicava o 403 instalado, mas generalizava a exigência à acumulação sem disposição expressa. Corrigido apenas em QA no complemento `'+candidate+'`: canCreate, leitura/edição e fila próprias usam o grant de Promotor; funções excecionais, Auditor, organização/tipo, estados, MFA e independência conservam os controlos. Três fontes, duas substituições e uma vista nova de recusa explicada; sem build ou migrations. Não foram concedidos grants ou alteradas credenciais ativas.\n\nOito verificações HTTP antes e quinze depois, 23 verificações de âmbito e abertura visual com Fortify/MFA normais, sem preencher, guardar ou transitar o formulário. Ativo DOC01 preservado por hash; B/COUNTRY02 e aceitação anterior mantidos. Dois requisitos recebem complemento pontual, com 3.400 outros registos brutos preservados. Proposta, delta, provas e reversão: outputs/investmoz-promotor-contexto-QA-20261015/. Falta somente decisão específica para aplicar as três fontes no ativo e observar a abertura, sem reinstalar DOC01.\n'
|
|
with (root/'docs/investmoz/v2/auditoria-portal/backlog.md').open('a',encoding='utf-8',newline='')as f:f.write(note)
|
|
recon=root/'docs/investmoz/v2/auditoria-portal/perfis-v1-reconciliacao.md';original=recon.read_bytes();(out/'RECONCILIACAO-ANTES.sha256').write_text(sha(original)+'\n','ascii')
|
|
prefix='## 15/10/2026 — interpretação atual do contexto de Promotor\n\nO original v1 §3.2/§5 distingue a atuação normal do Promotor da elevação excecional do Superutilizador. A orientação atual da Tempo exige preservar essa distinção quando a mesma conta acumula papéis. As afirmações históricas abaixo de que toda a atuação da conta acumulada exige elevação registam a interpretação de implementação então adotada; não constituem por si uma disposição expressa da Tempo para agravar a atuação normal de Promotor.\n\nComplemento `'+candidate+'` preparado e verificado apenas em QA, sem grants, credenciais ativas, build, migrations ou nova auditoria global. Abertura visual passou; ativo DOC01 e os controlos excecionais permanecem inalterados. Fonte, condição de código, provas e decisão concreta em outputs/investmoz-promotor-contexto-QA-20261015/RELATORIO-E-DECISAO.md. Disponibilização desta correção depende de autorização específica. O conteúdo anterior fica preservado abaixo como histórico.\n\n'
|
|
recon.write_bytes(prefix.encode('utf-8')+original)
|
|
for n in ['RELATORIO-E-DECISAO.md','FONTE-V1-E-CONDICAO.json','QA-ISOLAMENTO.json','HTTP-BEFORE.json','HTTP-AFTER.json','SCOPES-QA.json','INTERFACE-QA.json','PRESERVACAO-ATIVO-E-EXCECIONAL.json','ATUALIZACAO-MESMA-MATRIZ.json','DELTA-FONTES.patch','QA-RECUSA-VISIVEL.html','QA-EDITOR-ABERTO.jpg']:
|
|
payload['documentos-e-provas/'+n]=(out/n).read_bytes()
|
|
manifest={'candidate':candidate,'prepared_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'scope':'QA only; active installation requires a specific Tempo decision','sources':sources,'source_count':3,'replacements':2,'new_sources':1,'build_changes':0,'migrations':0,'new_roles_or_privilege_grants':0,'reversal':'Restore two PHP files from current DOC01 and remove new view by exact hash after references restored; clear affected compiled views only; no database or canonical rollback','payload':[{'path':n,'sha256':sha(b),'bytes':len(b)}for n,b in sorted(payload.items())]}
|
|
manifest_bytes=encode(manifest);(out/'MANIFESTO-DELTA.json').write_bytes(manifest_bytes)
|
|
zip_path=root/'outputs'/(candidate+'.zip');assert not zip_path.exists()
|
|
with zipfile.ZipFile(zip_path,'w',zipfile.ZIP_DEFLATED,compresslevel=9)as z:
|
|
for n,b in sorted(payload.items()):z.writestr(n,b)
|
|
z.writestr('MANIFESTO-DELTA.json',manifest_bytes)
|
|
with zipfile.ZipFile(zip_path)as z:
|
|
assert z.testzip()is None
|
|
for n,b in payload.items():assert z.read(n)==b
|
|
receipt={'candidate':candidate,'status':'QA demonstrated; active unchanged; specific activation decision pending','sources':3,'build_changes':0,'role_or_pair_changes':0,'HTTP_before':8,'HTTP_after':15,'scope_checks':23,'browser_opening':'passed in QA only; no values filled or saved','source_original_v1_sha256':'f9e0f6280566fed8b52d0b36bb814a82e11976fec9ea9f62d64611ff8c824b38','active_protected_files_unchanged':len(baseline['files']),'DOC01_reinstalled':False,'accepted_QA_repeated':False,'manifest_sha256':sha(manifest_bytes),'report_sha256':sha((out/'RELATORIO-E-DECISAO.md').read_bytes()),'screenshot_sha256':sha((out/'QA-EDITOR-ABERTO.jpg').read_bytes()),'zip':{'name':zip_path.name,'bytes':zip_path.stat().st_size,'sha256':sha(zip_path.read_bytes()),'entries':len(payload)+1,'all_entry_hashes_verified':True}}
|
|
(out/'RECIBO-INTEGRIDADE.json').write_bytes(encode(receipt));print(json.dumps(receipt,ensure_ascii=True))
|