feat: deploy cloud-only RMM and verify audited APT diagnostics
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -212,6 +212,29 @@ class PreconditionsTests(unittest.TestCase):
|
||||
with self.assertRaises(apt.Veto):
|
||||
apt.inspect_sandbox()
|
||||
|
||||
def test_private_control_layouts_must_be_empty_or_absent_in_worker(self):
|
||||
for layout in ('etc-rmm', 'etc-rmm-remote', 'rmm-helper', 'rmm-agent', 'rmm-agent-remote'):
|
||||
with self.subTest(layout=layout), tempfile.TemporaryDirectory() as temp:
|
||||
path = Path(temp) / layout
|
||||
with patch.object(apt, 'PRIVATE_CONTROL_DIRECTORIES', (str(path),)):
|
||||
apt.inspect_private_control_paths() # optional layout absent
|
||||
path.mkdir()
|
||||
apt.inspect_private_control_paths() # masked empty directory
|
||||
(path / 'arbitrary-future-secret-name').write_text('synthetic')
|
||||
with self.assertRaisesRegex(apt.Veto, 'SANDBOX_LEDGER_OR_KEYS_VISIBLE'):
|
||||
apt.inspect_private_control_paths()
|
||||
|
||||
def test_private_control_symlink_cannot_claim_an_empty_mask(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
base = Path(temp); (base / 'empty').mkdir()
|
||||
(base / 'link').symlink_to(base / 'empty', target_is_directory=True)
|
||||
with patch.object(apt, 'PRIVATE_CONTROL_DIRECTORIES', (str(base / 'link'),)):
|
||||
with self.assertRaisesRegex(apt.Veto, 'SANDBOX_LEDGER_OR_KEYS_VISIBLE'):
|
||||
apt.inspect_private_control_paths()
|
||||
(base / 'empty').rmdir() # dangling symlink is not an absent layout
|
||||
with self.assertRaisesRegex(apt.Veto, 'SANDBOX_LEDGER_OR_KEYS_VISIBLE'):
|
||||
apt.inspect_private_control_paths()
|
||||
|
||||
def test_previous_launch_or_handoff_is_unknown_never_relaunched(self):
|
||||
for marker in ('launch.json', 'hook-armed.json'):
|
||||
with tempfile.TemporaryDirectory(dir='/tmp/opencode') as temp:
|
||||
|
||||
@@ -170,6 +170,13 @@ print('CLONE_GAPS_CLOSED')
|
||||
|
||||
def test_dedicated_unit_has_narrow_profile_without_weakening_general_unit(self):
|
||||
unit = (ROOT / 'deploy/linux/rmm-apt-helper.service').read_text()
|
||||
# Explicit User=root triggers systemd 255's seccomp/setuid path:
|
||||
# CAP_SETUID disappears from E/P and setup capabilities leak into I.
|
||||
# Default root preserves the exact controller profile, not extra caps.
|
||||
self.assertFalse(any(line.startswith('User=') for line in unit.splitlines()))
|
||||
self.assertIn('Group=rmm-agent', unit)
|
||||
self.assertIn('SystemCallFilter=adjtimex clock_adjtime', unit)
|
||||
self.assertNotIn('CAP_SYS_TIME', next(line for line in unit.splitlines() if line.startswith('CapabilityBoundingSet=')))
|
||||
for required in ('NoNewPrivileges=true', 'PrivateNetwork=true', 'ProtectSystem=strict',
|
||||
'RestrictNamespaces=mnt pid net', 'DevicePolicy=strict', 'PrivateDevices=no',
|
||||
'AmbientCapabilities=', 'SystemCallArchitectures=native'):
|
||||
|
||||
@@ -41,7 +41,7 @@ test('simulated human prepares root request through UI only, without approving',
|
||||
const variants = params.variants;
|
||||
if (!Array.isArray(variants) || variants.length !== 1) throw new Error('One exact script variant required');
|
||||
const variant = object(variants[0]);
|
||||
await page.getByLabel('Interpreter', { exact: true }).selectOption(text(variant.interpreter));
|
||||
await page.getByRole('combobox', { name: 'Interpreter', exact: true }).selectOption(text(variant.interpreter));
|
||||
await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill(text(variant.script_utf8));
|
||||
await page.getByLabel('Erwartete stdout-Ausgabe', { exact: false }).fill(text(params.expected_stdout));
|
||||
} else {
|
||||
@@ -130,7 +130,7 @@ test('one opted-in immutable dev/test action: inspect all fixed bytes → UI cli
|
||||
expect(payload.execution_identity).toBe('root');
|
||||
expect(action.action).toBe('run_script'); expect(action.interpreter).toBe('posix_sh');
|
||||
expect(action.arguments).toEqual([]); expect(action.expected_stdout).toBe('RMM test unit prepared\n');
|
||||
expect(createHash('sha256').update(text(action.script_utf8)).digest('hex')).toBe('159ff240504b8a350b46a56fdf9cd50e5768816de7e6683829f05144978449f0');
|
||||
expect(createHash('sha256').update(text(action.script_utf8)).digest('hex')).toBe('3e299e84021beaa4cbdce6fa63eda193f6f123aba86368890fe20684c43e78ae');
|
||||
expect(payload.max_runtime_seconds).toBe(60);
|
||||
} else if (expected.case === 'refresh_inventory') {
|
||||
expect(payload.execution_identity).toBe('agent_service');
|
||||
|
||||
@@ -6,7 +6,16 @@ import { diagnostic } from './diagnostics';
|
||||
export default class SafeReporter implements Reporter {
|
||||
private executed = 0;
|
||||
onBegin() { console.log('Dev/test browser simulation suite. Secret-bearing step/error logs suppressed.'); }
|
||||
onTestEnd(_test: TestCase, result: TestResult) { if (result.status !== 'skipped') this.executed++; console.log(`Browser simulation: ${result.status}.`); }
|
||||
onTestEnd(_test: TestCase, result: TestResult) {
|
||||
if (result.status !== 'skipped') this.executed++;
|
||||
console.log(`Browser simulation: ${result.status}.`);
|
||||
// Extract only repository source line numbers. Assertion text, call logs
|
||||
// and entered form values (including passwords) remain suppressed.
|
||||
for (const error of result.errors) {
|
||||
const match = error.stack?.match(/mvp-actions\.spec\.ts:(\d+):\d+/);
|
||||
if (match) console.log(`Cloud/root UI failure source_line=${Number(match[1])}`);
|
||||
}
|
||||
}
|
||||
onStepEnd(_test: TestCase, _result: TestResult, step: TestStep) {
|
||||
if (step.category !== 'test.step') return;
|
||||
const safe = diagnostic(step.title, step.error, step.location?.line);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Cloud acceptance regressions: no network, client, approval or database."""
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'deploy'))
|
||||
import cloud_mvp_acceptance as cloud
|
||||
import cloud_root_acceptance as root_acceptance
|
||||
|
||||
|
||||
class CloudGuards(unittest.TestCase):
|
||||
def test_native_chrono_nanoseconds_are_read_without_repeating_the_job(self):
|
||||
value='2026-11-13T10:21:39.987858213Z'
|
||||
self.assertEqual(cloud.contract.timestamp(value),cloud.contract.timestamp('2026-11-13T10:21:39.987858Z'))
|
||||
self.assertEqual(value,'2026-11-13T10:21:39.987858213Z')
|
||||
for fraction in ('1','12','123','1234','12345','123456','123456789'):
|
||||
self.assertEqual(cloud.contract.timestamp('2026-11-13T10:21:39.'+fraction+'Z').microsecond,
|
||||
int((fraction+'000000')[:6]))
|
||||
with self.assertRaises(cloud.contract.GuardError):cloud.contract.timestamp('2026-11-13T10:21:39.987858')
|
||||
|
||||
def test_sse_empty_initial_data_is_not_a_json_response(self):
|
||||
class Response:
|
||||
status=200
|
||||
def __init__(self):self.stream=io.BytesIO(b'event: message\ndata: \n\nevent: message\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n')
|
||||
def getheaders(self):return [('Content-Type','text/event-stream')]
|
||||
def getheader(self,key,default=''):return 'text/event-stream'
|
||||
def readline(self,size):return self.stream.readline(size)
|
||||
class Connection:
|
||||
def __init__(self,*args,**kwargs):pass
|
||||
def request(self,*args,**kwargs):pass
|
||||
def getresponse(self):return Response()
|
||||
def close(self):pass
|
||||
with patch.object(cloud.http.client,'HTTPSConnection',Connection), \
|
||||
patch.object(cloud.ssl,'create_default_context'), \
|
||||
patch.object(Path,'read_text',return_value='synthetic-test-bearer'):
|
||||
response=cloud.server(dict(kind='http',path='/mcp',method='POST',body={},headers={}))
|
||||
self.assertTrue(response['data']['result']['ok'])
|
||||
|
||||
def test_cloud_adapter_cannot_target_an_approval_or_enrollment_endpoint(self):
|
||||
for path in ('/agent/v1/enroll','/api/v1/tenants/t/operation-plans/p/authorizations','/auth/dev/login'):
|
||||
with self.subTest(path=path),self.assertRaisesRegex(RuntimeError,'no administrative mutation endpoint'):
|
||||
cloud.server(dict(kind='http',path=path))
|
||||
|
||||
def test_caller_cannot_inject_interactive_or_bearer_credentials(self):
|
||||
for key in ('Cookie','authorization','X-CSRF-Token'):
|
||||
with patch.object(cloud.ssl,'create_default_context'),self.subTest(key=key), \
|
||||
self.assertRaisesRegex(RuntimeError,'caller credential injection'):
|
||||
cloud.server(dict(kind='http',path='/mcp',headers={key:'synthetic'},body={},method='POST'))
|
||||
|
||||
def test_browser_authorization_uses_only_the_actual_ui(self):
|
||||
code=(cloud.ROOT/'deploy/browser/cloud_approve.cjs').read_text()
|
||||
self.assertNotIn('page.request.',code)
|
||||
self.assertNotIn('page.evaluate(',code)
|
||||
self.assertNotIn(".post('/",code)
|
||||
self.assertIn('await approve.click()',code)
|
||||
self.assertIn('ignoreHTTPSErrors: false',code)
|
||||
|
||||
def test_cloud_root_runner_refuses_reboot_before_starting_a_browser(self):
|
||||
value=dict(profile='dev/test',case='reboot_last',expected_principal='simulated-testprincipal-a')
|
||||
with patch.object(cloud.contract,'protected_json',return_value=value), \
|
||||
patch.object(cloud,'prepare_browser') as trust, \
|
||||
patch.object(root_acceptance.browser.subprocess,'run') as run:
|
||||
with self.assertRaisesRegex(RuntimeError,'fixed cloud root cases only'):
|
||||
root_acceptance.browser.run('/synthetic/case.json')
|
||||
trust.assert_not_called();run.assert_not_called()
|
||||
|
||||
def test_root_preparation_requires_explicit_root_identity(self):
|
||||
value=dict(profile='dev/test',case='service_start',phase='prepare',expected_principal='simulated-testprincipal-a',
|
||||
request=dict(parameters=dict(execution_identity='agent_service')))
|
||||
with patch.object(cloud.contract,'protected_json',return_value=value), \
|
||||
patch.object(cloud,'prepare_browser') as trust:
|
||||
with self.assertRaisesRegex(RuntimeError,'root preparation only'):
|
||||
root_acceptance.browser.run('/synthetic/case.json',prepare=True)
|
||||
trust.assert_not_called()
|
||||
|
||||
def test_unresolved_cloud_effect_blocks_every_new_root_request(self):
|
||||
identity=dict(agent_id='synthetic-agent',asset_id='synthetic-asset')
|
||||
with patch.object(sys,'argv',['cloud_root_acceptance.py','--case','apt_native_install']), \
|
||||
patch.object(Path,'exists',return_value=False), \
|
||||
patch.object(cloud.contract,'protected_json',return_value=dict(identity=identity)), \
|
||||
patch.object(cloud,'Backend') as backend, \
|
||||
patch.object(cloud.bootstrap,'rpc',return_value=dict(unresolved=1)), \
|
||||
patch.object(root_acceptance.browser,'run') as browser:
|
||||
with self.assertRaisesRegex(cloud.contract.GuardError,'unresolved central job'):
|
||||
root_acceptance.main()
|
||||
backend.return_value.call.assert_not_called();browser.assert_not_called()
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Bootstrap guard regressions; no SSH, system service or actual chown."""
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'deploy'))
|
||||
import remote_client_bootstrap as bootstrap
|
||||
|
||||
|
||||
class InstallationGuards(unittest.TestCase):
|
||||
def staged_install(self, existing=False):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
def mapped(path):
|
||||
return root/str(path).lstrip('/')
|
||||
for name in ('usr/local/libexec', 'etc/systemd/system', 'var/lib'):
|
||||
(root/name).mkdir(parents=True, exist_ok=True)
|
||||
state = root/'var/lib/rmm-agent-remote'
|
||||
if existing:
|
||||
state.mkdir(mode=0o700)
|
||||
(state/'identity.json').write_bytes(b'preserved identity')
|
||||
binary = b'\x7fELF\x02\x01'+b'\x00'*12+b'\x3e\x00'+b'\x00'*64
|
||||
payload = dict(action='install', binary=base64.b64encode(binary).decode(),
|
||||
binary_sha256=hashlib.sha256(binary).hexdigest(), token='x'*64,
|
||||
ca=base64.b64encode(b'public CA').decode(), unit='reviewed fixture unit',
|
||||
environment='reviewed fixture environment')
|
||||
original = os.umask(0o077)
|
||||
try:
|
||||
with patch.object(bootstrap, 'Path', side_effect=mapped), \
|
||||
patch.object(bootstrap.os, 'geteuid', return_value=0), \
|
||||
patch('pwd.getpwnam', return_value=SimpleNamespace(pw_uid=993, pw_gid=984)), \
|
||||
patch.object(bootstrap.os, 'chown'), \
|
||||
patch.object(bootstrap.subprocess, 'run', return_value=SimpleNamespace(stdout=b'inactive\n')) as run:
|
||||
if existing:
|
||||
with self.assertRaisesRegex(RuntimeError, 'existing installation'):
|
||||
bootstrap.vm(payload)
|
||||
self.assertEqual((state/'identity.json').read_bytes(), b'preserved identity')
|
||||
self.assertFalse((root/'usr/local/libexec/rmm-agent-remote').exists())
|
||||
return
|
||||
result = bootstrap.vm(payload)
|
||||
self.assertTrue(result['installed'])
|
||||
self.assertEqual((root/'usr/local/libexec/rmm-agent-remote').stat().st_mode & 0o777, 0o755)
|
||||
self.assertEqual((root/'etc/rmm-remote').stat().st_mode & 0o777, 0o755)
|
||||
self.assertEqual((root/'etc/rmm-remote/ca.pem').stat().st_mode & 0o777, 0o644)
|
||||
self.assertEqual((root/'etc/rmm-remote/agent.env').stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual((state/'enroll.token').stat().st_mode & 0o777, 0o600)
|
||||
for call in run.call_args_list:
|
||||
self.assertNotIn('start', call.args[0])
|
||||
finally:
|
||||
os.umask(original)
|
||||
|
||||
def test_private_umask_does_not_prevent_unprivileged_execution_or_public_ca_read(self):
|
||||
self.staged_install()
|
||||
|
||||
def test_existing_identity_is_preserved_and_never_reenrolled(self):
|
||||
self.staged_install(existing=True)
|
||||
|
||||
def test_notebook_installation_option_is_rejected_before_any_remote_action(self):
|
||||
result = subprocess.run([sys.executable, str(Path(bootstrap.__file__)), '--provision-local'],
|
||||
capture_output=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertFalse(hasattr(bootstrap, 'local'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -73,7 +73,13 @@ class Guards(unittest.TestCase):
|
||||
setup=m.case_input('service_setup',self.settings())['parameters']
|
||||
self.assertEqual(setup['execution_identity'],'root')
|
||||
self.assertEqual(hashlib.sha256(setup['variants'][0]['script_utf8'].encode()).hexdigest(),
|
||||
'159ff240504b8a350b46a56fdf9cd50e5768816de7e6683829f05144978449f0')
|
||||
'3e299e84021beaa4cbdce6fa63eda193f6f123aba86368890fe20684c43e78ae')
|
||||
# The browser independently pins the reviewed bytes at the UI boundary.
|
||||
# Check that pin locally as well; do not wait for a live approval run to
|
||||
# discover drift between the two acceptance paths.
|
||||
browser=(m.ROOT/'tests/browser/mvp-actions.spec.ts').read_text()
|
||||
self.assertIn("update(text(action.script_utf8)).digest('hex')).toBe('" +
|
||||
hashlib.sha256(setup['variants'][0]['script_utf8'].encode()).hexdigest() + "')", browser)
|
||||
artifact=dict(self.artifact(),approved_cases=['service_setup','service_start','service_stop'])
|
||||
m.validate_run_artifact(artifact,self.settings(),['service_setup','service_start','service_stop'])
|
||||
with self.assertRaises(m.GuardError):m.validate_run_artifact(artifact,self.settings(),['service_start','service_setup','service_stop'])
|
||||
|
||||
Reference in New Issue
Block a user