883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
276 lines
15 KiB
Python
276 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Mock-only policy support; never touches a client, UI, server, or socket."""
|
|
from collections import deque
|
|
from contextlib import ExitStack,redirect_stdout
|
|
import copy
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
|
import native_manual_gameplay_ready as ready
|
|
import native_manual_login
|
|
import client_session
|
|
|
|
|
|
def policy(warm=True,enabled=False):
|
|
return dict(enabled=enabled,error=0,command=0,owner_matches=enabled,
|
|
code_contracts=[dict(address=hex(address),readable=warm,executable=warm,
|
|
prefix_matches=warm,observed_prefix=prefix if warm else '') for address,prefix in ready.TARGETS])
|
|
|
|
|
|
class FakeClock:
|
|
def __init__(self):self.now=0.;self.sleeps=[]
|
|
def monotonic(self):return self.now
|
|
def sleep(self,seconds):
|
|
if not 0<seconds<=.2:raise AssertionError('Unexpected fixed wait')
|
|
self.sleeps.append(seconds);self.now+=seconds
|
|
|
|
|
|
class FakeController:
|
|
def __init__(self):
|
|
self.account=dict(state=2,error=0,auth_result=0,discovery_result=0,realm_count=1,
|
|
selected_index=0,transport_result=0,server_proof_verified=1,transport_prepared=1,
|
|
auth_port=3724,memory_credentials=dict(generation=1,consumed_generation=1),
|
|
realms=[dict(index=0,name='FixtureRealm',address='127.0.0.1:8090',flags=0,type=1,wire_id=0)])
|
|
self.pipe=dict(error=0,closed=0,world_auth=1,world=dict(login_sent=1,self_create=1))
|
|
self.engine=dict(netclient=dict(state_enum=5,packet_host=dict(self_create_consumed=True)))
|
|
self.policies=deque([policy()]);self.actions=[];self.calls=[];self.policy_reads=0
|
|
self.after_first=None;self.activate=True
|
|
self.pipe_reads=0;self.after_pipe=None
|
|
|
|
def rpc(self,operation):
|
|
self.calls.append(operation)
|
|
if operation=='inspect-wire-account':return copy.deepcopy(self.account)
|
|
if operation=='inspect-engine-pipe':
|
|
self.pipe_reads+=1;result=copy.deepcopy(self.pipe)
|
|
if self.after_pipe:self.after_pipe()
|
|
return result
|
|
if operation=='inspect-engine-session':return copy.deepcopy(self.engine)
|
|
if operation=='inspect-native-channel-policy':
|
|
self.policy_reads+=1
|
|
current=self.policies.popleft() if len(self.policies)>1 else self.policies[0]
|
|
result=copy.deepcopy(current)
|
|
if self.after_first and self.policy_reads==1:self.after_first()
|
|
return result
|
|
raise AssertionError('Unapproved RPC; no authentication/world/gameplay actions')
|
|
|
|
def action(self,operation):
|
|
if operation!='enable-native-channel-policy':raise AssertionError('Unapproved policy action')
|
|
self.actions.append(operation)
|
|
if self.activate:self.policies=deque([policy(enabled=True)])
|
|
|
|
|
|
class ManualGameplayReadyTest(unittest.TestCase):
|
|
def setUp(self):
|
|
old_umask=os.umask(0o077);self.addCleanup(os.umask,old_umask)
|
|
temporary=tempfile.TemporaryDirectory(prefix='manual-policy-mock-');self.addCleanup(temporary.cleanup)
|
|
self.root=Path(temporary.name);(self.root/'runtime').mkdir()
|
|
(self.root/'runtime/native-client.pid').write_text('123')
|
|
self.controller=FakeController();self.clock=FakeClock()
|
|
self.stack=ExitStack();self.addCleanup(self.stack.close)
|
|
for module in (ready,native_manual_login):self.stack.enter_context(patch.object(module,'ROOT',self.root))
|
|
self.stack.enter_context(patch.object(ready,'local_listeners',return_value=set()))
|
|
self.stack.enter_context(patch.object(ready,'Controller',side_effect=lambda pid:self.controller))
|
|
self.stack.enter_context(patch.object(Path,'is_socket',return_value=True))
|
|
self.stack.enter_context(patch.object(ready.time,'monotonic',side_effect=self.clock.monotonic))
|
|
self.stack.enter_context(patch.object(ready.time,'sleep',side_effect=self.clock.sleep))
|
|
self.stack.enter_context(patch.object(socket,'socket',side_effect=AssertionError('No sockets in mocks')))
|
|
self.stack.enter_context(patch.object(subprocess,'run',side_effect=AssertionError('No subprocess in mocks')))
|
|
self.stack.enter_context(patch.object(client_session,'Session',side_effect=AssertionError('No UI/input in policy helper')))
|
|
self.binding()
|
|
|
|
def binding(self,**changes):
|
|
value=dict(dict(pid=123,restored=False,endpoint_profile='local-explicit'),**changes)
|
|
(self.root/'runtime/engine-poll-binding.json').write_text(json.dumps(value))
|
|
|
|
def run_helper(self,timeout=30,profile='local-explicit',wait_world=0):
|
|
report={}
|
|
with redirect_stdout(io.StringIO()) as output:
|
|
result=ready.run(profile,timeout,report,wait_world=wait_world)
|
|
return result,report,output.getvalue()
|
|
|
|
def test_warm_contracts_enable_only_existing_policy(self):
|
|
result,report,_=self.run_helper()
|
|
self.assertEqual(result,0)
|
|
self.assertTrue(report['policy_enabled'])
|
|
self.assertFalse(report['reused'])
|
|
self.assertEqual(self.controller.actions,['enable-native-channel-policy'])
|
|
self.assertGreaterEqual(self.controller.policy_reads,3) # Initial, fresh guard, activation.
|
|
self.assertTrue(set(self.controller.calls)<={'inspect-wire-account','inspect-engine-pipe',
|
|
'inspect-engine-session','inspect-native-channel-policy'})
|
|
|
|
def test_healthy_enabled_policy_is_reused_without_action(self):
|
|
# Cold code flags do not invalidate an already enabled healthy policy;
|
|
# its existing native runtime retains all deferred-call checks.
|
|
self.controller.policies=deque([policy(warm=False,enabled=True)])
|
|
result,report,_=self.run_helper()
|
|
self.assertEqual(result,0);self.assertTrue(report['reused'])
|
|
self.assertEqual(self.controller.actions,[]);self.assertEqual(self.clock.sleeps,[])
|
|
|
|
def test_cold_original_code_can_naturally_warm(self):
|
|
self.controller.policies=deque([policy(warm=False),policy(),policy()])
|
|
result,report,output=self.run_helper()
|
|
self.assertEqual(result,0);self.assertTrue(report['policy_enabled'])
|
|
self.assertIn('This helper sends no input or chat',output)
|
|
self.assertEqual(self.controller.actions,['enable-native-channel-policy'])
|
|
self.assertTrue(self.clock.sleeps)
|
|
|
|
def test_false_prefix_flags_alone_are_cold_and_timeout_without_action(self):
|
|
cold=policy()
|
|
for row in cold['code_contracts']:row.update(prefix_matches=False,observed_prefix='encoded-unverified')
|
|
self.controller.policies=deque([cold])
|
|
with redirect_stdout(io.StringIO()),self.assertRaises(TimeoutError):self.run_helper()
|
|
self.assertEqual(self.controller.actions,[])
|
|
self.assertGreaterEqual(self.clock.now,30)
|
|
self.assertLess(self.clock.now,30.3)
|
|
|
|
def test_account_profile_pipe_or_engine_changes_stop_before_enable(self):
|
|
changes=(lambda:self.binding(endpoint_profile='octo'),
|
|
lambda:self.controller.account.update(server_proof_verified=0),
|
|
lambda:self.controller.account['memory_credentials'].update(generation=2),
|
|
lambda:self.controller.account['realms'][0].update(name='DifferentRealm'),
|
|
lambda:self.controller.pipe.update(closed=1),
|
|
lambda:self.controller.engine['netclient'].update(state_enum=4),
|
|
lambda:self.controller.engine['netclient']['packet_host'].update(self_create_consumed=False))
|
|
for change in changes:
|
|
with self.subTest(change=change):
|
|
self.binding();self.controller=FakeController()
|
|
self.controller.policies=deque([policy(warm=False),policy()])
|
|
self.controller.after_first=change
|
|
with self.assertRaises(ValueError),redirect_stdout(io.StringIO()):self.run_helper()
|
|
self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_fresh_world_guard_after_warm_observation_is_required(self):
|
|
self.controller.after_first=lambda:self.controller.pipe['world'].update(self_create=0)
|
|
with self.assertRaises(ValueError):self.run_helper()
|
|
self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_changed_contract_metadata_or_policy_ownership_is_rejected(self):
|
|
cases=[]
|
|
for mutate in (lambda p:p.update(code_contracts=[]),
|
|
lambda p:p['code_contracts'][0].update(address='0x1'),
|
|
lambda p:p['code_contracts'][0].update(observed_prefix='contradictory'),
|
|
lambda p:p.update(error=8),
|
|
lambda p:p.update(enabled=True,owner_matches=False),
|
|
lambda p:p.update(command=2),
|
|
lambda p:p.update(owner_matches=True)):
|
|
candidate=policy();mutate(candidate);cases.append(candidate)
|
|
for candidate in cases:
|
|
with self.subTest(candidate=candidate):
|
|
self.controller=FakeController();self.controller.policies=deque([candidate])
|
|
with self.assertRaises(ValueError):self.run_helper()
|
|
self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_global_public_realm_required_for_public_profile(self):
|
|
self.binding(endpoint_profile='octo')
|
|
with self.assertRaises(ValueError):self.run_helper(profile='octo')
|
|
self.controller.account['realms'][0]['address']='8.8.8.8:8090'
|
|
result,report,_=self.run_helper(profile='octo')
|
|
self.assertEqual(result,0);self.assertEqual(report['endpoint_profile'],'octo')
|
|
|
|
def test_gateway_or_failed_authentication_never_enables(self):
|
|
with patch.object(ready,'local_listeners',return_value={19085}):
|
|
with self.assertRaises(ValueError):self.run_helper()
|
|
self.assertEqual(self.controller.calls,[])
|
|
for changes in (dict(state=5),dict(auth_result=-2),dict(discovery_result=-2),dict(transport_prepared=0)):
|
|
with self.subTest(changes=changes):
|
|
self.controller=FakeController();self.controller.account.update(changes)
|
|
with self.assertRaises(ValueError):self.run_helper()
|
|
self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_activation_timeout_is_not_retried(self):
|
|
self.controller.activate=False
|
|
with self.assertRaises(TimeoutError):self.run_helper()
|
|
self.assertEqual(self.controller.actions,['enable-native-channel-policy'])
|
|
|
|
def pending_world(self):
|
|
self.controller.pipe['world'].update(login_sent=0,self_create=0)
|
|
self.controller.engine['netclient'].update(state_enum=2)
|
|
self.controller.engine['netclient']['packet_host']['self_create_consumed']=False
|
|
|
|
def complete_world(self):
|
|
self.controller.pipe['world'].update(login_sent=1,self_create=1)
|
|
self.controller.engine['netclient'].update(state_enum=5)
|
|
self.controller.engine['netclient']['packet_host']['self_create_consumed']=True
|
|
|
|
def test_optional_wait_observes_manual_world_entry_before_any_policy_inspection(self):
|
|
self.pending_world()
|
|
def manual_entry():
|
|
if self.controller.pipe_reads==2:
|
|
self.assertEqual(self.controller.policy_reads,0)
|
|
self.assertEqual(self.controller.actions,[])
|
|
self.complete_world()
|
|
self.controller.after_pipe=manual_entry
|
|
result,report,output=self.run_helper(wait_world=10)
|
|
self.assertEqual(result,0);self.assertEqual(self.controller.actions,['enable-native-channel-policy'])
|
|
self.assertGreaterEqual(report['world_wait_polls'],2)
|
|
self.assertIn('performs no login, selection, world entry',output)
|
|
self.assertTrue(set(self.controller.calls)<={'inspect-wire-account','inspect-engine-pipe','inspect-engine-session','inspect-native-channel-policy'})
|
|
|
|
def test_wait_timeout_preserves_pending_world_without_policy_action(self):
|
|
self.pending_world()
|
|
with self.assertRaises(TimeoutError):self.run_helper(wait_world=1)
|
|
self.assertEqual(self.clock.now,1)
|
|
self.assertEqual(self.controller.actions,[]);self.assertEqual(self.controller.policy_reads,0)
|
|
|
|
def test_default_does_not_wait_or_enable_before_world_entry(self):
|
|
self.pending_world()
|
|
with self.assertRaises(ValueError):self.run_helper()
|
|
self.assertEqual(self.clock.sleeps,[]);self.assertEqual(self.controller.policy_reads,0)
|
|
|
|
def test_wait_rejects_changed_identity_or_failed_transport_without_action(self):
|
|
changes=(lambda:(self.root/'runtime/native-client.pid').write_text('456'),
|
|
lambda:self.binding(endpoint_profile='octo'),
|
|
lambda:self.controller.account.update(server_proof_verified=0),
|
|
lambda:self.controller.account.update(transport_prepared=0),
|
|
lambda:self.controller.account.update(transport_result=-2),
|
|
lambda:self.controller.account['memory_credentials'].update(generation=2,consumed_generation=2),
|
|
lambda:self.controller.account['realms'][0].update(address='127.0.0.1:8091'),
|
|
lambda:self.controller.pipe.update(error=1),
|
|
lambda:self.controller.pipe.update(closed=1),
|
|
lambda:self.controller.pipe.update(world_auth=0))
|
|
for change in changes:
|
|
with self.subTest(change=change):
|
|
(self.root/'runtime/native-client.pid').write_text('123');self.binding()
|
|
self.controller=FakeController();self.pending_world();self.controller.after_pipe=change
|
|
with self.assertRaises(ValueError):self.run_helper(wait_world=10)
|
|
self.assertEqual(self.controller.actions,[]);self.assertEqual(self.controller.policy_reads,0)
|
|
|
|
def test_wait_requires_identifiable_consumed_credential_generation(self):
|
|
for credentials in ({},dict(generation=0,consumed_generation=0),dict(generation=1,consumed_generation=0)):
|
|
with self.subTest(credentials=credentials):
|
|
self.controller=FakeController();self.controller.account['memory_credentials']=credentials;self.pending_world()
|
|
with self.assertRaises(ValueError):self.run_helper(wait_world=10)
|
|
self.assertEqual(self.clock.sleeps,[]);self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_world_readiness_is_rechecked_strictly_after_wait(self):
|
|
self.pending_world()
|
|
def transition():
|
|
if self.controller.pipe_reads==1:self.complete_world()
|
|
elif self.controller.pipe_reads==2:self.controller.pipe['world']['self_create']=0
|
|
self.controller.after_pipe=transition
|
|
with self.assertRaises(ValueError):self.run_helper(wait_world=10)
|
|
self.assertEqual(self.controller.actions,[])
|
|
|
|
def test_cli_redacts_errors_and_does_not_claim_acceptance(self):
|
|
path=self.root/'runtime/failed-policy.json'
|
|
with patch.object(sys,'argv',['manual-policy','--output',str(path)]),patch.object(ready,'run',side_effect=RuntimeError('PRIVATE-CREDENTIAL-CANARY')),redirect_stdout(io.StringIO()) as output:
|
|
self.assertEqual(ready.main(),2)
|
|
report=json.loads(path.read_text())
|
|
self.assertFalse(report['native_acceptance_verified'])
|
|
self.assertFalse(report['gameplay_input_automated'])
|
|
self.assertFalse(report['screenshots_captured'])
|
|
self.assertEqual(report['failure_type'],'RuntimeError')
|
|
self.assertNotIn('PRIVATE-CREDENTIAL-CANARY',path.read_text()+output.getvalue())
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|