Files
WoW-Hybrid-gateway/tests/debug_owner_fixed_code_window_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

278 lines
17 KiB
Python

"""Fixed original-image CODE observation, without clients or authentication.
Use the retained PE header and independently certified unwind ranges. Exercise
CLI -> actual request/helper -> private file with a bounded memory-reader spy;
all negative requests must fail before any process-memory I/O.
"""
import argparse
import contextlib
import hashlib
import io
import json
from pathlib import Path
import stat
import struct
import sys
import tempfile
import unittest
import zlib
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'ops'))
import client_installation
with patch.object(client_installation, 'client_debug_socket', return_value=ROOT / 'runtime/fixed-code-fixture.sock'):
import debug_client_owner as owner
JOB = ROOT / 'runtime/rea-system-jobs-20261022/map-zone-definition-closure-20261024/activation-helper-continuation'
HEADER = ROOT / 'runtime/rea-system-jobs-20261022/replacement-races-activation-20261024/row-application-continuation/pinned-original-PE-headers.bin'
class FixedCodeWindowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.header = HEADER.read_bytes()
cls.certified = {}
for selector, proof in [('row-ingestion', 'db-reply-first-ingestion-unwind-bounds.json'),
('post-ingestion', 'db-reply-post-ingestion-unwind-bounds.json'),
('registry-getter', 'descriptor-registry-root-unwind-bounds.json')]:
item = json.loads((JOB / proof).read_text())['requests'][0]
cls.certified[selector] = (int(item['start_rva'], 16), item['bytes'])
continuation = json.loads((ROOT / 'runtime/continuation-20261027/MapAreaLod-height-constructor758/type4-role-selector-continuation101-qualified-private.json').read_text())
assert continuation['status'] == 'PASS_REACHED_TYPE4_ROLE_SELECTOR_CONTINUATION101_CHAIN_QUALIFIED'
assert all(part['root']['begin_RVA'] == '0x20c3360' for part in continuation['parts'])
cls.certified['lod2-type4-continuation'] = (int(continuation['RVA'], 16), continuation['bytes'])
cls.mapping = [f'{owner.BASE:x}-{owner.BASE + 0x5000000:x} r--p 00000000 00:00 0']
def invoke(self, request, reader, *, header=None, mappings=None, image_sha=None):
return owner.read_fixed_image_code_window(
request, image_sha256=owner.PINNED_CLIENT_SHA256 if image_sha is None else image_sha,
image_header=self.header if header is None else header,
mappings=self.mapping if mappings is None else mappings, read_memory=reader)
def test_actual_cli_route_fixed_ranges_and_private_output(self):
self.assertEqual(owner.FIXED_IMAGE_CODE_WINDOWS, self.certified)
for selector, (rva, size) in self.certified.items():
with self.subTest(selector=selector), tempfile.TemporaryDirectory(dir=ROOT / 'runtime') as temporary:
output = Path(temporary) / 'code.bin'
calls = []
expected = bytes((i + rva) % 256 for i in range(size))
def reader(address, count):
calls.append((address, count))
self.assertEqual((address, count), (owner.BASE + rva, size))
return expected
test = self
class Socket:
def connect(self, address):
test.assertEqual(address, str(owner.SOCKET))
def sendall(self, data):
request = json.loads(data)
test.assertEqual(request, {'operation': 'read-fixed-image-code', 'window': selector})
self.reply = b'OK\n' + test.invoke(request, reader)
def recv(self, limit):
result, self.reply = self.reply[:limit], self.reply[limit:]
return result
def close(self):
pass
with patch.object(owner.socket, 'socket', return_value=Socket()), patch.object(
sys, 'argv', ['debug_client_owner.py', 'read-fixed-code', selector, str(output)]), contextlib.redirect_stdout(io.StringIO()):
owner.read_fixed_code()
self.assertEqual(calls, [(owner.BASE + rva, size)])
self.assertEqual(output.read_bytes(), expected)
self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
def test_invalid_requests_identity_sections_and_maps_do_not_read(self):
request = {'operation': 'read-fixed-image-code', 'window': 'row-ingestion'}
pe = struct.unpack_from('<I', self.header, 0x3c)[0]
optional_size = struct.unpack_from('<H', self.header, pe + 20)[0]
section_count = struct.unpack_from('<H', self.header, pe + 6)[0]
table = pe + 24 + optional_size
text = next(table + i * 40 for i in range(section_count)
if self.header[table + i * 40:table + i * 40 + 8].rstrip(b'\0') == b'.text')
nonexec = bytearray(self.header)
struct.pack_into('<I', nonexec, text + 36, 0x40000040)
partial = bytearray(self.header)
start = struct.unpack_from('<I', self.header, text + 12)[0]
rva, size = self.certified['row-ingestion']
struct.pack_into('<I', partial, text + 8, rva + size - start - 1)
cases = [
('unknown selector', {'request': dict(request, window='arbitrary-code')}),
('nonstring selector', {'request': dict(request, window=[])}),
('RVA injection', {'request': dict(request, rva=0x649130)}),
('size injection', {'request': dict(request, size=475)}),
('PID injection', {'request': dict(request, pid=123)}),
('wrong operation', {'request': dict(request, operation='inspect-engine-session')}),
('wrong image', {'image_sha': '0' * 64}),
('bad header', {'header': b'not a PE image'}),
('nonexecutable PE section', {'header': bytes(nonexec)}),
('partial PE extent', {'header': bytes(partial)}),
('unmapped', {'mappings': []}),
('unreadable', {'mappings': [self.mapping[0].replace('r--p', '--xp')]}),
('partial runtime extent', {'mappings': [f'{owner.BASE + rva:x}-{owner.BASE + rva + size - 1:x} r--p 0 00:00 0']}),
]
for label, options in cases:
with self.subTest(label=label):
calls = []
kwargs = dict(options)
supplied = kwargs.pop('request', request)
def reader(address, count):
calls.append((address, count))
raise AssertionError('Out-of-scope memory reader reached')
with self.assertRaises(RuntimeError):
self.invoke(supplied, reader, **kwargs)
self.assertEqual(calls, [])
def test_short_read_refuses_without_additional_io(self):
rva, size = self.certified['registry-getter']
calls = []
def reader(address, count):
calls.append((address, count))
return b'x' * (count - 1)
with self.assertRaisesRegex(RuntimeError, 'Incomplete fixed code-window read'):
self.invoke({'operation': 'read-fixed-image-code', 'window': 'registry-getter'}, reader)
self.assertEqual(calls, [(owner.BASE + rva, size)])
def test_cli_output_outside_runtime_refuses_before_socket(self):
with patch.object(owner.socket, 'socket') as socket, patch.object(
sys, 'argv', ['debug_client_owner.py', 'read-fixed-code', 'row-ingestion', '/tmp/not-runtime-code.bin']):
with self.assertRaisesRegex(RuntimeError, 'output must remain under runtime'):
owner.read_fixed_code()
socket.assert_not_called()
def test_type4_continuation_exact_cli_and_refusal_boundary(self):
selector = 'lod2-type4-continuation'
rva, size = self.certified[selector]
self.assertEqual(owner.FIXED_IMAGE_CODE_WINDOWS, self.certified)
self.assertEqual((rva, size), (0x20c341e, 101))
calls = []
expected = bytes(range(size))
def reader(address, count):
calls.append((address, count))
self.assertEqual((address, count), (owner.BASE + rva, size))
return expected
request = {'operation': 'read-fixed-image-code', 'window': selector}
test = self
class Socket:
def connect(self, address):
test.assertEqual(address, str(owner.SOCKET))
def sendall(self, data):
test.assertEqual(json.loads(data), request)
self.reply = b'OK\n' + test.invoke(request, reader)
def recv(self, limit):
result, self.reply = self.reply[:limit], self.reply[limit:]
return result
def close(self):
pass
with tempfile.TemporaryDirectory(dir=ROOT / 'runtime') as temporary:
output = Path(temporary) / 'type4-code.bin'
with patch.object(owner.socket, 'socket', return_value=Socket()), patch.object(
sys, 'argv', ['debug_client_owner.py', 'read-fixed-code', selector, str(output)]), contextlib.redirect_stdout(io.StringIO()):
owner.read_fixed_code()
self.assertEqual(calls, [(owner.BASE + rva, size)])
self.assertEqual(output.read_bytes(), expected)
self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
for options in ({'request': dict(request, rva=rva)},
{'request': dict(request, size=size)},
{'request': dict(request, window='lod2-vtable')},
{'image_sha': '0' * 64},
{'mappings': [f'{owner.BASE + rva:x}-{owner.BASE + rva + size:x} --xp 0 00:00 0']},
{'mappings': [f'{owner.BASE + rva:x}-{owner.BASE + rva + size - 1:x} r--p 0 00:00 0']}):
with self.subTest(options=options):
supplied = dict(options)
selected = supplied.pop('request', request)
with self.assertRaises(RuntimeError):
self.invoke(selected, lambda *_: self.fail('Refused request reached memory I/O'), **supplied)
def test_finite_function_index_qualified_receipts_and_named_reads(self):
index = owner.load_fixed_code_function_index(ROOT / owner.FIXED_CODE_FUNCTION_INDEX)
job = ROOT / 'runtime/continuation-20261027/MapAreaLod-height-constructor758'
receipt = json.loads((job / 'complete-c49-function-index/derivation-receipt-private.json').read_text())
self.assertEqual(len(index), receipt['selector_count'])
self.assertEqual(receipt['resolved_table_entries'] + receipt['held_table_entries'], 304691)
self.assertEqual(receipt['held_reasons'], {'unsupported unwind version 2': 30})
qualified = json.loads((job / 'exact-three-direct-vtable-method-bounds-private.json').read_text())
for row in qualified['rows']:
start = int(row['begin_RVA'], 16)
self.assertEqual(index[f'c49-function-{start:08x}'], ((start, row['bytes']),))
fatal = ROOT / 'runtime/continuation-20261027/GrimReaches-M2-collision-sequence-RCA/fatal-M2Shared2794'
callframes = json.loads((fatal / 'fatal-M2Shared-callframe-unwind-qualification-private.json').read_text())
root = callframes['rows'][0]['root']; start = int(root['begin_RVA'], 16)
self.assertEqual(index[f'c49-function-{start:08x}'], ((start, root['bytes']),))
caller = json.loads((fatal / 'exact-sequence-selection-caller-family-qualified-private.json').read_text())
start = int(caller['root_RVA'], 16)
self.assertEqual(index[f'c49-function-{start:08x}'], ((start, sum(r['bytes'] for r in caller['parts'])),))
continuation = json.loads((job / 'type4-role-selector-continuation101-qualified-private.json').read_text())
for part in continuation['parts']:
row = part['entry']; start = int(row['begin_RVA'], 16)
self.assertEqual(index[f'c49-entry-{start:08x}'], ((start, int(row['end_RVA'], 16) - start),))
self.assertEqual(index['c49-function-020c3360'], ((0x20c3360, 291),))
held = json.loads((job / 'complete-c49-function-index/held-table-entries-private.json').read_text())
self.assertTrue(all(f'c49-entry-{r["entry"][0]:08x}' not in index for r in held))
with self.assertRaises(TypeError):
index['invented'] = ((0x20c341e, 101),)
selector = 'c49-function-020c3360'
request = {'operation': 'read-fixed-image-code', 'window': selector}
calls = []
def read(address, size):
calls.append((address, size)); return b'C' * size
def invoke(request, **options):
return owner.read_fixed_image_code_window(request, image_sha256=options.get('image_sha', owner.PINNED_CLIENT_SHA256),
image_header=options.get('header', self.header), mappings=options.get('mappings', self.mapping),
read_memory=options.get('reader', read), function_windows=options.get('windows', index))
test = self
class Socket:
def connect(self, address):
test.assertEqual(address, str(owner.SOCKET))
def sendall(self, data):
test.assertEqual(json.loads(data), request); self.reply = b'OK\n' + invoke(request)
def recv(self, limit):
result, self.reply = self.reply[:limit], self.reply[limit:]; return result
def close(self):
pass
with tempfile.TemporaryDirectory(dir=ROOT / 'runtime') as temporary:
output = Path(temporary) / 'indexed-function.bin'
with patch.object(owner.socket, 'socket', return_value=Socket()), patch.object(
sys, 'argv', ['debug_client_owner.py', 'read-fixed-code', selector, str(output)]), contextlib.redirect_stdout(io.StringIO()):
owner.read_fixed_code()
self.assertEqual(calls, [(owner.BASE + 0x20c3360, 291)])
self.assertEqual(output.read_bytes(), b'C' * 291)
self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
payload = dict(schema='c49-original-function-chain-code-index-v1', image_sha256=owner.PINNED_CLIENT_SHA256,
image_base=owner.BASE, max_read_bytes=65536,
windows={'c49-function-01da07f0': [[0x1da07f0, 1032], [0x20c2220, 758]]})
raw = zlib.compress(json.dumps(payload).encode()); fixture = Path(temporary) / 'finite-index.zlib'; fixture.write_bytes(raw)
with self.assertRaisesRegex(RuntimeError, 'index identity differs'):
owner.load_fixed_code_function_index(fixture)
with patch.object(owner, 'FIXED_CODE_FUNCTION_INDEX_SHA256', hashlib.sha256(raw).hexdigest()):
disjoint = owner.load_fixed_code_function_index(fixture)
named = {'operation': 'read-fixed-image-code', 'window': 'c49-function-01da07f0'}
calls.clear(); self.assertEqual(invoke(named, windows=disjoint), b'C' * 1790)
self.assertEqual(calls, [(owner.BASE + 0x1da07f0, 1032), (owner.BASE + 0x20c2220, 758)])
with self.assertRaisesRegex(RuntimeError, 'not fully readable'):
invoke(named, windows=disjoint, mappings=[f'{owner.BASE + 0x1da07f0:x}-{owner.BASE + 0x1da07f0 + 1032:x} r--p 0 00:00 0'],
reader=lambda *_: self.fail('Partially readable chain reached memory I/O'))
for bad, options in [(dict(request, rva=0x20c3360), {}), (dict(request, size=291), {}),
(dict(request, window='c49-function-ffffffff'), {}), (request, {'image_sha': '0' * 64}),
(request, {'mappings': []})]:
with self.assertRaises(RuntimeError):
invoke(bad, reader=lambda *_: self.fail('Refused named read reached memory I/O'), **options)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--result', type=Path, required=True)
parser.add_argument('--type4-continuation-only', action='store_true')
parser.add_argument('--function-index-only', action='store_true')
arguments = parser.parse_args()
suite = (unittest.TestSuite([FixedCodeWindowTest('test_finite_function_index_qualified_receipts_and_named_reads')])
if arguments.function_index_only else unittest.TestSuite([FixedCodeWindowTest('test_type4_continuation_exact_cli_and_refusal_boundary')])
if arguments.type4_continuation_only else unittest.defaultTestLoader.loadTestsFromTestCase(FixedCodeWindowTest))
result = unittest.TextTestRunner(verbosity=2).run(suite)
arguments.result.write_text(json.dumps({'status': 'PASS' if result.wasSuccessful() else 'FAIL',
'tests': result.testsRun, 'failures': len(result.failures), 'errors': len(result.errors),
'certified_windows': 4, 'finite_function_index_boundary': arguments.function_index_only,
'pre_IO_refusal_cases': 7 if arguments.function_index_only else 6 if arguments.type4_continuation_only else 26, 'actual_client_started_or_read': False,
'page_protection_or_input_changed': False}, indent=2) + '\n')
sys.exit(0 if result.wasSuccessful() else 1)