Files
rust-discovery/tests/linux_managed_helper_rollover.py
T

137 lines
6.4 KiB
Python

"""Restart and access-boundary regressions for the managed development helper."""
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from contextlib import ExitStack
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('rollover', Path(__file__).resolve().parents[1] /
'tools/dev_linux_helper_rollover.py')
op = importlib.util.module_from_spec(spec)
spec.loader.exec_module(op)
class LinuxHelperSwitch(unittest.TestCase):
def setUp(self):
stack = ExitStack()
self.addCleanup(stack.close)
root = Path(stack.enter_context(tempfile.TemporaryDirectory()))
cfg = root/'etc'
cfg.mkdir()
self.unit = root/'helper.service'
self.proof, self.settings = cfg/'agent-pin.json', cfg/'helper.json'
self.args = SimpleNamespace(tenant='tenant', asset='asset', agent='agent',
previous='old', current='new', action='switch')
self.old, self.new = root/'old', root/'new'
self.old.mkdir()
self.new.mkdir()
(root/'release.lock').touch()
(root/'config.json').write_bytes(op.encoded({'tenant': 'tenant'}))
(root/'current').symlink_to(self.new)
self.binding = dict(tenant_id='tenant', asset_id='asset', agent_id='agent',
enrollment_generation=1, assignment_version=1)
self.hashes = ['1'*64, '2'*64]
locked = dict(binding=self.binding, profile='full_maintenance_v1', allowed_services=[],
allow_reboot=False, allow_root_scripts=True, helper_binary_sha256=self.hashes[0])
self.settings.write_bytes(op.encoded(locked))
self.proof.write_bytes(self.sign(locked))
self.unit.write_text(f'[Service]\nExecStart={self.old}/helper\nOther=unchanged\n')
self.live = {self.unit.name:self.old/'helper', op.AGENT:self.new/'agent'}
self.restart_count = 0
for name, value in [('ROOT',root),('CONFIG',cfg),('UNIT',self.unit),
('protected',lambda path: None),('process_image',self.live.get),
('run',self.command),('prop',self.prop),('pair',self.pair)]:
stack.enter_context(patch.object(op, name, value))
stack.enter_context(patch.object(op.os,'geteuid',return_value=0))
self.before = [p.read_bytes() for p in [self.settings,self.proof,self.unit]]
def sign(self, config):
sha = hashlib.sha256(op.encoded(config)).hexdigest()
return op.encoded(dict(identity=self.binding,policy_sha256=sha,
helper_binary_sha256=config['helper_binary_sha256']))
def pair(self, release):
idx = int(release == 'new')
return (self.old, self.new)[idx], {'release_sequence':1+idx,'version':str(idx)}, self.hashes[idx]
def prop(self, unit, field):
if field == 'ActiveState':
return 'inactive'
if field == 'FragmentPath':
return str(self.unit)
if field == 'ExecStart':
path = self.unit.read_text().split('ExecStart=')[1].splitlines()[0]
return f'{{ path={path} ; argv[]={path} ; }}'
if field == 'Environment':
return 'RMM_HELPER_CONFIG='+str(self.settings)
raise AssertionError(field)
def command(self,*args,**kw):
if args[0] == 'runuser':
if args[-1] == 'idle':
return b'idle'
return op.encoded({'asset_id':'asset','agent_id':'agent'})
if args[1] == '--inspect-full-maintenance-profile':
return self.sign(json.loads(Path(kw['env']['RMM_HELPER_CONFIG']).read_bytes()))
if args == ('systemctl','stop',op.AGENT,self.unit.name):
self.live.clear()
elif args == ('systemctl','start',self.unit.name,op.AGENT):
self.restart_count += 1
path = self.unit.read_text().split('ExecStart=')[1].splitlines()[0]
self.live.update({self.unit.name:Path(path),op.AGENT:self.new/'agent'})
elif args != ('systemctl','daemon-reload'):
raise AssertionError(args)
return b''
def test_interrupted_switch_resume_and_exact_rollback(self):
report = op.device(self.args,False)
self.assertEqual(self.before,[p.read_bytes() for p in [self.settings,self.proof,self.unit]])
original = op.replace
def interrupt(path,data):
if path == self.proof:
raise RuntimeError('interrupted')
original(path,data)
with patch.object(op,'replace',interrupt), self.assertRaisesRegex(RuntimeError,'interrupted'):
op.device(self.args,True)
self.assertEqual(report,op.device(self.args,True))
self.assertEqual(report,op.device(self.args,True))
self.assertEqual(1,self.restart_count)
self.args.action='rollback'
op.device(self.args,True)
self.assertEqual(self.before,[p.read_bytes() for p in [self.settings,self.proof,self.unit]])
self.assertEqual(self.live[op.AGENT],self.new/'agent')
def test_mismatched_proof_or_unit_rejected_before_service_changes(self):
self.proof.write_text('{}')
with self.assertRaisesRegex(ValueError,'proof'):
op.device(self.args,True)
self.proof.write_bytes(self.before[1])
self.unit.write_text('ExecStart=/unrelated/helper\n')
with self.assertRaisesRegex(ValueError,'effective'):
op.device(self.args,True)
self.assertEqual(self.restart_count,0)
def test_only_two_existing_scope_pins_change(self):
receipt=op.device(self.args,False)
scope={**self.binding, 'principals':['existing-operator'], 'allow_reboot':False,
**dict(zip(op.PINS,receipt['previous']))}
policy={'schema_version':1,'linux':[scope],'windows':[{'agent_id':'other'}]}
before=copy.deepcopy(policy)
op.existing_scope(policy,receipt).update(zip(op.PINS,receipt['current']))
changed={k for k in scope if scope[k]!=before['linux'][0][k]}
self.assertEqual(changed,set(op.PINS))
self.assertEqual(policy['windows'],before['windows'])
for bad in [dict(receipt,binding=dict(receipt['binding'],asset_id='other')),
dict(receipt,current=['foreign','foreign'])]:
with self.assertRaises(ValueError):
op.existing_scope(policy,bad)
if __name__ == '__main__':
unittest.main()