Files
rust-discovery/tests/windows_auto_transport_acceptance.py
T
2026-11-13 23:43:37 +01:00

143 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""Local guards of the passive Windows fault runner; no network or VM."""
import copy
import hashlib
import pathlib
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT=pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'deploy/windows'))
import auto_transport_acceptance as auto
def flags(enabled=False):
role=dict(RMM_PROFILE='development',RMM_DEV_AUTH='true',RMM_DEV_TRANSPORT_FAULTS='true' if enabled else 'false',
RMM_DEV_TRANSPORT_FAULT_FILE='/root-policy/transport-fault.json' if enabled else None)
return dict(roles={'api':copy.deepcopy(role),'gateway':copy.deepcopy(role)},
compose_sha256='known-compose',root_policy_sha256='unchanged-closed-policy',fault_config_sha256='old-known-fault')
def receipts():
origin='2026-11-13T22:00:00+00:00'; ident='11111111-1111-4111-8111-111111111111'
config=dict(fault_id=ident)
baseline=dict(agent_id=auto.base.AGENT,asset_id=auto.base.ASSET,enrollment_generation=1,assignment_version=1,certificate_sha256='same-certificate')
rows=[dict(created_at=origin,data=dict(slot=i,handshake_id='handshake-'+str(i),status=503,
agent_id=auto.base.AGENT,tenant_id=auto.cloud.TENANT,fault_id=ident,config_sha256='new-known-fault',
testsimulation=True,certificate_sha256='same-certificate')) for i in (1,2)]
observed=dict(receipts=rows,device=dict(baseline,transport='https',last_contact_at='2026-11-13T22:00:01+00:00',sync_ready=False,restore_blocked=True))
return observed,config,baseline
class ReceiptGuards(unittest.TestCase):
def test_exact_peer_configuration_and_two_distinct_actual_rejections(self):
observed,config,baseline=receipts();auto.validate_receipts(observed,config,'new-known-fault',baseline)
for mutate in (
lambda value:value['receipts'][1]['data'].update(slot=1),
lambda value:value['receipts'][1]['data'].update(handshake_id='handshake-1'),
lambda value:value['receipts'][0]['data'].update(status=401),
lambda value:value['receipts'][0]['data'].update(certificate_sha256='other-certificate'),
lambda value:value['receipts'][0]['data'].update(config_sha256='unverified-host-hash'),
lambda value:value['receipts'][0]['data'].update(tenant_id='other-tenant'),
lambda value:value['receipts'][0]['data'].update(fault_id='other-fault'),
lambda value:value['receipts'][0]['data'].update(testsimulation=False),
lambda value:value['device'].update(assignment_version=2),
):
bad=copy.deepcopy(observed);mutate(bad)
with self.subTest(value=bad),self.assertRaises(auto.base.cb.contract.GuardError):
auto.validate_receipts(bad,config,'new-known-fault',baseline)
def test_hello_before_fresh_heartbeat_is_waited_for_without_inventing_sync(self):
observed,config,baseline=receipts()
before_heartbeat=copy.deepcopy(observed);before_heartbeat['device']['last_contact_at']='2026-11-13T21:59:59+00:00'
second=copy.deepcopy(observed);second['device']['last_contact_at']='2026-11-13T22:00:32+00:00'
with patch.object(auto,'observe',side_effect=[before_heartbeat,observed,second]),patch.object(auto.time,'sleep'):
outcome=auto.wait_fallback(config['fault_id'],config,'new-known-fault',baseline)
self.assertEqual(outcome['second']['device']['last_contact_at'],second['device']['last_contact_at'])
self.assertFalse(outcome['second']['device']['sync_ready'])
def test_both_real_roles_and_explicit_dev_profile_required(self):
self.assertTrue(auto.flags_disabled(flags(False)));self.assertTrue(auto.flags_enabled(flags(True)))
for role in ('api','gateway'):
wrong=flags(False);wrong['roles'][role]['RMM_PROFILE']='production'
self.assertFalse(auto.flags_disabled(wrong))
wrong=flags(False);wrong['roles'][role]['RMM_DEV_TRANSPORT_FAULT_FILE']='/unexpected/file'
self.assertFalse(auto.flags_disabled(wrong))
wrong=flags(True);wrong['roles'][role]['RMM_DEV_TRANSPORT_FAULTS']='false'
self.assertFalse(auto.flags_enabled(wrong))
class RestoreGuards(unittest.TestCase):
def test_already_disabled_and_original_wss_restored_are_only_read_back(self):
with tempfile.TemporaryDirectory() as tmp:
folder=pathlib.Path(tmp);auto.base.save(folder,'enable-intent.json',{'original_enable_started':True})
current=flags(False)
native=dict(agent_id=auto.base.AGENT,asset_id=auto.base.ASSET,transport='wss',
config_sha256=auto.base.ORIGINAL_CONFIG,config_acl_sha256='same-acl',service_state='Running',
hashes={'key':'unchanged'},acl_sha256={'key':'unchanged'},telemetry_creation_ticks=1,
journal=dict(integrity='ok',read_only=True,agent_id=auto.base.AGENT,sequence=7))
before=dict(server=current,native=copy.deepcopy(native))
intent=dict(id='11111111-1111-4111-8111-111111111111',config_sha256='new-known-fault',
compose_sha256='known-compose',source_sha256='qualified-source')
calls=[]
def remote(ident,action,**kwargs):
calls.append(action);self.assertEqual(action,'state');return native
with patch.object(auto,'status',return_value=current),patch.object(auto.base,'remote',side_effect=remote), \
patch.object(auto.cloud.bootstrap,'rpc',side_effect=AssertionError('no replayed activation or disable')):
auto.cleanup(folder,intent,before)
auto.cleanup(folder,intent,before)
self.assertEqual(calls,['state','state'])
self.assertEqual(auto.base.cb.contract.protected_json(folder/'disable-intent.json')['known_hashes'],['new-known-fault','old-known-fault'])
def test_unknown_host_fault_hash_never_becomes_mutation_authority(self):
with tempfile.TemporaryDirectory() as tmp:
folder=pathlib.Path(tmp);auto.base.save(folder,'enable-intent.json',{'original_enable_started':True})
before=flags(False);current=flags(True);current['fault_config_sha256']='unknown-host-hash'
intent=dict(id='11111111-1111-4111-8111-111111111111',config_sha256='new-known-fault',
compose_sha256='known-compose',source_sha256='qualified-source')
def denied_rpc(host,function,payload):
self.assertEqual(host,'server.conf')
self.assertIs(function,auto.fault.configure_server)
self.assertEqual(payload['expected_config_sha256'],['new-known-fault','old-known-fault'])
self.assertNotIn(current['fault_config_sha256'],payload['expected_config_sha256'])
raise auto.base.cb.contract.GuardError('actual file failed exact known CAS')
with patch.object(auto,'status',return_value=current),patch.object(auto.cloud.bootstrap,'rpc',side_effect=denied_rpc), \
patch.object(auto.base,'remote',side_effect=AssertionError('no Windows mutation before exact server cleanup')):
with self.assertRaises(auto.base.cb.contract.GuardError):auto.cleanup(folder,intent,dict(server=before))
def test_native_enter_lost_reply_closes_same_case_without_reentering(self):
https_id='22222222-2222-4222-8222-222222222222'
native=dict(agent_id=auto.base.AGENT,asset_id=auto.base.ASSET,transport='wss',
config_sha256=auto.base.ORIGINAL_CONFIG,config_acl_sha256='same-acl',service_state='Running',
hashes={'key':'unchanged'},acl_sha256={'key':'unchanged'},telemetry_creation_ticks=1,
journal=dict(integrity='ok',read_only=True,agent_id=auto.base.AGENT,sequence=7,pending_inventory_events=0))
current=flags(False)
current['compose_sha256']=hashlib.sha256((auto.cloud.ROOT/'deploy/server.compose.yaml').read_bytes()).hexdigest()
with tempfile.TemporaryDirectory() as tmp:
root=pathlib.Path(tmp);https=root/'https';prerequisite=https/https_id;prerequisite.mkdir(parents=True)
auto.base.save(prerequisite,'result.json',dict(verified=True,case='explicit_https',no_jobs_or_approvals=True,final_native=native))
calls=[]
def remote(ident,action,**kwargs):
calls.append(action)
if action=='enter':raise RuntimeError('lost reply')
return native
counts=dict(windows=dict(jobs=0,outbox=0,permits=0,unresolved=0),linux=dict(jobs=30,outbox=30,permits=26,unresolved=0))
with patch.object(auto,'STATE',root/'auto'),patch.object(auto.base,'STATE',https), \
patch.object(auto.base,'stage_script',return_value='known-source'),patch.object(auto.base,'remote',side_effect=remote), \
patch.object(auto,'status',return_value=current),patch.object(auto,'observe',return_value={'device':{}}), \
patch.object(auto,'scopes',return_value=counts),patch.object(auto,'prior_hash',return_value='old-known-fault'), \
patch.object(auto,'cleanup') as cleanup:
with self.assertRaisesRegex(RuntimeError,'lost reply'):auto.start(https_id)
self.assertEqual(calls,['state','enter'])
self.assertEqual(cleanup.call_count,1)
case=next((root/'auto').iterdir())
self.assertTrue((case/'enter-intent.json').exists())
self.assertTrue((case/'enter-failure.json').exists())
self.assertFalse((case/'result.json').exists())
if __name__=='__main__':unittest.main()