the-custodian/docs/changes/netkingdom-target-2026-10-16/access-native-source/b2-b3/r3/actual-retained-python-source-smoke.py
codex e19bcd1f3d
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 2s
Reject generated-only commits / generated-commit-guard (push) Successful in 13s
docs: preserve reviewed NetKingdom session artifacts
2026-11-01 22:42:33 +01:00

101 lines
12 KiB
Python

"""Disposable synthetic proof: actual Approval App HTTPS -> actual Access serve.
No native config, credential environment, approval or backend effect is used.
"""
import base64, hashlib, http.server, io, json, os, pathlib, socket, ssl, subprocess, sys, tempfile, threading, time
from datetime import datetime, timedelta, timezone
from wsgiref.simple_server import make_server, WSGIRequestHandler
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
sys.path.insert(0, '/home/worsch/approval-engine')
sys.path.insert(0, '/home/worsch/secrets-engine/src')
from approval_engine.api import App
from approval_engine.auth import Identity, StaticTokenAuthenticator
from approval_engine.store import Engine
from secrets_engine.authorization import request_digest, approval_binding_digest
from urllib.request import Request, urlopen
from urllib.error import HTTPError
OUT=pathlib.Path(sys.argv[1]);OUT.mkdir(exist_ok=True)
if any(OUT.iterdir()):raise RuntimeError('use a fresh empty proof output directory')
def digest(raw):return 'sha256:'+hashlib.sha256(raw).hexdigest()
def write(path,raw,mode=0o600):path.write_bytes(raw);path.chmod(mode)
def identity(subject,kind,scopes):return Identity(subject=subject,issuer='synthetic-test-only',audiences=('approval-engine',),principal_type=kind,tenant='tenant:platform',roles=frozenset(),scopes=frozenset(scopes),assurance={'level':'synthetic'},evidence_ref='synthetic-test-only',tenant_source='directory')
class Quiet(WSGIRequestHandler):
def log_message(self,*args):pass
class Review(http.server.BaseHTTPRequestHandler):
def do_POST(self):
raw=self.rfile.read(int(self.headers['Content-Length']));body=json.loads(raw)
assert self.path=='/apis/authentication.k8s.io/v1/tokenreviews'
assert self.headers['Authorization']=='Bearer synthetic-reviewer'
assert body['spec']['audiences']==['flex-auth','access-engine']
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'status':{'authenticated':True,'audiences':['flex-auth'],'user':{'username':'system:serviceaccount:secrets-engine:secrets-engine'}}}).encode())
def log_message(self,*args):pass
with tempfile.TemporaryDirectory(prefix='access-actual-python-source-') as folder:
root=pathlib.Path(folder);now=datetime.now(timezone.utc)
key=rsa.generate_private_key(public_exponent=65537,key_size=2048);name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'localhost')]);cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=1)).not_valid_after(now+timedelta(hours=1)).add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),critical=False).sign(key,hashes.SHA256()))
ca=root/'ca.pem';private=root/'tls-key.pem';write(ca,cert.public_bytes(serialization.Encoding.PEM));write(private,key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
tls=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);tls.load_cert_chain(ca,private)
ctx=ssl.create_default_context(cafile=str(ca))
def start(server):server.socket=tls.wrap_socket(server.socket,server_side=True);threading.Thread(target=server.serve_forever,daemon=True).start();return 'https://localhost:'+str(server.server_port)
review=http.server.HTTPServer(('127.0.0.1',0),Review);review_origin=start(review)
engine=Engine(root/'approval.sqlite3',freshness_ttl=120)
auth=StaticTokenAuthenticator({'synthetic-creator':identity('secrets-engine','service',{'approval:create'}),'synthetic-human':identity('synthetic-human','human',{'approval:approve'}),'synthetic-reader':identity('synthetic-access-reader','service',{'approval:read'})})
app=App(engine,auth)
source=make_server('127.0.0.1',0,app,handler_class=Quiet);origin=start(source)
def source_call(method,path,body,token):
request=Request(origin+path,data=json.dumps(body).encode() if body is not None else None,method=method,headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'})
with urlopen(request,context=ctx,timeout=3) as response:return response.status,json.load(response)
# Reuse existing owner interoperability contract generator; it has synthetic metadata only.
generated=subprocess.check_output([sys.executable,'/tmp/access-trusted-b2-b3-r3/tools/service_task_execution_fixture.py'],env={'PATH':os.defpath})
request=json.loads(generated)['request'];request['subject']['tenant']='tenant:platform';request['resource']['tenant']='tenant:platform';request['context']['purpose']='actual Python App source-only synthetic proof';del request['context']['approval'];request['context']['execution_contract']['backend_budget']['ttl_seconds']=30;request['context']['execution_contract']['operation_deadline']=(now+timedelta(seconds=60)).replace(microsecond=0).isoformat()
seed=root/'seed';write(seed,base64.urlsafe_b64encode(bytes([19])*32).rstrip(b'='),0o440)
reviewer_token=root/'review-token';write(reviewer_token,b'synthetic-reviewer',0o440)
reader_token=root/'reader-token';write(reader_token,b'synthetic-reader',0o440)
registry=root/'registry.json';write(registry,pathlib.Path('/tmp/access-trusted-b2-b3-r3/examples/secrets-engine/registry_snapshot.json').read_bytes())
config=root/'source.json';write(config,json.dumps({'source_id':'synthetic-actual-approval-app','source_revision':'actual-owner-python-source-fixture','origin':origin,'store_tenant':'tenant:platform','ca_file':str(ca),'token_file':str(reader_token)}).encode())
listener=socket.socket();listener.bind(('127.0.0.1',0));port=listener.getsockname()[1];listener.close()
record=root/'record.jsonl';url=f'http://127.0.0.1:{port}'
command=['/tmp/netkingdom-access-trusted-r3','serve','--addr',f'127.0.0.1:{port}','--registry',str(registry),'--policy','/tmp/access-trusted-b2-b3-r3/examples/secrets-engine-service-task-execution-v2/policy_package.md','--log',str(record),'--caller-auth-mode','enforce','--caller-audience','flex-auth','--caller-kubernetes-url',review_origin,'--caller-reviewer-token-file',str(reviewer_token),'--caller-ca-file',str(ca),'--caller-binding','secrets-engine=system:serviceaccount:secrets-engine:secrets-engine','--envelope-signing-key-file',str(seed),'--envelope-signing-kid','synthetic-v2','--approval-source-file',str(config)]
child=subprocess.Popen(command,env={},stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
for _ in range(100):
try:
with urlopen(url+'/healthz',timeout=.2):break
except Exception:time.sleep(.02)
jwt='synthetic.'+base64.urlsafe_b64encode(json.dumps({'exp':int((now+timedelta(minutes=2)).timestamp())}).encode()).decode().rstrip('=')+'.synthetic'
def check(value):
req=Request(url+'/v1/check',data=json.dumps(value).encode(),headers={'Authorization':'Bearer '+jwt,'Content-Type':'application/json'})
try:
with urlopen(req,timeout=5) as response:return response.status,response.read()
except HTTPError as error:return error.code,error.read()
claimfree=json.loads(json.dumps(request))
pre_status,pre_raw=check(claimfree);assert pre_status==200,(pre_status,pre_raw)
pre_file=root/'preapproval.json';write(pre_file,pre_raw)
subprocess.run(['/tmp/netkingdom-access-owner-proof-verifier',str(pre_file),'/home/worsch/the-custodian/docs/changes/netkingdom-target-2026-10-16/access-native-source/b2-b3/r2/actual-python-source/synthetic-public-trust.json',str(pre_file)],env={},check=True,stdout=subprocess.DEVNULL)
pre=json.loads(pre_raw);assert pre['effect']=='deny' and 'lifetime' not in pre and pre['signature']['mode']=='signed'
assert pre['binding']['submitted_request_digest']==request_digest(claimfree)
assert pre['binding']['request_digest']==pre['binding']['approval_binding_digest']!=request_digest(claimfree)
assert pre['binding']['context']==claimfree['context'] and pre['diagnostics']['registry_subject'] is True
assert pre['provenance']['policy_package']=='secrets-engine.task-execution.service-pilot' and pre['provenance']['policy_version']=='v2'
assert pre['provenance']['policy_package_digest']=='sha256:de5683e5a34161b9349b10cd8e4abef704e0136e3b14b97719fcd7a79850fc4d'
native={'action':pre['binding']['action'],'actor':pre['binding']['subject']['id'],'principal':pre['binding']['subject'].get('attributes',{}).get('principal') or pre['binding']['subject']['id'],'purpose':pre['binding']['context']['purpose'],'target':pre['binding']['resource']}
aid='aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
status,created=source_call('POST','/v1/approvals',{'id':aid,'binding':native,'validity':{'not_before':(now-timedelta(minutes=1)).isoformat(),'expires_at':(now+timedelta(minutes=3)).isoformat()},'required_count':1,'pdp_digest':pre['binding']['approval_binding_digest'],'pdp_path':True,'human_control':True},'synthetic-creator');assert status==201
status,_=source_call('POST',f'/v1/approvals/{aid}/entries',{},'synthetic-human');assert status==200
status,claim=source_call('GET',f'/v1/approvals/{aid}/claim',None,'synthetic-reader');assert status==200 and claim['valid_now'] is True and claim['binding']['human_control'] is True
request['context']['approval']=claim
status,raw=check(request);assert status==200,(status,raw)
response=json.loads(raw);assert response['effect']=='allow' and response['signature']['mode']=='signed'
assert response['lifetime']['expires_at']==request['context']['execution_contract']['operation_deadline'].replace('+00:00','Z');assert response['binding']['context']==request['context'];assert response['binding']['submitted_request_digest']==request_digest(request);assert response['binding']['approval_binding_digest']==pre['binding']['approval_binding_digest']
assert response['provenance']['approval_observation']['source_id']=='synthetic-actual-approval-app'
saved=record.read_bytes();records=[json.loads(line) for line in saved.splitlines()];assert len(records)==2 and records[0]==pre and records[1]==response
# Actual producer state transition is fetched anew and cannot be rescued by carried claim.
engine.revoke(aid)
refused,_=check(request);assert refused!=200 and record.read_bytes()==saved
for name,value in [('request.json',request),('response.json',response),('source-record.json',records[1]),('preapproval-receipt.json',pre),('preapproval-source-record.json',records[0]),('claimfree-request.json',claimfree),('original-approval-claim.json',claim)]:write(OUT/name,(json.dumps(value,indent=2)+'\n').encode(),0o644)
receipt={'scope':'disposable synthetic only','actual_source':'Approval App over TLS with authenticated create, configured synthetic human entry, read; actual SQLite engine','actual_access':'production serve binary from B2/B3 R3 retained-registry preapproval successor','allow':True,'backend_ttl_seconds':30,'operation_authority_seconds':60,'explicit_approval_freshness_seconds':120,'decision_expiry_equals_exact_operation_deadline':True,'original_context_unchanged':True,'published_digest_match':True,'returned_source_record_match':True,'actual_source_revoke_refused':True,'no_record_after_refusal':True,'native_admission':False,'retained_registry_sha256':digest(registry.read_bytes()),'signed_deny_supplies_facts_not_execution':True,'approval_issued_from_authenticated_normalized_binding':True,'submitted_proposal_unchanged_except_original_issued_claim':True,'files_sha256':{p.name:digest(p.read_bytes()) for p in OUT.iterdir() if p.suffix=='.json' and p.name!='receipt.json'}}
write(OUT/'receipt.json',(json.dumps(receipt,indent=2)+'\n').encode(),0o644);print(json.dumps(receipt,indent=2))
finally:
child.terminate();child.wait(timeout=5);source.shutdown();review.shutdown();engine.close()