test_onboarding_install.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. """Exercise self-hosted installer preservation, integrity and recovery invariants."""
  2. import hashlib
  3. import importlib.util
  4. import json
  5. import os
  6. from pathlib import Path
  7. import tempfile
  8. import threading
  9. import time
  10. import unittest
  11. from concurrent.futures import ThreadPoolExecutor
  12. from unittest.mock import patch
  13. from types import SimpleNamespace
  14. import yaml
  15. ROOT = Path(__file__).resolve().parents[2]
  16. spec = importlib.util.spec_from_file_location('onboarding_install', ROOT / 'cloud/onboarding/install.py')
  17. installer = importlib.util.module_from_spec(spec)
  18. spec.loader.exec_module(installer)
  19. class OnboardingInstallTests(unittest.TestCase):
  20. def setUp(self):
  21. self.temp = tempfile.TemporaryDirectory()
  22. self.addCleanup(self.temp.cleanup)
  23. self.root = Path(self.temp.name)
  24. self.home = self.root / 'data'
  25. self.package = self.root / 'package'
  26. self.home.mkdir()
  27. source = self.package / 'payload/plugins/fixture/__init__.py'
  28. source.parent.mkdir(parents=True)
  29. source.write_text('# bridge fixture\n')
  30. manifest = {'version': 'fixture', 'files': {'plugins/fixture/__init__.py': hashlib.sha256(source.read_bytes()).hexdigest()},
  31. 'config': {'plugins': ['fixture'], 'hooks': {'post_tool_call': [{'command': 'bridge fixture', 'timeout': 20}]}}}
  32. (self.package / 'manifest.json').write_text(json.dumps(manifest))
  33. self.original = {'_config_version': 45, 'model': {'provider': 'custom', 'api_key': 'user-model-key'}, 'terminal': {'backend': 'ssh'},
  34. 'plugins': {'enabled': ['my-plugin']}, 'hooks': {'post_tool_call': [{'command': 'my-hook'}]},
  35. 'sessions': {'auto_archive': True}}
  36. (self.home / 'config.yaml').write_text(yaml.safe_dump(self.original))
  37. (self.home / '.env').write_text('MY_SETTING=preserved\n')
  38. (self.home / 'state.db').write_bytes(b'user-history')
  39. self.env = {key: 'fixture' for key in installer.ENV_KEYS}
  40. self.env['AGENT_ID'] = 'agent-node-app-fixture'
  41. def apply(self):
  42. return installer.install(self.package, self.home, self.env)
  43. def test_model_history_user_plugins_and_hooks_preserved(self):
  44. self.apply()
  45. actual = yaml.safe_load((self.home / 'config.yaml').read_text())
  46. for key in ['model', 'terminal', 'sessions']:
  47. self.assertEqual(actual[key], self.original[key])
  48. self.assertEqual(actual['plugins']['enabled'], ['my-plugin', 'fixture'])
  49. self.assertEqual(actual['hooks']['post_tool_call'][0], {'command': 'my-hook'})
  50. self.assertEqual((self.home / 'state.db').read_bytes(), b'user-history')
  51. self.assertIn('MY_SETTING=preserved', (self.home / '.env').read_text())
  52. def test_second_install_is_idempotent_without_duplicate_hooks(self):
  53. self.apply()
  54. self.assertEqual(self.apply()['changed'], [])
  55. def test_other_agent_identity_rejected_before_writes(self):
  56. (self.home / '.env').write_text('AGENT_ID=somebody-else\n')
  57. with self.assertRaisesRegex(ValueError, '其他容器身份'):
  58. self.apply()
  59. self.assertFalse((self.home / 'plugins').exists())
  60. def test_missing_model_is_explicit_and_preserves_directory(self):
  61. (self.home / 'config.yaml').write_text('model:\n provider: auto\n')
  62. with self.assertRaisesRegex(ValueError, '配置可用模型'):
  63. self.apply()
  64. self.assertFalse((self.home / 'plugins').exists())
  65. def test_corrupt_payload_rejected_before_writes(self):
  66. (self.package / 'payload/plugins/fixture/__init__.py').write_text('corrupted')
  67. with self.assertRaisesRegex(ValueError, '摘要不匹配'):
  68. self.apply()
  69. self.assertFalse((self.home / 'plugins').exists())
  70. def test_old_config_schema_rejected_before_writes(self):
  71. config = dict(self.original)
  72. config.pop('_config_version')
  73. (self.home / 'config.yaml').write_text(yaml.safe_dump(config))
  74. with self.assertRaisesRegex(ValueError, '配置版本'):
  75. self.apply()
  76. self.assertFalse((self.home / 'plugins').exists())
  77. def test_scoped_hook_approval_preserves_user_approval_and_global_policy(self):
  78. approved = {'event': 'pre_tool_call', 'command': 'my-existing-hook', 'approved_at': 'preserve'}
  79. (self.home / 'shell-hooks-allowlist.json').write_text(json.dumps({'approvals': [approved]}))
  80. self.apply()
  81. actual = json.loads((self.home / 'shell-hooks-allowlist.json').read_text())
  82. self.assertEqual(actual['approvals'][0], approved)
  83. self.assertEqual(actual['approvals'][1]['command'], 'bridge fixture')
  84. self.assertNotIn('hooks_auto_accept', yaml.safe_load((self.home / 'config.yaml').read_text()))
  85. def test_parent_traversal_rejected(self):
  86. with self.assertRaises(ValueError):
  87. installer.checked_path(self.home, '../outside')
  88. def test_modified_bridge_file_backed_up(self):
  89. self.apply()
  90. target = self.home / 'plugins/fixture/__init__.py'
  91. target.write_text('previous custom bridge')
  92. result = self.apply()
  93. self.assertEqual((Path(result['backup']) / 'plugins/fixture/__init__.py').read_text(), 'previous custom bridge')
  94. def test_concurrent_different_identities_cannot_both_install(self):
  95. barrier = threading.Barrier(2)
  96. original_read = installer.read_env
  97. def slow_read(path):
  98. result = original_read(path)
  99. time.sleep(0.15)
  100. return result
  101. def worker(identity):
  102. barrier.wait()
  103. environment = dict(self.env, AGENT_ID=identity)
  104. try:
  105. installer.install(self.package, self.home, environment)
  106. return 'installed'
  107. except ValueError as error:
  108. self.assertIn('其他容器身份', str(error))
  109. return 'rejected'
  110. with patch.object(installer, 'read_env', side_effect=slow_read):
  111. with ThreadPoolExecutor(max_workers=2) as pool:
  112. results = list(pool.map(worker, ['agent-node-app-A', 'agent-node-app-B']))
  113. self.assertCountEqual(results, ['installed', 'rejected'])
  114. def test_failed_install_releases_directory_lock(self):
  115. bad = dict(self.env, MATRIX_PASSWORD='')
  116. with self.assertRaises(ValueError):
  117. installer.install(self.package, self.home, bad)
  118. self.assertIn('agentId', self.apply())
  119. @unittest.skipIf(os.name == 'nt', 'requires supported Hermes runtime')
  120. def test_native_Hermes_loads_only_explicitly_approved_bridge_hook(self):
  121. from agent import shell_hooks
  122. self.apply()
  123. manager = SimpleNamespace(_hooks={})
  124. config = yaml.safe_load((self.home / 'config.yaml').read_text())
  125. with patch.object(shell_hooks, 'get_hermes_home', return_value=self.home), \
  126. patch('hermes_cli.plugins.get_plugin_manager', return_value=manager):
  127. registered = shell_hooks.register_from_config(config)
  128. self.assertEqual([spec.command for spec in registered], ['bridge fixture'])
  129. self.assertEqual(len(manager._hooks['post_tool_call']), 1)
  130. @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'requires real Linux UID ownership')
  131. def test_runtime_parents_are_writable_by_hermes_uid(self):
  132. self.apply()
  133. for relative in ['cache', 'sessions', 'work', 'work/uploads', 'work/deliverables']:
  134. self.assertEqual((self.home / relative).stat().st_uid, 10000)
  135. if __name__ == '__main__':
  136. unittest.main()