Files
WoW-Hybrid-gateway/tests/native_channel_policy_request_test.py

186 lines
13 KiB
Python

#!/usr/bin/env python3
import json,struct,sys,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import engine_channel_policy_host as p
import native_realm_contract as login
class Memory:
def __init__(self):self.data=bytearray(struct.pack('<12I',1,48,*([0]*10)));self.writes=[];self.closed=False;self.race=False;self.maps=[(a,a+64,'r-x','0','original')for a,_ in p.TARGETS]
def read(self,a,n):
if 0x30000<=a and a+n<=0x30030:return bytes(self.data[a-0x30000:a-0x30000+n])
if a==0x10098:return struct.pack('<I',5)
if a==0x10218:return b'\0\1'
if a==0x101a0:return struct.pack('<4Q',0x90000,0,0,0)
for address,value in p.TARGETS:
if a==address:return bytes.fromhex(value)
raise AssertionError((a,n))
def u64(self,a):
if a==0x145e7a098:return 0x10000
raise AssertionError(a)
def allowed(self,*args):return True
def write(self,a,b):
self.writes.append((a,bytes(b)));self.data[a-0x30000:a-0x30000+len(b)]=b
def close(self):self.closed=True
class Request(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.root/'docs/evidence/gameplay').mkdir(parents=True)
(self.root/'runtime/engine-poll-binding.json').write_text(json.dumps({'endpoint_profile':'local-explicit'}))
(self.root/'docs/evidence/gameplay/reference-instance-deferred-buffer-contract.json').write_text(json.dumps({'status':'real-callback-observed-only','hardware_registers_restored':True,'metadata':{'cursor':16}}))
self.mem=Memory();self.pipe={'error':0,'closed':0,'world_auth':1,'world':{'login_sent':1,'self_create':1}}
self.account={'state':2,'transport_prepared':1,'selected_index':0}
self.exports={'gw_wire_channel_policy':0x20000};self.identity='123';self.frame_calls=10
for target,name,value in [(p,'ROOT',self.root),(p.host,'Access',lambda pid:self.mem),(p,'_request_process',lambda pid:self.identity),(p,'_request_libraries',lambda *a:None),(p,'_request_frame',self.frame),(p.wire,'module',lambda access:(0x10000,{'exports':self.exports},{})),(p.wire,'inspect_account',lambda pid:self.account),(p.engine_pipe_host,'inspect',lambda pid:self.pipe),(login,'require_realm',lambda *a:None)]:
q=patch.object(target,name,value);q.start();self.addCleanup(q.stop)
q=patch('native_lifecycle_audit.audit');q.start();self.addCleanup(q.stop)
def frame(self,*a):
self.frame_calls+=1;return dict(calls=self.frame_calls,windows_thread=42)
def test_publication_owner_then_command_only(self):
result=p.request_enable(77);self.assertEqual(self.mem.writes,[(0x30028,struct.pack('<Q',0x10000)),(0x30008,struct.pack('<I',1))]);self.assertTrue(result['native_result_pending']);self.assertFalse(result['enabled_outcome_written']);self.assertTrue(self.mem.closed)
def test_consumed_command_readback_outcome_and_refusals(self):
# One affected asynchronous publication boundary, not a replay of preflight.
for case in ('native-success','disabled','native-error','wrong-owner','changed-current-owner',
'wrong-thread','unconsumed-command','wrong-ABI','wrong-size','owner-write-failed','other-write-error'):
with self.subTest(case=case):
self.mem=Memory();mem=self.mem;write=mem.write;original_owner=mem.u64
def publish(address,raw):
write(address,raw)
if case=='owner-write-failed' and address==0x30028:raise ValueError('Binding data write failed')
if address!=0x30008:return
struct.pack_into('<4I',mem.data,8,0,1,0,42)
if case=='disabled':struct.pack_into('<I',mem.data,12,0)
if case=='native-error':struct.pack_into('<I',mem.data,16,3)
if case=='wrong-owner':struct.pack_into('<Q',mem.data,40,0x11000)
if case=='changed-current-owner':mem.u64=lambda a:0x11000 if a==0x145e7a098 else original_owner(a)
if case=='wrong-thread':struct.pack_into('<I',mem.data,20,43)
if case=='unconsumed-command':struct.pack_into('<I',mem.data,8,1)
if case=='wrong-ABI':struct.pack_into('<I',mem.data,0,2)
if case=='wrong-size':struct.pack_into('<I',mem.data,4,47)
raise ValueError('Binding data is not writable' if case=='other-write-error' else 'Binding data write failed')
with patch.object(mem,'write',side_effect=publish):
if case=='native-success':
result=p.request_enable(77)
self.assertTrue(result['consumed_command_readback_admitted']);self.assertFalse(result['native_result_pending'])
self.assertFalse(result['enabled_outcome_written']);self.assertTrue(result['native_outcome_observed']['owner_matches'])
record=json.loads((self.root/'runtime/native-channel-policy-binding.json').read_text())
self.assertTrue(record['consumed_command_readback_admitted']);self.assertFalse(record['native_result_pending'])
else:
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(len(mem.writes),1 if case=='owner-write-failed' else 2)
self.assertTrue(mem.closed)
def test_dry_run_preserves_every_byte(self):
result=p.request_enable(77,publish=False);self.assertEqual(self.mem.writes,[]);self.assertFalse(result['request_published']);self.assertTrue(result['strict_owned_frame_preflight_verified']);self.assertGreater(result['frame_freshness']['calls_after'],result['frame_freshness']['calls_before'])
def test_pending_command_refused(self):
struct.pack_into('<I',self.mem.data,8,1)
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_stale_process_refused(self):
with patch.object(p,'_request_process',side_effect=['123','124']):
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_frame_changed_refused(self):
with patch.object(p,'_request_frame',side_effect=[{'calls':10,'windows_thread':42},ValueError('stale')]):
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_world_guards(self):
for field in ('error','closed','world_auth','login_sent','self_create'):
with self.subTest(field=field):
self.pipe={'error':0,'closed':0,'world_auth':1,'world':{'login_sent':1,'self_create':1}}
if field in self.pipe:self.pipe[field]=1 if field in ('error','closed')else 0
else:self.pipe['world'][field]=0
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_no_auth_when_not_prepared(self):
self.account['transport_prepared']=0
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_code_contract_refused(self):
with patch.object(self.mem,'allowed',side_effect=lambda a,n,mode:mode!='x'):
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_stalled_frame_refused(self):
with patch.object(p,'_request_frame',return_value={'calls':10,'windows_thread':42}),patch.object(p.time,'monotonic',side_effect=[0,3]):
with self.assertRaisesRegex(ValueError,'did not advance within3s'):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_slow_frame_budget_and_stalled_frame_refusal(self):
class Clock:
value=0.0
def monotonic(self):return self.value
def monotonic_ns(self):return int(self.value*1_000_000_000)
def sleep(self,seconds):self.value+=seconds
clock=Clock()
def delayed(*args):return dict(calls=10+(clock.value>=1.2),windows_thread=42)
with patch.object(p.time,'monotonic',clock.monotonic),patch.object(p.time,'monotonic_ns',clock.monotonic_ns),patch.object(p.time,'sleep',clock.sleep),patch.object(p,'_request_frame',delayed):
result=p.request_enable(77)
self.assertGreaterEqual(clock.value,1.2);self.assertLess(clock.value,5)
self.assertGreater(result['frame_freshness']['calls_after'],result['frame_freshness']['calls_before'])
self.assertEqual(self.mem.writes,[(0x30028,struct.pack('<Q',0x10000)),(0x30008,struct.pack('<I',1))])
self.assertTrue(result['native_result_pending']);self.assertFalse(result['enabled_outcome_written'])
self.mem=Memory();clock=Clock()
with patch.object(p.time,'monotonic',clock.monotonic),patch.object(p.time,'monotonic_ns',clock.monotonic_ns),patch.object(p.time,'sleep',clock.sleep),patch.object(p,'_request_frame',lambda *a:dict(calls=10,windows_thread=42)):
with self.assertRaisesRegex(ValueError,r'Existing native frame did not advance within3s .*10->10'):
p.request_enable(77)
self.assertGreaterEqual(clock.value,3);self.assertLess(clock.value,3.1)
self.assertEqual(self.mem.writes,[]);self.assertTrue(self.mem.closed)
def test_wrong_frame_thread_refused(self):
with patch.object(p,'_request_frame',side_effect=[{'calls':10,'windows_thread':42},{'calls':11,'windows_thread':43}]):
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_typed_protection_retries_read_only_then_publishes_once(self):
with patch.object(p,'_request_targets',side_effect=[p.NativeTargetTemporarilyProtected('cold'),None]),patch.object(p,'_refresh_request_maps'):
result=p.request_enable(77)
self.assertEqual(len(self.mem.writes),2);self.assertEqual(result['frame_freshness']['target_protection_retries'],1)
def test_protection_wait_rejects_world_loss_without_publication(self):
with patch.object(p,'_request_targets',side_effect=p.NativeTargetTemporarilyProtected('cold')),patch.object(p,'_refresh_request_maps'),patch.object(p.engine_pipe_host,'inspect',side_effect=[self.pipe,dict(self.pipe,closed=1)]):
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
def test_readable_prefix_mismatch_never_retries(self):
with patch.object(p,'_request_targets',side_effect=ValueError('signature')),patch.object(p,'_refresh_request_maps')as refresh:
with self.assertRaises(ValueError):p.request_enable(77)
refresh.assert_not_called();self.assertEqual(self.mem.writes,[])
def test_policy_outcome_preserved(self):
struct.pack_into('<I',self.mem.data,12,1)
with self.assertRaises(ValueError):p.request_enable(77)
self.assertEqual(self.mem.writes,[])
class ProtectionClassification(unittest.TestCase):
def test_only_existing_noaccess_span_is_transient(self):
mem=Memory();mem.maps=[(a,a+64,'---p','0','code')for a,_ in p.TARGETS]
with patch.object(mem,'allowed',return_value=False):
with self.assertRaises(p.NativeTargetTemporarilyProtected):p._request_targets(mem)
mem.maps=[]
with self.assertRaises(ValueError)as error:p._request_targets(mem)
self.assertNotIsInstance(error.exception,p.NativeTargetTemporarilyProtected)
mem.maps=[(a,a+64,'-w-p','0','code')for a,_ in p.TARGETS]
with self.assertRaises(ValueError)as error:p._request_targets(mem)
self.assertNotIsInstance(error.exception,p.NativeTargetTemporarilyProtected)
class Frame(unittest.TestCase):
def test_exact_bound_callback_and_native_frame(self):
with tempfile.TemporaryDirectory()as d:
root=Path(d);(root/'runtime').mkdir();binding={'pid':77,'restored':False,'wire_ping_only':False,'owner':0x10000,'bound_vtable':0x20000,'wire_frame_data':0x31000,'wire_frame_callback':0x32000,'data':0x40000};f=root/'runtime/engine-poll-binding.json';f.write_text(json.dumps(binding));values=[1,p.wire.SIZE,8,1,100,42,0,0,0,0,1234,0,0x40000]
class M:
def read(self,a,n):return struct.pack('<9IiIIQ',*values)
def u64(self,a):return {0x10000:0x20000,0x20028:0x32000}[a]
def allowed(self,*args):return True
with patch.object(p,'ROOT',root):
self.assertEqual(p._request_frame(M(),77,0x30000,{'gw_wire_frame_data':0x1000,'gw_wire_frame_callback':0x2000},0x10000)['calls'],100)
for index in (2,3,4,5,6,12):
old=values[index];values[index]=0 if index in(2,3,4,5,12)else 1
with self.subTest(index=index),self.assertRaises(ValueError):p._request_frame(M(),77,0x30000,{'gw_wire_frame_data':0x1000,'gw_wire_frame_callback':0x2000},0x10000)
values[index]=old
binding['pid']=78;f.write_text(json.dumps(binding))
with self.assertRaises(ValueError):p._request_frame(M(),77,0x30000,{'gw_wire_frame_data':0x1000,'gw_wire_frame_callback':0x2000},0x10000)
class Libraries(unittest.TestCase):
def test_exact_hash_and_mapping(self):
import hashlib
with tempfile.TemporaryDirectory()as d:
root=Path(d);build=root/'build';build.mkdir();pins={};mem=Memory();mem.maps=[];exe=root/'runtime/native-client/_classic_beta_/WowB.exe';exe.parent.mkdir(parents=True);exe.write_bytes(b'image');image_sha=hashlib.sha256(b'image').hexdigest()
for k in ('core','wire_unix','source_codec'):
f=build/(k+'.so');f.write_bytes(k.encode());pins[k+'_path']=str(f);pins[k+'_sha256']=hashlib.sha256(f.read_bytes()).hexdigest();mem.maps.append((0,0,'r','0',str(f)))
with patch.object(p,'ROOT',root):
p._request_libraries(mem,{'wire_unix_library':pins,'patched_sha256':image_sha})
mem.maps.pop()
with self.assertRaises(ValueError):p._request_libraries(mem,{'wire_unix_library':pins,'patched_sha256':image_sha})
mem.maps.append((0,0,'r','0',str(build/'source_codec.so')));(build/'core.so').write_bytes(b'changed')
with self.assertRaises(ValueError):p._request_libraries(mem,{'wire_unix_library':pins,'patched_sha256':image_sha})
if __name__=='__main__':unittest.main()