#!/usr/bin/env python3 """Read-only legacy readiness gate, or explicit bounded systemd Hello-World run. Without arguments this checks the original passive installation read-only. After the separately authorized migration, --run-service-hello starts the installed non-root service and owned tunnel, submits a fixed MCP request and uses actual dev/test browser clicks. It never approves via API/DB, runs the network agent as root, or creates/resets a device identity. """ import json import os from pathlib import Path import subprocess import tempfile import vm_access_check as access from vm_passive_test import execute, remote_python, require ROOT = access.ROOT def readiness(facts): blockers = [] if not facts['identity_present']: blockers.append('preserved_device_identity_missing') if facts['ssh_uid'] == 0: blockers.append('root_ssh_requires_existing_unprivileged_account_deployment') if not facts['dedicated_account_present']: blockers.append('no_existing_dedicated_unprivileged_test_account') if facts['state_owner_uid'] == 0: blockers.append('preserved_state_root_owned_requires_controlled_account_migration') if facts['agent_count'] or facts['port_occupied']: blockers.append('existing_agent_or_tunnel_requires_lifecycle_review') # Even a successful readiness check is not deployment or sync acceptance. return blockers def private_report(value): directory = ROOT / 'devstate/vm-jobs' directory.mkdir(mode=0o700, exist_ok=True) require(not directory.is_symlink() and directory.stat().st_uid == os.getuid() and directory.stat().st_mode & 0o777 == 0o700, 'unsafe report directory') path = directory / 'preflight.json' flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW fd = os.open(path, flags, 0o600) with os.fdopen(fd, 'w') as stream: os.fchmod(stream.fileno(), 0o600) json.dump(value, stream, indent=2) def main(): os.umask(0o077) config = access.load_config(ROOT / 'credentials/linux-vm.conf') prior = json.loads((ROOT / 'devstate/vm-passive/result.json').read_text()) require(prior.get('agent_stopped') and prior.get('tunnel_stopped'), 'previous passive lifecycle not confirmed stopped') directory = prior['remote_directory'] require(isinstance(directory, str) and directory.startswith('/') and '\n' not in directory, 'invalid preserved state path') known = Path.home() / '.ssh/known_hosts' address, port = config['address'], config.get('port', '22') lookup = address if port == '22' else f'[{address}]:{port}' execute(['ssh-keygen', '-F', lookup, '-f', str(known)]) with tempfile.TemporaryDirectory(prefix='rmm-job-', dir=ROOT / 'credentials') as folder: folder = Path(folder) password = folder / 'password' password.write_text(config.get('password', '') + '\n') password.chmod(0o600) askpass = folder / 'askpass' askpass.write_text('#!/bin/sh\nexec cat "$RMM_SSH_PASSWORD_FILE"\n') askpass.chmod(0o700) env = dict(os.environ, SSH_ASKPASS=str(askpass), SSH_ASKPASS_REQUIRE='force', DISPLAY='rmm-test:0', RMM_SSH_PASSWORD_FILE=str(password)) ssh = ['ssh', '-F', '/dev/null', '-T', '-p', port, '-o', 'StrictHostKeyChecking=yes', '-o', f'UserKnownHostsFile={known}', '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes', '-o', 'ConnectTimeout=10', '-o', 'ConnectionAttempts=1', '-o', 'NumberOfPasswordPrompts=1', '-o', 'LogLevel=ERROR'] if config.get('ssh_key_path'): ssh += ['-i', str(Path(config['ssh_key_path']).expanduser()), '-o', 'IdentitiesOnly=yes'] # Only presence/ownership/process facts leave the VM. Never read a key, # identity payload, log, process command line, or credential into output. code = '''import glob,json,os,pwd,subprocess from pathlib import Path p=Path(%r) agents=0 for f in glob.glob('/proc/[0-9]*/exe'): try: if os.path.basename(os.readlink(f))=='rmm-agent': agents+=1 except OSError: pass ports=subprocess.run(['ss','-H','-ltn'],capture_output=True,text=True,check=True).stdout print(json.dumps(dict(ssh_uid=os.geteuid(),identity_present=(p/'state/identity.json').is_file(), state_owner_uid=p.stat().st_uid,dedicated_account_present=any(x.pw_uid>0 and x.pw_name in ('rmm-agent','rmm-test') for x in pwd.getpwall()),agent_count=agents, port_occupied=any(x.split()[3].rsplit(':',1)[-1]=='18443' for x in ports.splitlines())))) ''' % directory facts = json.loads(remote_python(ssh, config['username'] + '@' + address, env, code)) blockers = readiness(facts) report = dict(facts=facts, blockers=blockers, deployment_performed=False, ui_approval_performed=False, jobs_executed=False, identity_or_journal_modified=False) private_report(report) print('VM_JOB_PREFLIGHT=' + ('blocked' if blockers else 'ready_for_controlled_deployment')) for blocker in blockers: print('BLOCKED:', blocker) print('No agent/tunnel started; no plan, approval, job, account or state change.') return 2 if blockers else 0 if __name__ == '__main__': import sys if sys.argv[1:] == ['--run-service-hello']: from vm_job_live import run try: run() except Exception as error: from vm_job_bootstrap import sanitized_error print('VM_JOB_CHECK_INCOMPLETE=' + json.dumps(sanitized_error(error))) raise SystemExit(2) from None raise SystemExit(0) try: raise SystemExit(main()) except (RuntimeError, ValueError, OSError, KeyError, subprocess.TimeoutExpired): print('BLOCKED: VM readiness check incomplete; private diagnostics withheld') raise SystemExit(2) from None