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

140 lines
11 KiB
Python

"""Deploy only the owner-authorized immutable opening. No SQL/service changes."""
from pathlib import Path
import ctypes, hashlib, json, os, re, subprocess, sys, zipfile
from datetime import datetime, timezone
ROOT=Path(__file__).resolve().parents[2]
PREP=ROOT/'outputs/investmoz-staff-preparation-20261012'
OUT=ROOT/'outputs/investmoz-workflow-opening-20261012'
PRIVATE=ROOT/'storage/app/private/investmoz-v2/portal-audit'
PHP='C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe'
DELIVERY='2e2f16c83483'
ZIP_HASH='13ddf150f0f7ab03de83437064bf32f34a382727880e9c7470faf87a9d035819'
MANIFEST_HASH='1da64a6def3d1ffe814e0fea8ac7b0f654320715032bfe7d89dabf750988cd64'
MODE=sys.argv[1]
assert MODE in ['stage','enable','contain']
def read(p): return json.loads(Path(p).read_text(encoding='utf-8-sig'))
def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def save(p,v): Path(p).write_text(json.dumps(v,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
def now(): return datetime.now(timezone.utc)
folder=PREP/('abertura-workflow-'+DELIVERY)
archive=folder/('investmoz-abertura-'+DELIVERY+'.zip')
assert sha(archive)==ZIP_HASH and sha(folder/'manifesto-final.json')==MANIFEST_HASH
manifest=read(folder/'manifesto-final.json')
flags=list(manifest['flags'])
assert len(flags)==3 and all(manifest['flags'].values())
assert manifest['schema_changes']==manifest['service_changes']==0 and manifest['migrations']==[]
assert not (ROOT/'bootstrap/cache/config.php').exists() and not list((ROOT/'bootstrap/cache').glob('routes-*.php')), 'Unexpected configuration or route cache'
OUT.mkdir(exist_ok=True)
receipt_file=PRIVATE/'workflow-opening-2e2f16c83483-execution.json'
def inspect(name):
r=subprocess.run([PHP,str(PREP/'deployment-state-readonly.php')],cwd=ROOT,capture_output=True,text=True,encoding='utf-8',timeout=30)
assert r.returncode==0, 'Read-only inspection failed; details withheld'
result=json.loads(r.stdout); save(OUT/name,result)
assert result['target']=='investemoz:5432' and result['app_url']=='https://portal-investidor.test'
assert result['flags']['organization_country_enabled'] and result['flags']['profile_administration_enabled']
assert not result['flags']['notifications_enabled'] and not result['flags']['opportunity_modular_profiles_qa_enabled']
assert result['scanner']['available'] and result['queue']==[]
assert len(result['staff'])==3 and all(x['email_verified'] and x['mfa_confirmed'] for x in result['staff'])
return result
def replace(target,data):
target=Path(target); assert target.resolve().is_relative_to(ROOT.resolve())
target.parent.mkdir(parents=True,exist_ok=True)
temp=target.with_name(target.name+'.opening-2e2f16c83483-new'); assert not temp.exists()
if target==ROOT/'.env':
# Retain the existing secured file/DACL. Windows refuses ReplaceFile on
# this live configuration file; one exclusive FileStream writes the
# reviewed bytes without exposing keys or widening access.
temp.write_bytes(data)
command="""$ErrorActionPreference='Stop'; $taskEnv='C:\\laragon\\www\\portal-investidor\\.env'; $taskTemp=$taskEnv+'.opening-2e2f16c83483-new'; Set-Acl -LiteralPath $taskTemp -AclObject (Get-Acl -LiteralPath $taskEnv); $taskBytes=[IO.File]::ReadAllBytes($taskTemp); $taskStream=[IO.File]::Open($taskEnv,[IO.FileMode]::Open,[IO.FileAccess]::Write,[IO.FileShare]::None); try { $taskStream.Write($taskBytes,0,$taskBytes.Length); $taskStream.SetLength($taskBytes.Length); $taskStream.Flush($true) } finally { $taskStream.Dispose() }; Remove-Item -LiteralPath $taskTemp"""
completed=subprocess.run(['powershell.exe','-NoProfile','-Command',command],capture_output=True)
assert completed.returncode==0, 'Configuration write failed; diagnostic details withheld'
assert target.read_bytes()==data
return
temp.write_bytes(data)
if target.exists():
# Windows ReplaceFile merges/preserves the replaced file's DACL and metadata.
api=ctypes.WinDLL('kernel32',use_last_error=True).ReplaceFileW
api.argtypes=[ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_uint32,ctypes.c_void_p,ctypes.c_void_p]
api.restype=ctypes.c_int
if not api(str(target),str(temp),None,0,None,None): raise ctypes.WinError(ctypes.get_last_error())
else: os.replace(temp,target)
def record(): save(receipt_file,receipt); save(OUT/'manifesto-execucao.json',receipt)
if MODE=='stage':
assert not receipt_file.exists(), 'Already staged: inspect receipt instead of repeating'
before=inspect('destino-antes.json')
assert all(not before['flags'][key] for key in ['profile_access_enabled','opportunity_dashboard_access_enabled','opportunity_specialized_drafts_enabled'])
backup=read(PRIVATE/'internal-designation-target-backup.json')
assert backup['result']=='passed' and backup['restore_verified'] and backup['files_verified']
assert backup['target']['database']=='investemoz' and int(backup['target']['port'])==5432
assert backup['restored_target']['port']==55441 and backup['restored_target']['database'].endswith('_test')
assert now()<datetime.fromisoformat(backup['valid_until']) and len(backup['tables'])==295
assert sha(backup['dump_path'])==backup['dump_sha256'] and sha(backup['files_path'])==backup['files_sha256']
assert backup['verified_at']==manifest['backup']['verified_at'] and backup['dump_sha256']==manifest['backup']['dump_sha256'] and backup['files_sha256']==manifest['backup']['files_sha256']
for item in manifest['source_files']:
p=ROOT/item['path']; assert (sha(p) if p.is_file() else None)==item['before_sha256'], 'Baseline divergence: '+item['path']
if p.is_file(): assert backup['active_files_manifest']['active-code/'+item['path']]==item['before_sha256']
assert sha(ROOT/'public/build/manifest.json')==backup['active_manifest_sha256']
for name in flags:
matches=re.findall(rb'(?m)^'+name.encode()+rb'=([^\r\n]*)\r?$',(ROOT/'.env').read_bytes())
assert matches in [[],[b'false']], 'Unexpected explicit flag value'
recovery=PRIVATE/('workflow-opening-recovery-'+now().strftime('%Y%m%d_%H%M%S')); recovery.mkdir()
with zipfile.ZipFile(recovery/'before.zip','w',compression=zipfile.ZIP_STORED) as stream:
old=[ROOT/item['path'] for item in manifest['source_files'] if item['before_sha256'] is not None]
old+=list((ROOT/'public/build').rglob('*')); old+=[ROOT/'.env']
snapshots={}
for p in old:
if p.is_file():
member=p.relative_to(ROOT).as_posix(); snapshots[member]=sha(p); stream.write(p,member)
with zipfile.ZipFile(recovery/'before.zip') as stream:
for name,digest in snapshots.items(): assert hashlib.sha256(stream.read(name)).hexdigest()==digest
save(recovery/'inventory.json',snapshots)
receipt={'at':now().isoformat(),'authorization':{'source':'Explicit owner instruction in conversation: pode fazer a entrega','scope':'Delivery 2e2f16c83483 and exactly three opening flags','human_portal_actor_impersonated':False},'delivery':DELIVERY,'code':manifest['code_revision_short'],'package_sha256':ZIP_HASH,'manifest_sha256':MANIFEST_HASH,'state':'verified_before_staging','recovery_directory':str(recovery),'backup_verified_at':backup['verified_at'],'backup_restore_target':backup['restored_target'],'changed_files':[],'original_env_sha256':sha(ROOT/'.env'),'schema_writes':0,'business_data_writes':0,'service_changes':0,'COUNTRY02_preserved':True,'operational_flags_enabled':False,'full_restore_requires_separate_decision':True}
record()
with zipfile.ZipFile(archive) as stream:
items=manifest['source_files']+manifest['compiled_resources']
payload={x['path']:stream.read('payload/'+x['path']) for x in items}
for x in items: assert hashlib.sha256(payload[x['path']]).hexdigest()==x.get('after_sha256',x.get('sha256'))
order=[p for p in payload if p.startswith('public/build/') and p!='public/build/manifest.json']
order += [p for p in payload if not p.startswith('public/build/')]
order += ['public/build/manifest.json']
for relative in order:
p=ROOT/relative
if p.is_file() and sha(p)==hashlib.sha256(payload[relative]).hexdigest(): continue
replace(p,payload[relative]); receipt['changed_files'].append(relative); record()
for x in items: assert sha(ROOT/x['path'])==x.get('after_sha256',x.get('sha256'))
assert sha(ROOT/'.env')==receipt['original_env_sha256']
after=inspect('destino-codigo-gates-off.json')
assert before['protected_tables']==after['protected_tables'], 'Active data changed during staging; inspect before enabling'
assert before['flags']==after['flags']
receipt.update(state='staged_verified_gates_off',all_168_payload_hashes_verified=True,active_data_unchanged=True,source_files=9,compiled_resources=159)
record()
else:
receipt=read(receipt_file)
assert receipt['delivery']==DELIVERY
if MODE=='enable':
assert receipt['state']=='staged_verified_gates_off'
before=inspect('destino-pre-abertura.json')
assert before['protected_tables']==read(OUT/'destino-antes.json')['protected_tables'], 'Data divergence before opening'
for x in manifest['source_files']+manifest['compiled_resources']: assert sha(ROOT/x['path'])==x.get('after_sha256',x.get('sha256'))
assert sha(ROOT/'.env')==receipt['original_env_sha256']
env=ROOT/'.env'; original=env.read_bytes(); updated=original
for name in flags:
pattern=rb'(?m)^'+name.encode()+rb'=(true|false)(\r?)$'
matches=re.findall(pattern,updated)
assert len(matches)<=1
if matches:
updated=re.sub(pattern,lambda m:name.encode()+b'='+ (b'true' if MODE=='enable' else b'false')+m[2],updated)
else:
assert MODE=='enable', 'Containment flag missing'
updated+=(b'' if updated.endswith(b'\n') else b'\r\n')+name.encode()+b'=true\r\n'
replace(env,updated)
after=inspect('destino-aberto.json' if MODE=='enable' else 'destino-contencao.json')
expected=read(OUT/'destino-antes.json')['flags'].copy()
for key in ['profile_access_enabled','opportunity_dashboard_access_enabled','opportunity_specialized_drafts_enabled']: expected[key]=MODE=='enable'
assert after['flags']==expected, 'Unexpected feature change'
assert after['protected_tables']==read(OUT/'destino-antes.json')['protected_tables']
receipt.update(state='enabled_verified' if MODE=='enable' else 'contained',operational_flags_enabled=MODE=='enable',flag_keys_changed=flags,only_three_environment_values_changed=True,at=now().isoformat())
record()
print(json.dumps({k:receipt[k] for k in ['delivery','code','state','COUNTRY02_preserved','operational_flags_enabled','schema_writes','business_data_writes','service_changes']}))