| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- """Exercise self-hosted installer preservation, integrity and recovery invariants."""
- import hashlib
- import importlib.util
- import json
- import os
- from pathlib import Path
- import tempfile
- import threading
- import time
- import unittest
- from concurrent.futures import ThreadPoolExecutor
- from unittest.mock import patch
- from types import SimpleNamespace
- import yaml
- ROOT = Path(__file__).resolve().parents[2]
- spec = importlib.util.spec_from_file_location('onboarding_install', ROOT / 'cloud/onboarding/install.py')
- installer = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(installer)
- class OnboardingInstallTests(unittest.TestCase):
- def setUp(self):
- self.temp = tempfile.TemporaryDirectory()
- self.addCleanup(self.temp.cleanup)
- self.root = Path(self.temp.name)
- self.home = self.root / 'data'
- self.package = self.root / 'package'
- self.home.mkdir()
- source = self.package / 'payload/plugins/fixture/__init__.py'
- source.parent.mkdir(parents=True)
- source.write_text('# bridge fixture\n')
- manifest = {'version': 'fixture', 'files': {'plugins/fixture/__init__.py': hashlib.sha256(source.read_bytes()).hexdigest()},
- 'config': {'plugins': ['fixture'], 'hooks': {'post_tool_call': [{'command': 'bridge fixture', 'timeout': 20}]}}}
- (self.package / 'manifest.json').write_text(json.dumps(manifest))
- self.original = {'_config_version': 45, 'model': {'provider': 'custom', 'api_key': 'user-model-key'}, 'terminal': {'backend': 'ssh'},
- 'plugins': {'enabled': ['my-plugin']}, 'hooks': {'post_tool_call': [{'command': 'my-hook'}]},
- 'sessions': {'auto_archive': True}}
- (self.home / 'config.yaml').write_text(yaml.safe_dump(self.original))
- (self.home / '.env').write_text('MY_SETTING=preserved\n')
- (self.home / 'state.db').write_bytes(b'user-history')
- self.env = {key: 'fixture' for key in installer.ENV_KEYS}
- self.env['AGENT_ID'] = 'agent-node-app-fixture'
- def apply(self):
- return installer.install(self.package, self.home, self.env)
- def test_model_history_user_plugins_and_hooks_preserved(self):
- self.apply()
- actual = yaml.safe_load((self.home / 'config.yaml').read_text())
- for key in ['model', 'terminal', 'sessions']:
- self.assertEqual(actual[key], self.original[key])
- self.assertEqual(actual['plugins']['enabled'], ['my-plugin', 'fixture'])
- self.assertEqual(actual['hooks']['post_tool_call'][0], {'command': 'my-hook'})
- self.assertEqual((self.home / 'state.db').read_bytes(), b'user-history')
- self.assertIn('MY_SETTING=preserved', (self.home / '.env').read_text())
- def test_second_install_is_idempotent_without_duplicate_hooks(self):
- self.apply()
- self.assertEqual(self.apply()['changed'], [])
- def test_other_agent_identity_rejected_before_writes(self):
- (self.home / '.env').write_text('AGENT_ID=somebody-else\n')
- with self.assertRaisesRegex(ValueError, '其他容器身份'):
- self.apply()
- self.assertFalse((self.home / 'plugins').exists())
- def test_missing_model_is_explicit_and_preserves_directory(self):
- (self.home / 'config.yaml').write_text('model:\n provider: auto\n')
- with self.assertRaisesRegex(ValueError, '配置可用模型'):
- self.apply()
- self.assertFalse((self.home / 'plugins').exists())
- def test_corrupt_payload_rejected_before_writes(self):
- (self.package / 'payload/plugins/fixture/__init__.py').write_text('corrupted')
- with self.assertRaisesRegex(ValueError, '摘要不匹配'):
- self.apply()
- self.assertFalse((self.home / 'plugins').exists())
- def test_old_config_schema_rejected_before_writes(self):
- config = dict(self.original)
- config.pop('_config_version')
- (self.home / 'config.yaml').write_text(yaml.safe_dump(config))
- with self.assertRaisesRegex(ValueError, '配置版本'):
- self.apply()
- self.assertFalse((self.home / 'plugins').exists())
- def test_scoped_hook_approval_preserves_user_approval_and_global_policy(self):
- approved = {'event': 'pre_tool_call', 'command': 'my-existing-hook', 'approved_at': 'preserve'}
- (self.home / 'shell-hooks-allowlist.json').write_text(json.dumps({'approvals': [approved]}))
- self.apply()
- actual = json.loads((self.home / 'shell-hooks-allowlist.json').read_text())
- self.assertEqual(actual['approvals'][0], approved)
- self.assertEqual(actual['approvals'][1]['command'], 'bridge fixture')
- self.assertNotIn('hooks_auto_accept', yaml.safe_load((self.home / 'config.yaml').read_text()))
- def test_parent_traversal_rejected(self):
- with self.assertRaises(ValueError):
- installer.checked_path(self.home, '../outside')
- def test_modified_bridge_file_backed_up(self):
- self.apply()
- target = self.home / 'plugins/fixture/__init__.py'
- target.write_text('previous custom bridge')
- result = self.apply()
- self.assertEqual((Path(result['backup']) / 'plugins/fixture/__init__.py').read_text(), 'previous custom bridge')
- def test_concurrent_different_identities_cannot_both_install(self):
- barrier = threading.Barrier(2)
- original_read = installer.read_env
- def slow_read(path):
- result = original_read(path)
- time.sleep(0.15)
- return result
- def worker(identity):
- barrier.wait()
- environment = dict(self.env, AGENT_ID=identity)
- try:
- installer.install(self.package, self.home, environment)
- return 'installed'
- except ValueError as error:
- self.assertIn('其他容器身份', str(error))
- return 'rejected'
- with patch.object(installer, 'read_env', side_effect=slow_read):
- with ThreadPoolExecutor(max_workers=2) as pool:
- results = list(pool.map(worker, ['agent-node-app-A', 'agent-node-app-B']))
- self.assertCountEqual(results, ['installed', 'rejected'])
- def test_failed_install_releases_directory_lock(self):
- bad = dict(self.env, MATRIX_PASSWORD='')
- with self.assertRaises(ValueError):
- installer.install(self.package, self.home, bad)
- self.assertIn('agentId', self.apply())
- @unittest.skipIf(os.name == 'nt', 'requires supported Hermes runtime')
- def test_native_Hermes_loads_only_explicitly_approved_bridge_hook(self):
- from agent import shell_hooks
- self.apply()
- manager = SimpleNamespace(_hooks={})
- config = yaml.safe_load((self.home / 'config.yaml').read_text())
- with patch.object(shell_hooks, 'get_hermes_home', return_value=self.home), \
- patch('hermes_cli.plugins.get_plugin_manager', return_value=manager):
- registered = shell_hooks.register_from_config(config)
- self.assertEqual([spec.command for spec in registered], ['bridge fixture'])
- self.assertEqual(len(manager._hooks['post_tool_call']), 1)
- @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'requires real Linux UID ownership')
- def test_runtime_parents_are_writable_by_hermes_uid(self):
- self.apply()
- for relative in ['cache', 'sessions', 'work', 'work/uploads', 'work/deliverables']:
- self.assertEqual((self.home / relative).stat().st_uid, 10000)
- if __name__ == '__main__':
- unittest.main()
|