railiance-platform/scripts/t03-attended-delivery.py
codex 68a059c730
All checks were successful
CI Smoke / host-smoke (push) Successful in 1s
CI Smoke / container-smoke (push) Successful in 2s
Prepare contained native execution of the three approved T03 actions
Assistant: codex
Assistant-Model: gpt-6-astra
Assistant-Session: 01a09cbb-87c6-7900-a145-4ce53ba9f1a6
2026-09-14 03:21:49 +02:00

49 lines
3.7 KiB
Python

"""Scoped reader -> contained attended administration; never exports credentials."""
import importlib.util,json,os,signal,stat,subprocess,tempfile
from pathlib import Path
from datetime import datetime,timezone
from urllib.request import Request,build_opener,ProxyHandler,HTTPRedirectHandler
ROOT=Path('/home/worsch/railiance-platform')
spec=importlib.util.spec_from_file_location('preflight',ROOT/'scripts/approval-client-reader-preflight.py');pre=importlib.util.module_from_spec(spec);spec.loader.exec_module(pre)
RECEIPT=ROOT/'docs/evidence/2026-09-14-t03-attended-delivery.json'
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self,*args,**kwargs):return None
def require(value,code):
if not value:raise ValueError(code)
def private(path,directory=False):
st=path.lstat();require(st.st_uid==os.getuid() and stat.S_IMODE(st.st_mode)==(0o700 if directory else 0o600) and (stat.S_ISDIR(st.st_mode) if directory else stat.S_ISREG(st.st_mode)),'private_path_required')
def main(receipt):
require(Path.home().parent.name=='.warden-attended-login' and not os.getenv('BAO_TOKEN') and not os.getenv('VAULT_TOKEN'),'attended_reader_required')
require(not Path('/home/worsch/secrets-engine/docs/evidence/2026-09-14-t03-native-execution.json').exists(),'execution_receipt_requires_reconciliation')
identity=pre.bao('token','lookup','-format=json')['data'];pre.validate_identity(identity)
for path,expected in pre.EXPECTED.items():require(sorted(pre.bao('token','capabilities','-format=json',path))==expected,'reader_scope_failed')
runtime=Path('/run/user')/str(os.getuid());private(runtime,True)
fs=subprocess.run(['findmnt','-n','-o','FSTYPE','-T',str(runtime)],capture_output=True,text=True,timeout=10)
require(fs.returncode==0 and fs.stdout.strip()=='tmpfs','private_tmpfs_required')
helper=Path.home()/'.vault-token';private(helper)
with tempfile.TemporaryDirectory(prefix='t03-native-',dir=runtime) as name:
directory=Path(name);private(directory,True)
req=Request('https://bao.coulomb.social/v1/platform/data/workloads/secrets-engine/approval-client?version=1',headers={'X-Vault-Token':helper.read_text().strip()})
with build_opener(ProxyHandler({}),NoRedirect()).open(req,timeout=20) as response:
data=response.read(65537);require(len(data)<=65536,'response_bound_exceeded')
data=json.loads(data);require(data['data']['metadata']['version']==1,'custody_version_mismatch')
value=data['data']['data']['CLIENT_SECRET'];require(isinstance(value,str) and 0<len(value)<=16384,'credential_invalid')
fd=os.open(directory/'client-secret',os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'w') as stream:stream.write(value)
del value,data,req
receipt.update(phase='scoped_reader_delivered',reader_effective_policy_verified=True,existing_kv_version=1)
RECEIPT.write_text(json.dumps(receipt,indent=2)+'\n')
p=subprocess.run(['python3',str(ROOT/'scripts/openbao-attended-exec.py'),'--','python3','-B',str(ROOT/'scripts/t03-native-execution.py'),'admin','--directory',str(directory),'--negative-token-file',str(helper)],capture_output=True,timeout=780)
# Warden's output remains inside this envelope, never forwarded or stored.
require(p.returncode==0,'attended_admin_failed')
receipt.update(status='passed',phase='native_actions_completed',admin_warden_exited_0=True)
receipt['private_runtime_removed']=True
if __name__=='__main__':
receipt={'observed_at':datetime.now(timezone.utc).isoformat(),'status':'failed','phase':'preflight','credential_values_emitted':False}
try:main(receipt)
except Exception as e:
if type(e) is ValueError and str(e).replace('_','').isalnum():receipt['failure_code']=str(e)
raise SystemExit(1) from None
finally:RECEIPT.write_text(json.dumps(receipt,indent=2)+'\n')