From 8de43e7c08efe38dca7f9ba2329789ce429c27c7 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 6 Nov 2026 21:52:43 -0600 Subject: [PATCH] Add isolated sandbox host preparation --- jeannie | 16 ++-- scripts/network-sandbox-host.py | 99 ++++++++++++++++++++++ scripts/network-sandbox-prepare.py | 26 ++++++ tests/jeannie/test_network_sandbox_host.py | 28 ++++++ 4 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 scripts/network-sandbox-host.py create mode 100644 scripts/network-sandbox-prepare.py create mode 100644 tests/jeannie/test_network_sandbox_host.py diff --git a/jeannie b/jeannie index c4b68b0..08c30cb 100755 --- a/jeannie +++ b/jeannie @@ -208,7 +208,7 @@ Apps And Services website-translation-model Prepare website translation model support. website-ollama-listen Configure website Ollama access. install-gitea-runner [TOKEN] Install the Gitea Actions runner. - network-sandbox plan Inspect proposed isolated network lab. + network-sandbox {plan|prepare} Inspect or prepare isolated network lab infrastructure. Security Learning security-scan Run the security scan bundle. @@ -790,11 +790,15 @@ case "${1:-}" in ;; network-sandbox) require_debian_server "network-sandbox" - if [[ "${2:-plan}" != "plan" || $# -gt 2 ]]; then - echo "Usage: ./jeannie network-sandbox plan" >&2 - exit 2 - fi - python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" + [[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare}" >&2; exit 2; } + case "${2:-plan}" in + plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;; + prepare) + record_change_journal "network-sandbox" "$@" + python3 "${REPO_ROOT}/scripts/network-sandbox-prepare.py" + ;; + *) echo "Usage: ./jeannie network-sandbox {plan|prepare}" >&2; exit 2 ;; + esac ;; nuke) record_change_journal "nuke" "$@" diff --git a/scripts/network-sandbox-host.py b/scripts/network-sandbox-host.py new file mode 100644 index 0000000..4121c3d --- /dev/null +++ b/scripts/network-sandbox-host.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Prepare only the isolated bridge and storage for the network sandbox. + +This runs on the Orange Pi as root. It deliberately does not create or start +guests, change the cluster guard, or configure the existing host bridges. +""" +import os +import subprocess +import sys +from pathlib import Path + +BRIDGE = 'vmbr9' +ALIAS = 'jeannie-network-sandbox' +STORAGE = 'jeannie-sandbox' +STORAGE_PATH = Path('/data/jeannie/network-sandbox/lxc') +EXPECTED_UUID = '19972338-9757-4f4b-89d7-c202df14a9aa' +MARKER = '.jeannie-network-sandbox-storage' + + +def run(*args): + return subprocess.run(args, check=True, text=True, capture_output=True).stdout.strip() + + +def verify_data(): + uuid = run('findmnt', '-rn', '-M', '/data', '-o', 'UUID') + opts = run('findmnt', '-rn', '-M', '/data', '-o', 'OPTIONS').split(',') + if uuid != EXPECTED_UUID or 'rw' not in opts: + raise RuntimeError('/data is not the expected writable SSD filesystem') + for part in (Path('/data/jeannie'), Path('/data/jeannie/network-sandbox'), STORAGE_PATH): + if part.is_symlink(): + raise RuntimeError(f'Refusing symlink in sandbox storage path: {part}') + + +def verify_bridge(): + base = Path('/sys/class/net') / BRIDGE + if not (base / 'bridge').is_dir(): + raise RuntimeError(f'{BRIDGE} is not a bridge') + if (base / 'ifalias').read_text().strip() != ALIAS: + raise RuntimeError(f'{BRIDGE} is not marked as the Jeannie sandbox bridge') + if (base / 'bridge/vlan_filtering').read_text().strip() != '1': + raise RuntimeError(f'{BRIDGE} is not VLAN aware') + members = sorted(p.name for p in (base / 'brif').iterdir()) + if members: + raise RuntimeError(f'Refusing to reuse nonempty sandbox bridge: {members}') + + +def verify_storage_config(): + config = Path('/etc/pve/storage.cfg').read_text(encoding='utf-8') + blocks = config.split('\n\n') + matching = [b for b in blocks if b.splitlines() and b.splitlines()[0].strip() == f'dir: {STORAGE}'] + if len(matching) != 1: + raise RuntimeError(f'Cannot verify storage {STORAGE}') + values = {} + for line in matching[0].splitlines()[1:]: + fields = line.split(None, 1) + if len(fields) == 2: + values[fields[0]] = fields[1] + if values.get('path') != str(STORAGE_PATH) or 'rootdir' not in values.get('content', '').split(','): + raise RuntimeError(f'Storage {STORAGE} exists with unexpected configuration') + if not (STORAGE_PATH / MARKER).is_file(): + raise RuntimeError('Sandbox storage marker is missing') + + +def main(): + if os.geteuid() != 0 or sys.argv[1:] != ['prepare']: + print('Run as root with the single argument: prepare', file=sys.stderr) + return 2 + try: + verify_data() + bridge_path = Path('/sys/class/net') / BRIDGE + if bridge_path.exists(): + verify_bridge() + else: + run('ip', 'link', 'add', 'name', BRIDGE, 'type', 'bridge', 'vlan_filtering', '1') + run('ip', 'link', 'set', 'dev', BRIDGE, 'alias', ALIAS) + run('ip', 'link', 'set', 'dev', BRIDGE, 'up') + verify_bridge() + + status = run('pvesm', 'status') + exists = any(line.split() and line.split()[0] == STORAGE for line in status.splitlines()) + if exists: + verify_storage_config() + else: + if STORAGE_PATH.exists() and not (STORAGE_PATH / MARKER).is_file(): + raise RuntimeError('Existing sandbox directory is unmarked; refusing to adopt it') + STORAGE_PATH.mkdir(parents=True, exist_ok=True) + (STORAGE_PATH / MARKER).touch(exist_ok=True) + run('pvesm', 'add', 'dir', STORAGE, '--path', str(STORAGE_PATH), '--content', 'rootdir,vztmpl') + verify_storage_config() + print(f'Prepared transient {BRIDGE} and SSD storage {STORAGE}. No guests were created.') + except (OSError, RuntimeError, subprocess.CalledProcessError) as exc: + detail = exc.stderr.strip() if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc) + print(f'Sandbox preparation failed: {detail}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/network-sandbox-prepare.py b/scripts/network-sandbox-prepare.py new file mode 100644 index 0000000..fd5d9f5 --- /dev/null +++ b/scripts/network-sandbox-prepare.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Send the scoped sandbox preparation program to the Orange Pi over SSH.""" +import os +import subprocess +import sys +from pathlib import Path + + +def main(): + root = Path(__file__).resolve().parent + host = os.environ.get('LAB_PIMOX_HOST', '192.168.100.80') + user = os.environ.get('LAB_PIMOX_USER', 'jv') + key = os.environ.get('LAB_PIMOX_SSH_KEY_PATH', '/home/jv/.ssh/id_ed25519') + try: + source = (root / 'network-sandbox-host.py').read_bytes() + return subprocess.run(['ssh', '-T', '-i', key, '-o', 'BatchMode=yes', + '-o', 'IdentitiesOnly=yes', '-o', 'ConnectTimeout=10', + '-o', 'StrictHostKeyChecking=accept-new', f'{user}@{host}', + 'sudo -n python3 - prepare'], input=source, timeout=120).returncode + except (OSError, subprocess.SubprocessError) as exc: + print(f'Sandbox preparation failed: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/jeannie/test_network_sandbox_host.py b/tests/jeannie/test_network_sandbox_host.py new file mode 100644 index 0000000..ac7a6c0 --- /dev/null +++ b/tests/jeannie/test_network_sandbox_host.py @@ -0,0 +1,28 @@ +"""Checks for the host-side storage precondition.""" +import importlib.util +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('sandbox_host', ROOT / 'scripts/network-sandbox-host.py') +host = importlib.util.module_from_spec(spec) +spec.loader.exec_module(host) + + +class SandboxHostTests(unittest.TestCase): + def test_expected_writable_ssd_is_accepted(self): + with patch.object(host, 'run', side_effect=[host.EXPECTED_UUID, 'rw,relatime']), \ + patch.object(Path, 'is_symlink', return_value=False): + host.verify_data() + + def test_wrong_or_readonly_filesystem_is_rejected(self): + for uuid, options in [('other', 'rw,relatime'), (host.EXPECTED_UUID, 'ro,relatime')]: + with self.subTest(uuid=uuid, options=options), \ + patch.object(host, 'run', side_effect=[uuid, options]): + with self.assertRaises(RuntimeError): + host.verify_data() + + +if __name__ == '__main__': + unittest.main()