883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
268 lines
19 KiB
Python
268 lines
19 KiB
Python
"""Explicit realm-UI activation, original Login ordering, and default-off boundary.
|
|
|
|
Uses the actual dispatcher block, host/controller and original-memory publisher;
|
|
no native client, original handler reads, authentication, or installed assets.
|
|
"""
|
|
import ast
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest.mock import Mock, patch
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0,str(ROOT/'ops'))
|
|
import engine_wire_host as wire
|
|
import engine_login_input_binding as original
|
|
import engine_session_retirement as retirement
|
|
import native_engine_character_test as control
|
|
import native_manual_login as manual
|
|
import forever_launcher_backend as backend
|
|
|
|
BASE,BRIDGE,OWNER,VTABLE=0x2000,0x1000,0x8000,0x9000
|
|
EXPORTS=dict(gw_wire_frame_data=0x100,gw_wire_auth_data=0x600,
|
|
gw_wire_auth_credentials_data=0x1200,gw_wire_account_ui_data=0x1500,
|
|
gw_wire_account_ui_snapshot=0x10,gw_wire_account_ui_select=0x20,
|
|
gw_wire_account_ui_activate=0x30)
|
|
PIN=dict(path='runtime/ready.json',sha256='a'*64)
|
|
|
|
def frame(command=2,error=0):
|
|
return dict(command=command,error=error,api_result=0,completed=True,abi_echo=1)
|
|
|
|
def account():
|
|
return dict(state=0,server_proof_verified=0,transport_prepared=0,
|
|
memory_credentials=dict(state=0,generation=0,consumed_generation=0,
|
|
username_bytes=0,password_bytes=0),
|
|
source_ui=dict(available=True,enabled=False,request=0,state=0,error=0))
|
|
|
|
def binding(activation=None):
|
|
row=dict(pid=123,restored=False,wire_ping_only=True,owner=OWNER,
|
|
bound_vtable=VTABLE,wire_frame_callback=0xa000)
|
|
if activation is not None:row['realm_ui_activation']=activation
|
|
return row
|
|
|
|
class Memory:
|
|
def __init__(self,command=2):
|
|
self.bytes=bytearray(0x10000);self.writes=[];self.fd=42;self.closed=False
|
|
self.put(BRIDGE+0x20,struct.pack('<4I3Q',2,40,1,0,BASE,BASE+0x10,BASE+0x20))
|
|
self.put(OWNER,struct.pack('<Q',VTABLE));self.put(VTABLE+40,struct.pack('<Q',0xa000))
|
|
self.command(command)
|
|
self.put(BASE+EXPORTS['gw_wire_auth_data'],struct.pack('<II',1,1732)+bytes(1724))
|
|
self.put(BASE+EXPORTS['gw_wire_auth_credentials_data'],struct.pack('<8I',1,132,0,0,0,0,0,0)+bytes(100))
|
|
self.put(BASE+EXPORTS['gw_wire_account_ui_data'],struct.pack('<IIQ4i',1,32,0,0,0,0,0))
|
|
self.put(0xb000+0x20,struct.pack('<QQ',0xc000,7))
|
|
self.put(0xb000+0x48,struct.pack('<QQ',0xc100,8))
|
|
self.put(0xc000,b'fixture');self.put(0xc100,b'example1')
|
|
def put(self,address,value):self.bytes[address:address+len(value)]=value
|
|
def command(self,value,error=0):
|
|
self.put(BASE+EXPORTS['gw_wire_frame_data'],struct.pack('<IIi6IiIIQ',1,wire.SIZE,value,1,1,1,error,0,0,0,1,0,0))
|
|
def read(self,address,size):return bytes(self.bytes[address:address+size])
|
|
def write(self,address,value):self.put(address,value);self.writes.append((address,bytes(value)))
|
|
def u64(self,address):return struct.unpack('<Q',self.read(address,8))[0]
|
|
def allowed(self,address,size,permission):return True
|
|
def module(self):return BRIDGE,dict(exports={'gw_registration_realm_binding':0x20})
|
|
def close(self):self.closed=True
|
|
|
|
class ActivationBoundary(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
|
self.root=Path(self.tmp.name);(self.root/'runtime').mkdir()
|
|
self.path=self.root/'runtime/engine-poll-binding.json'
|
|
self.path.write_text(json.dumps(binding()))
|
|
def patches(self,memory):
|
|
return (patch.object(wire,'ROOT',self.root),
|
|
patch.object(wire.host,'Access',return_value=memory),
|
|
patch.object(wire.host,'require_safepoint'),
|
|
patch.object(wire,'module',return_value=(BASE,dict(exports=EXPORTS),{})),
|
|
patch.object(wire,'inspect_account',return_value=account()))
|
|
def activate(self,memory,readiness=PIN):
|
|
from contextlib import ExitStack
|
|
with ExitStack() as stack:
|
|
for context in self.patches(memory):stack.enter_context(context)
|
|
proof=stack.enter_context(patch.object(wire,'require_realm_ui_readiness',return_value=dict(readiness=readiness)))
|
|
wire.activate_realm_ui(123,{},readiness=readiness)
|
|
return proof
|
|
def test_explicit_activation_requires_complete_binding_and_idle_control(self):
|
|
memory=Memory();self.activate(memory)
|
|
self.assertEqual(memory.writes,[(BASE+EXPORTS['gw_wire_frame_data']+8,struct.pack('<i',11))])
|
|
self.assertEqual(json.loads(self.path.read_text())['realm_ui_activation']['readiness'],PIN)
|
|
for problem in ('ABI1','select','error','busy-account','missing-control'):
|
|
with self.subTest(problem=problem):
|
|
self.path.write_text(json.dumps(binding()));memory=Memory()
|
|
facts=account()
|
|
if problem=='ABI1':memory.put(BRIDGE+0x20,struct.pack('<I',1))
|
|
elif problem=='select':memory.put(BRIDGE+0x20+32,struct.pack('<Q',0))
|
|
elif problem=='error':memory.command(2,4)
|
|
elif problem=='busy-account':facts['state']=1
|
|
else:facts['source_ui']={'available':False}
|
|
from contextlib import ExitStack
|
|
with ExitStack() as stack:
|
|
for context in self.patches(memory):stack.enter_context(context)
|
|
stack.enter_context(patch.object(wire,'inspect_account',return_value=facts))
|
|
stack.enter_context(patch.object(wire,'require_realm_ui_readiness',return_value=dict(readiness=PIN)))
|
|
with self.assertRaises(ValueError):wire.activate_realm_ui(123,{},readiness=PIN)
|
|
self.assertEqual(memory.writes,[])
|
|
def test_both_account_publishers_require_acknowledgment_and_default_stays_off(self):
|
|
active=dict(readiness=PIN)
|
|
for command,proof,accept in ((2,None,True),(10,None,True),(11,active,False),
|
|
(-11,active,False),(2,active,False),(12,active,True),(12,None,False)):
|
|
with self.subTest(command=command,activation=bool(proof)):
|
|
memory=Memory(command)
|
|
if accept:self.assertEqual(wire.require_account_start_ready(memory,BASE,dict(exports=EXPORTS),binding(proof)),command)
|
|
else:
|
|
with self.assertRaises(ValueError):wire.require_account_start_ready(memory,BASE,dict(exports=EXPORTS),binding(proof))
|
|
self.assertEqual(memory.writes,[])
|
|
memory=Memory(12);memory.put(BASE+EXPORTS['gw_wire_account_ui_data']+24,struct.pack('<i',1))
|
|
with self.assertRaises(ValueError):wire.require_account_start_ready(memory,BASE,dict(exports=EXPORTS),binding(active))
|
|
memory=Memory(-11)
|
|
with patch.object(wire.host,'Access',return_value=memory),patch.object(wire,'module',return_value=(BASE,dict(exports=EXPORTS),{})):
|
|
self.assertEqual(wire.inspect(123)['command'],-11)
|
|
def test_original_input_cannot_publish_account3_before_activation_ack(self):
|
|
from contextlib import ExitStack
|
|
for command,accept in ((11,False),(-11,False),(12,True),(2,True)):
|
|
with self.subTest(command=command):
|
|
memory=Memory(command);self.path.write_text(json.dumps(binding(None if command==2 else dict(readiness=PIN))))
|
|
reads=[]
|
|
def preadv(fd,buffers,address):
|
|
reads.append(address);buffers[0][:]=memory.read(address,len(buffers[0]));return len(buffers[0])
|
|
def pwrite(fd,data,address):memory.write(address,data);return len(data)
|
|
with ExitStack() as stack:
|
|
for context in self.patches(memory):stack.enter_context(context)
|
|
stack.enter_context(patch.object(original,'ROOT',self.root))
|
|
stack.enter_context(patch.object(original.observed,'capture',return_value={'descriptor_contract_valid':True}))
|
|
stack.enter_context(patch.object(original,'isolated_modern_fallback'))
|
|
stack.enter_context(patch.object(retirement,'capture_generation',return_value=1))
|
|
stack.enter_context(patch.object(original.os,'preadv',side_effect=preadv))
|
|
stack.enter_context(patch.object(original.os,'pwrite',side_effect=pwrite))
|
|
context=dict(expected=None,version='/fixture/version',addons='/fixture/addons',
|
|
endpoint_kind=0,auth_port=3724,public_endpoint=False,profile='local')
|
|
if accept:
|
|
result=original.capture(123,SimpleNamespace(rsp=0xb000),context)
|
|
self.assertTrue(result['owned_mailbox_queued'])
|
|
self.assertEqual(reads,[0xc000,0xc100])
|
|
self.assertEqual(memory.writes[-1],(BASE+EXPORTS['gw_wire_frame_data']+8,struct.pack('<I',3)))
|
|
self.assertEqual(memory.writes[-2],(BASE+EXPORTS['gw_wire_auth_credentials_data']+8,struct.pack('<I',1)))
|
|
else:
|
|
with self.assertRaises(ValueError):original.capture(123,SimpleNamespace(rsp=0xb000),context)
|
|
self.assertEqual(reads,[]);self.assertEqual(memory.writes,[])
|
|
def test_existing_file_input_publisher_uses_the_same_ack_gate(self):
|
|
from contextlib import ExitStack
|
|
private=self.root/'secrets/fixture';private.mkdir(parents=True)
|
|
for name,value in [('account.json',json.dumps(dict(username='fixture'))),('password.txt','example1'),
|
|
('version-hash.bin','fixture'),('addon-tail.bin','fixture')]:
|
|
path=private/name;path.write_text(value);path.chmod(0o600)
|
|
(private.parent/'native-local-bootstrap.json').write_text(json.dumps(dict(account_directory=str(private))))
|
|
for command,accept in ((11,False),(12,True),(2,True)):
|
|
with self.subTest(command=command):
|
|
memory=Memory(command);self.path.write_text(json.dumps(binding(None if command==2 else dict(readiness=PIN))))
|
|
with ExitStack() as stack:
|
|
for context in self.patches(memory):stack.enter_context(context)
|
|
if accept:
|
|
wire.start_account(123,{})
|
|
self.assertEqual(memory.writes[-1],(BASE+EXPORTS['gw_wire_frame_data']+8,struct.pack('<I',3)))
|
|
else:
|
|
with self.assertRaises(ValueError):wire.start_account(123,{})
|
|
self.assertEqual(memory.writes,[])
|
|
def test_pinned_installed_pair_is_required_not_private_staging(self):
|
|
target=self.root/'runtime/native-client';target.mkdir();(target/'.build.info').write_bytes(b'fixture-build')
|
|
def save(name,value):
|
|
path=self.root/'runtime'/name;path.write_text(json.dumps(value))
|
|
return dict(path=str(path),sha256=hashlib.sha256(path.read_bytes()).hexdigest())
|
|
candidates={name:dict(sha256=str(i)*64) for i,name in enumerate(('realm-list','glue-parent'),1)}
|
|
stage=save('stage.json',[dict(consumer=name,candidate=row,source_pending_enabled=True,global_native_APIs_overridden=False) for name,row in candidates.items()])
|
|
check=save('check.json',dict(status='PASS_OFFLINE_ORIGINAL_CONSUMERS_SOURCE_FACTORY_AND_NATIVE_FALLBACK',candidates=candidates))
|
|
publication=save('publication.json',dict(applied=True,target=str(target),composed_root='root',published_build_info_sha256=hashlib.sha256(b'fixture-build').hexdigest()))
|
|
ready=dict(kind='original-Source-realm-UI-CASC-ready-v1',status='PASS_INSTALLED_SOURCE_REALM_UI_PAIR',installed=True,casc_ready=True,
|
|
target_root=str(target),composed_root='root',stage=stage,check=check,publication=publication,
|
|
consumers={name:dict(file_data_id=i,candidate_sha256=row['sha256']) for i,(name,row) in enumerate(candidates.items(),1)})
|
|
with patch.object(wire,'ROOT',self.root):
|
|
reference=save('ready.json',ready);self.assertFalse(wire.require_realm_ui_readiness(reference)['native_ui_acceptance_verified'])
|
|
for change in ('not-installed','not-CASC','missing-consumer','wrong-body','changed-publication','unpinned'):
|
|
altered=json.loads(json.dumps(ready))
|
|
if change=='not-installed':altered['installed']=False
|
|
elif change=='not-CASC':altered['casc_ready']=False
|
|
elif change=='missing-consumer':del altered['consumers']['glue-parent']
|
|
elif change=='wrong-body':altered['consumers']['realm-list']['candidate_sha256']='f'*64
|
|
elif change=='changed-publication':altered['composed_root']='other'
|
|
else:altered['check']['sha256']='0'*64
|
|
with self.subTest(change=change),self.assertRaises(ValueError):wire.require_realm_ui_readiness(save('altered.json',altered))
|
|
(target/'.build.info').write_bytes(b'changed')
|
|
with self.assertRaises(ValueError):wire.require_realm_ui_readiness(reference)
|
|
def test_controller_waits_for_ack_before_original_login_arm_and_propagates_pins(self):
|
|
self.path.write_text(json.dumps(binding()))
|
|
(self.root/'runtime/engine-listener-binding.json').write_text(json.dumps(dict(pid=123,restored=False)))
|
|
c=control.Controller(123);events=[];commands=iter((frame(2),frame(11),frame(-11),frame(12)))
|
|
def rpc(operation,**kwargs):
|
|
events.append(operation)
|
|
if operation=='inspect-wire-frame':return next(commands)
|
|
if operation=='inspect-wire-account':return account()
|
|
if operation=='inspect-engine-listener':return dict(stage=1,error=0)
|
|
raise AssertionError(operation)
|
|
c.rpc=rpc;c.action=lambda operation,**kwargs:events.append((operation,kwargs))
|
|
with patch.object(control,'ROOT',self.root):
|
|
self.assertEqual(c.prepare_original_login(source_realm_ui_readiness=PIN)['command'],12)
|
|
self.assertIn(('activate-source-realm-ui',dict(readiness=PIN)),events)
|
|
self.assertEqual(events.count('inspect-wire-frame'),4)
|
|
c=Mock();manual.prepare_background_manual_arm(c)
|
|
c.prepare_original_login.assert_called_once_with()
|
|
c=Mock();manual.prepare_background_manual_arm(c,7,PIN)
|
|
c.prepare_original_login.assert_called_once_with(retirement_generation=7,source_realm_ui_readiness=PIN)
|
|
c=control.Controller(123);c.action=Mock();c.rpc=Mock(return_value=frame(12,4))
|
|
with self.assertRaises(RuntimeError):c.activate_realm_ui(PIN)
|
|
def test_backend_opt_in_and_owner_rpc_pass_the_same_pinned_reference(self):
|
|
for opt_in in (False,True):
|
|
argv=['forever_launcher_backend.py','--endpoint-profile','octo']
|
|
if opt_in:argv+=['--source-realm-ui-readiness',PIN['path'],'--source-realm-ui-readiness-sha256',PIN['sha256']]
|
|
with patch.object(backend,'ROOT',self.root),patch.object(sys,'argv',argv),patch.object(backend,'supervise',return_value=0) as run,patch.dict(os.environ,{},clear=False):
|
|
self.assertEqual(backend.main(),0)
|
|
args=run.call_args.args[0]
|
|
self.assertEqual(args.source_realm_ui_readiness,PIN if opt_in else None)
|
|
with patch.object(manual,'run',return_value=2) as arm,patch.object(backend,'emit'),patch.object(backend.threading,'Thread'),patch.object(backend,'StatusLog',type('UnusedStatusLog',(),{})):
|
|
self.assertIsNone(backend.manual_login_handoff(args,None,123,Mock()))
|
|
self.assertEqual(arm.call_args.args[0].source_realm_ui_readiness,PIN if opt_in else None)
|
|
source=ast.parse((ROOT/'ops/debug_client_owner.py').read_text())
|
|
candidates=[n for n in ast.walk(source) if isinstance(n,ast.Dict) and any(isinstance(k,ast.Constant) and k.value=='activate-source-realm-ui' for k in n.keys)]
|
|
self.assertEqual(len(candidates),1)
|
|
mapping=candidates[0];index=next(i for i,k in enumerate(mapping.keys) if isinstance(k,ast.Constant) and k.value=='activate-source-realm-ui')
|
|
fn=eval(compile(ast.Expression(mapping.values[index]),'<actual-owner-rpc>','eval'),dict(engine_wire_host=Mock(),request=dict(readiness=PIN)))
|
|
fn(123,{'point':'fixture'})
|
|
fn.__globals__['engine_wire_host'].activate_realm_ui.assert_called_once_with(123,{'point':'fixture'},readiness=PIN)
|
|
def test_actual_dispatcher_marks_busy_before_activation_ack_and_does_not_authenticate(self):
|
|
source=(ROOT/'native/wine_wire_windows.c').read_text()
|
|
start=source.index('if(InterlockedCompareExchange(&gw_wire_frame_data.command,-11,11)==11)')
|
|
opening=source.index('{',start);depth=1;end=opening+1
|
|
while depth:
|
|
depth+=(source[end]=='{')-(source[end]=='}');end+=1
|
|
block=source[start:end]
|
|
account_source=(ROOT/'native/wine_wire_account.c').read_text()
|
|
start=account_source.index('__declspec(dllexport) void WINAPI gw_wire_account_ui_activate(void)')
|
|
opening=account_source.index('{',start);end=account_source.index('\n}',opening)+2
|
|
activate=account_source[start:end].replace('__declspec(dllexport)','').replace('WINAPI','')
|
|
code='''#include <assert.h>
|
|
typedef int LONG;
|
|
struct {LONG command,error;} gw_wire_frame_data;
|
|
struct {LONG enabled;} gw_wire_account_ui_data;
|
|
static LONG state,ui_bridge_ready,ui_auth_generation,calls;
|
|
static LONG InterlockedCompareExchange(LONG*p,LONG n,LONG old){LONG value=*p;if(value==old)*p=n;return value;}
|
|
static LONG InterlockedExchange(LONG*p,LONG n){LONG old=*p;*p=n;return old;}
|
|
'''+activate+'''
|
|
static void activate_checked(void){assert(gw_wire_frame_data.command==-11);++calls;gw_wire_account_ui_activate();}
|
|
#define gw_wire_account_ui_activate activate_checked
|
|
static void dispatch(void){'''+block+'''}
|
|
int main(void){state=2;gw_wire_frame_data.command=11;dispatch();assert(calls==1);assert(ui_bridge_ready==1);assert(gw_wire_frame_data.command==12);assert(!gw_wire_account_ui_data.enabled);
|
|
dispatch();assert(calls==1);state=1;gw_wire_frame_data.command=11;dispatch();assert(calls==1);assert(gw_wire_frame_data.command==12);assert(gw_wire_frame_data.error==4);
|
|
state=2;gw_wire_frame_data.command=3;dispatch();assert(calls==1);assert(gw_wire_frame_data.command==3);return 0;}
|
|
'''
|
|
source_path=self.root/'dispatcher.c';binary=self.root/'dispatcher';source_path.write_text(code)
|
|
result=subprocess.run(['cc','-std=c11','-Wall','-Wextra','-Werror',str(source_path),'-o',str(binary)],capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
result=subprocess.run([str(binary)],capture_output=True,text=True);self.assertEqual(result.returncode,0,result.stderr)
|
|
|
|
if __name__=='__main__':unittest.main()
|