Add independent network sandbox guests
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-06 22:23:09 -06:00
parent 549f1c1200
commit b1073738f3
12 changed files with 543 additions and 9 deletions

View File

@ -56,6 +56,7 @@ var allowedCommands = map[string]bool{
"deploy-office": true,
"deploy-ai-tools": true, "deploy-omniroute": true, "deploy-hermes": true,
"rpi-services": true, "host-bootstrap": true, "bootstrap-gitea-repo": true, "repo-sync": true, "backup-gitea": true, "hermes-connect": true,
"network-sandbox": true,
"backup": true, "drill-restore": true, "drill-gitea-restore": true,
"drill-pihole-restore": true, "install-gitea-runner": true,
"move-prometheus-stack-workers": true, "doctor-versions": true,

27
docs/network-sandbox.md Normal file
View File

@ -0,0 +1,27 @@
# Isolated network sandbox
`./jeannie network-sandbox plan` reports the intended guest identities and
host prerequisites. `prepare` creates the isolated VLAN-aware `vmbr9` and
SSD-backed `jeannie-sandbox` storage after running the sandbox unit checks.
The bridge is transient and the storage definition persists across reboot.
`./jeannie network-sandbox provision` creates OpenWrt VM 9100 and Alpine ARM64
containers 9110 and 9111 on VLANs 10 and 20. It requires an empty, marked
`vmbr9`, the expected writable SSD, the sandbox storage definition, available
guest IDs, KVM, and an SSH public key. It verifies downloaded images against
checksums retrieved from the official distribution servers. It never adopts or
overwrites existing guest IDs, and preserves partially created resources on
failure for inspection.
**Guests are created stopped and the OpenWrt WAN virtual link is disconnected.**
`network-sandbox start` starts only the dedicated sandbox guests after verifying
their identity, isolation and host routes; `stop` stops only those guests.
These lifecycle commands are independent of K3s. The cluster runtime guard
checks declared control-plane and worker VM IDs and Pimox cluster VM names;
it does not depend on sandbox guests, bridge, storage, or health. Keep custom
cluster guests declared in the inventory or VM ID overrides so that the guard
recognizes them. The WAN stays disconnected; internet access is not yet
implemented because firewall and VLAN isolation require end-to-end validation.
The existing cluster bridge, host addresses, and existing VM disks are not
modified by this workflow. Download and disk-import staging files remain under
`/data/jeannie/network-sandbox` after provisioning.

24
jeannie
View File

@ -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|prepare} Inspect or prepare isolated network lab infrastructure.
network-sandbox {plan|prepare|provision|start|stop} Manage the independent network lab.
Security Learning
security-scan Run the security scan bundle.
@ -790,19 +790,33 @@ case "${1:-}" in
;;
network-sandbox)
require_debian_server "network-sandbox"
[[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare}" >&2; exit 2; }
[[ $# -le 2 ]] || { echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop}" >&2; exit 2; }
case "${2:-plan}" in
plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;;
prepare)
prepare|provision|start)
record_change_journal "network-sandbox" "$@"
echo "Checking sandbox configuration and host preparation logic..."
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
-p 'test_network_sandbox_config.py' || exit 1
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
-p 'test_network_sandbox_host.py' || exit 1
python3 "${REPO_ROOT}/scripts/network-sandbox-prepare.py"
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
-p 'test_network_sandbox_guests.py' || exit 1
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
-p 'test_network_sandbox_guard.py' || exit 1
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
-p 'test_network_sandbox_lifecycle.py' || exit 1
case "${2}" in
prepare) python3 "${REPO_ROOT}/scripts/network-sandbox-prepare.py" ;;
provision) python3 "${REPO_ROOT}/scripts/network-sandbox-guests.py" ;;
start) python3 "${REPO_ROOT}/scripts/network-sandbox-lifecycle.py" start ;;
esac
;;
*) echo "Usage: ./jeannie network-sandbox {plan|prepare}" >&2; exit 2 ;;
stop)
record_change_journal "network-sandbox" "$@"
python3 "${REPO_ROOT}/scripts/network-sandbox-lifecycle.py" stop
;;
*) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop}" >&2; exit 2 ;;
esac
;;
nuke)

View File

@ -53,6 +53,11 @@ fi
return values
def is_competing_cluster_vm(vmid, name, cluster_vmids):
"""Classify declared cluster VMs without depending on unrelated guests."""
return vmid in cluster_vmids or name.startswith(('pimox-cp-', 'pimox-worker-'))
def check(profile=None, vm_start=False):
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
profiles = inventory["cluster"]["profiles"]
@ -79,15 +84,25 @@ def check(profile=None, vm_start=False):
hyper_state = services(hypervisor["lan_ip"], hypervisor["user"], hyper_key)
output = remote(hypervisor["lan_ip"], hypervisor["user"], hyper_key, "sudo -n qm list")
vms = {}
vm_names = {}
for line in output.splitlines():
fields = line.split()
if fields and fields[0].isdigit():
if len(fields) < 3 or fields[2] not in ("running", "stopped", "paused", "suspended"):
raise RuntimeError("Cannot determine Pimox VM state")
vms[int(fields[0])] = fields[2]
vm_names[int(fields[0])] = fields[1]
if not output.strip() or "VMID" not in output:
raise RuntimeError("Cannot verify Pimox VM inventory")
cp_vmid = int(profiles["pimox"]["pimox"]["control_plane_vmid"])
cp_vmid = int(os.environ.get('LAB_PIMOX_CONTROL_PLANE_VMID') or
os.environ.get('LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID') or
profiles["pimox"]["pimox"]["control_plane_vmid"])
pimox = inventory.get('pimox', {})
worker_base = int(os.environ.get('LAB_PIMOX_WORKER_BASE_VMID') or pimox.get('worker_base_vmid', 9010))
worker_count = int(os.environ.get('LAB_PIMOX_WORKER_COUNT') or profiles['pimox']['pimox'].get('worker_count', 0))
if worker_count < 0 or worker_count > 4096:
raise RuntimeError('Invalid Pimox worker count')
cluster_vmids = {cp_vmid} | set(range(worker_base, worker_base + worker_count))
conflicts = []
if laptop_state["k3s"] == "running" or laptop_state["k3s_workloads"] == "running":
conflicts.append("unexpected laptop k3s service is running on " + laptop["lan_ip"])
@ -98,9 +113,14 @@ def check(profile=None, vm_start=False):
conflicts.append("VM startup is incompatible with the selected direct-host k3s profile")
if laptop_state["kubelet"] == "running" or laptop_state["api"] == "running":
conflicts.append("Debian laptop control plane is running")
active_vms = [str(vmid) for vmid, state in vms.items() if state != "stopped"]
active_vms = []
for vmid, state in vms.items():
if state == "stopped":
continue
if is_competing_cluster_vm(vmid, vm_names[vmid], cluster_vmids):
active_vms.append(str(vmid))
if active_vms:
conflicts.append("Pimox VMs are not stopped: " + ", ".join(active_vms))
conflicts.append("Competing Pimox cluster VMs are not stopped: " + ", ".join(active_vms))
else:
if hyper_state["k3s"] == "running" or hyper_state["api"] == "running" or hyper_state["k3s_workloads"] == "running":
conflicts.append("Orange Pi host K3s/control-plane API is running")

View File

@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Provision the isolated sandbox guests in the stopped state on Pimox.
The caller supplies CONFIGS and AUTHORIZED_KEY when streaming this program to
the host. Existing VM/container IDs are never adopted or overwritten.
"""
import gzip
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from pathlib import Path
BASE = Path('/data/jeannie/network-sandbox')
STORAGE = BASE / 'lxc'
OPENWRT = 'openwrt-24.10.6-armsr-armv8-generic-ext4-combined-efi.img.gz'
OPENWRT_URL = 'https://downloads.openwrt.org/releases/24.10.6/targets/armsr/armv8/'
ALPINE = 'alpine-minirootfs-3.22.7-aarch64.tar.gz'
ALPINE_URL = 'https://dl-cdn.alpinelinux.org/alpine/v3.22/releases/aarch64/'
def run(*args, timeout=180):
result = subprocess.run(args, text=True, capture_output=True, timeout=timeout)
if result.returncode:
raise RuntimeError(f'{args[0]} failed: {result.stderr.strip()[-800:]}')
return result.stdout.strip()
def fetch(url, destination):
with urllib.request.urlopen(url, timeout=120) as source, destination.open('wb') as output:
shutil.copyfileobj(source, output)
def verified_download(base, name, checksum_url, directory):
target = directory / name
checksum = directory / (name + '.sha256')
fetch(base + name, target)
fetch(checksum_url, checksum)
match = re.search(r'(?m)^([0-9a-fA-F]{64})\s+[* ]?' + re.escape(name) + r'\s*$', checksum.read_text())
if not match:
raise RuntimeError(f'Official checksum not found for {name}')
digest = hashlib.sha256()
with target.open('rb') as image:
for chunk in iter(lambda: image.read(1024 * 1024), b''):
digest.update(chunk)
if digest.hexdigest() != match.group(1).lower():
raise RuntimeError(f'Checksum mismatch for {name}')
return target
def check_preconditions():
if os.geteuid() != 0:
raise RuntimeError('Host provisioning must run as root')
if run('uname', '-m') != 'aarch64':
raise RuntimeError('Sandbox images require an ARM64 host')
if run('findmnt', '-rn', '-M', '/data', '-o', 'UUID') != '19972338-9757-4f4b-89d7-c202df14a9aa':
raise RuntimeError('/data is not the expected SSD')
if 'rw' not in run('findmnt', '-rn', '-M', '/data', '-o', 'OPTIONS').split(','):
raise RuntimeError('/data is not writable')
for path in (Path('/data/jeannie'), BASE, STORAGE):
if path.is_symlink():
raise RuntimeError(f'Refusing symlink in sandbox storage path: {path}')
if not (STORAGE / '.jeannie-network-sandbox-storage').is_file():
raise RuntimeError('Sandbox storage marker missing; run network-sandbox prepare')
storage_cfg = Path('/etc/pve/storage.cfg').read_text(encoding='utf-8')
blocks = [block for block in storage_cfg.split('\n\n')
if block.splitlines() and block.splitlines()[0].strip() == 'dir: jeannie-sandbox']
if len(blocks) != 1:
raise RuntimeError('Sandbox storage configuration is absent or ambiguous')
values = dict(line.split(None, 1) for line in blocks[0].splitlines()[1:] if len(line.split(None, 1)) == 2)
if values.get('path') != str(STORAGE) or not {'rootdir', 'vztmpl'}.issubset(set(values.get('content', '').split(','))):
raise RuntimeError('Sandbox storage has unexpected path or content types')
bridge = Path('/sys/class/net/vmbr9')
if not (bridge / 'bridge').is_dir() or (bridge / 'ifalias').read_text().strip() != 'jeannie-network-sandbox':
raise RuntimeError('Sandbox bridge is absent or unmarked; run network-sandbox prepare')
if (bridge / 'bridge/vlan_filtering').read_text().strip() != '1' or list((bridge / 'brif').iterdir()):
raise RuntimeError('Sandbox bridge must be VLAN aware and empty before provisioning')
if not Path('/dev/kvm').exists():
raise RuntimeError('/dev/kvm is unavailable')
ids = {str(entry.get('vmid')) for entry in json.loads(run('pvesh', 'get', '/cluster/resources', '--type', 'vm', '--output-format', 'json'))}
occupied = ids.intersection({'9100', '9110', '9111'})
if occupied:
raise RuntimeError('Guest IDs already in use; refusing to adopt or replace: ' + ', '.join(sorted(occupied)))
image_stores = run('pvesm', 'status', '--content', 'images')
if not any(line.split() and line.split()[0] == 'opi5_ssd' and 'active' in line.split() for line in image_stores.splitlines()):
raise RuntimeError('opi5_ssd is not available for the OpenWrt VM disk')
def write_router_image(archive, work):
image = work / 'openwrt.img'
with gzip.open(archive, 'rb') as source, image.open('wb') as dest:
shutil.copyfileobj(source, dest)
loop = run('losetup', '--find', '--partscan', '--show', str(image))
mountpoint = work / 'root'
mountpoint.mkdir()
mounted = False
try:
partition = Path(loop + 'p2')
if not partition.exists():
raise RuntimeError('OpenWrt root partition did not appear')
run('mount', str(partition), str(mountpoint))
mounted = True
config_dir = mountpoint / 'etc/config'
if not config_dir.is_dir():
raise RuntimeError('OpenWrt image lacks /etc/config')
for name in ('network', 'dhcp', 'firewall'):
(config_dir / name).write_text(CONFIGS[name], encoding='utf-8')
if AUTHORIZED_KEY:
keys = mountpoint / 'etc/dropbear'
keys.mkdir(parents=True, exist_ok=True)
(keys / 'authorized_keys').write_text(AUTHORIZED_KEY.rstrip() + '\n', encoding='utf-8')
(keys / 'authorized_keys').chmod(0o600)
run('sync')
finally:
if mounted:
run('umount', str(mountpoint))
run('losetup', '-d', loop)
return image
def main():
try:
check_preconditions()
BASE.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix='guest-provision-', dir=str(BASE)))
print(f'Preparing verified guest images in {work}', flush=True)
archive = verified_download(OPENWRT_URL, OPENWRT, OPENWRT_URL + 'sha256sums', work)
alpine = verified_download(ALPINE_URL, ALPINE, ALPINE_URL + ALPINE + '.sha256', work)
image = write_router_image(archive, work)
template_dir = STORAGE / 'template/cache'
template_dir.mkdir(parents=True, exist_ok=True)
template_name = 'alpine-3.22-default_3.22.7_arm64.tar.gz'
template = template_dir / template_name
if template.exists():
raise RuntimeError(f'Template already exists; refusing overwrite: {template}')
shutil.copyfile(alpine, template)
run('qm', 'create', '9100', '--name', 'jeannie-sandbox-openwrt',
'--description', 'jeannie-network-sandbox-v1', '--bios', 'ovmf',
'--cores', '2', '--memory', '512', '--onboot', '0',
'--net0', 'virtio,bridge=vmbr0,link_down=1',
'--net1', 'virtio,bridge=vmbr9,trunks=10;20',
'--ostype', 'l26', '--scsihw', 'virtio-scsi-pci', '--serial0', 'socket')
run('qm', 'set', '9100', '--efidisk0', 'opi5_ssd:1,efitype=4m,pre-enrolled-keys=0')
run('qm', 'importdisk', '9100', str(image), 'opi5_ssd', '--format', 'raw', timeout=900)
cfg = run('qm', 'config', '9100')
match = re.search(r'^unused\d+:\s*(\S+)', cfg, re.MULTILINE)
if not match:
raise RuntimeError('Imported VM disk was not found')
run('qm', 'set', '9100', '--scsi0', match.group(1), '--boot', 'order=scsi0')
for ctid, vlan in ((9110, 10), (9111, 20)):
run('pct', 'create', str(ctid), f'jeannie-sandbox:vztmpl/{template_name}',
'--hostname', f'jeannie-sandbox-client-{vlan}', '--arch', 'arm64',
'--unprivileged', '1', '--cores', '1', '--memory', '256', '--swap', '0',
'--rootfs', 'jeannie-sandbox:2', '--onboot', '0',
'--net0', f'name=eth0,bridge=vmbr9,tag={vlan},ip=dhcp', timeout=600)
print('Created stopped OpenWrt VM 9100 and stopped Alpine containers 9110 and 9111.')
print('WAN remains disconnected. Guests were not started; runtime guard was not changed.')
print(f'Provisioning files retained at {work}')
except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox guest provisioning failed: {exc}. Existing and partially created resources were preserved.', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Provision stopped sandbox guests through the Debian-to-Pimox SSH path."""
import importlib.util
import json
import os
import subprocess
import sys
from pathlib import Path
def main():
scripts = 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:
spec = importlib.util.spec_from_file_location('sandbox_config', scripts / 'network-sandbox-config.py')
config = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config)
configs = config.build_configs()
public_key = Path(key + '.pub')
authorized = public_key.read_text(encoding='utf-8').strip() if public_key.is_file() else ''
if not authorized.startswith(('ssh-ed25519 ', 'ssh-rsa ', 'ecdsa-sha2-')):
raise ValueError('A readable SSH public key is required for the sandbox router')
source = (scripts / 'network-sandbox-guests-host.py').read_text(encoding='utf-8')
prelude = 'import json\nCONFIGS = json.loads(' + repr(json.dumps(configs)) + ')\nAUTHORIZED_KEY = ' + repr(authorized) + '\n'
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 -'], input=(prelude + source).encode(), timeout=1800).returncode
except (OSError, ValueError, subprocess.SubprocessError) as exc:
print(f'Sandbox guest provisioning failed: {exc}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Start or stop only the dedicated, previously provisioned sandbox guests."""
import fcntl
import ipaddress
import json
import os
import subprocess
import sys
from pathlib import Path
def run(*args):
result = subprocess.run(args, capture_output=True, text=True, timeout=120)
if result.returncode:
raise RuntimeError(f'{args[0]} failed: {result.stderr.strip()[-500:]}')
return result.stdout.strip()
def config_fields(text):
return dict(line.split(': ', 1) for line in text.splitlines() if ': ' in line)
def network_options(text):
return dict(part.split('=', 1) for part in text.split(',') if '=' in part)
def verify_guests(require_isolated=True):
router = config_fields(run('qm', 'config', '9100'))
if router.get('name') != 'jeannie-sandbox-openwrt' or router.get('description') != 'jeannie-network-sandbox-v1':
raise RuntimeError('VM 9100 is not the dedicated sandbox router')
if require_isolated:
networks = {key for key in router if key.startswith('net') and key[3:].isdigit()}
if networks != {'net0', 'net1'}:
raise RuntimeError('Unexpected router interfaces; refusing to start it')
wan, lan = network_options(router['net0']), network_options(router['net1'])
if wan.get('bridge') != 'vmbr0' or wan.get('link_down') != '1':
raise RuntimeError('Router WAN must remain disconnected pending isolation validation')
if lan.get('bridge') != 'vmbr9' or set(lan.get('trunks', '').split(';')) != {'10', '20'}:
raise RuntimeError('Router is not attached to the expected sandbox VLAN trunk')
for ctid, vlan in ((9110, 10), (9111, 20)):
client = config_fields(run('pct', 'config', str(ctid)))
if client.get('hostname') != f'jeannie-sandbox-client-{vlan}' or client.get('unprivileged') != '1':
raise RuntimeError(f'Container {ctid} is not the expected unprivileged sandbox client')
if require_isolated:
net = network_options(client.get('net0', ''))
if net.get('bridge') != 'vmbr9' or net.get('tag') != str(vlan):
raise RuntimeError(f'Container {ctid} is not attached to its sandbox VLAN')
if any(k.startswith('net') and k[3:].isdigit() and k != 'net0' for k in client):
raise RuntimeError(f'Container {ctid} has an unexpected network interface')
def verify_bridge_and_routes():
bridge = Path('/sys/class/net/vmbr9')
if not (bridge / 'bridge').is_dir() or (bridge / 'ifalias').read_text().strip() != 'jeannie-network-sandbox':
raise RuntimeError('The dedicated sandbox bridge is missing or unmarked')
if (bridge / 'bridge/vlan_filtering').read_text().strip() != '1':
raise RuntimeError('Sandbox bridge is not VLAN aware')
allowed = {'tap9100i1', 'veth9110i0', 'veth9111i0'}
members = {p.name for p in (bridge / 'brif').iterdir()}
if not members.issubset(allowed):
raise RuntimeError('Sandbox bridge has unexpected members: ' + ', '.join(sorted(members - allowed)))
sandbox_nets = [ipaddress.ip_network('172.29.210.0/24'), ipaddress.ip_network('172.29.220.0/24')]
for route in json.loads(run('ip', '-j', '-4', 'route', 'show', 'table', 'all')):
if route.get('dst', 'default') == 'default':
continue
network = ipaddress.ip_network(route['dst'], strict=False)
if any(network.overlaps(sandbox) for sandbox in sandbox_nets):
raise RuntimeError(f'Sandbox subnet overlaps an existing host route: {network}')
def status(command, guest):
output = run(command, 'status', str(guest))
if output not in ('status: stopped', 'status: running'):
raise RuntimeError(f'Unexpected {command} status for {guest}: {output}')
return output.endswith('running')
def owned_existing_guests():
resources = json.loads(run('pvesh', 'get', '/cluster/resources', '--type', 'vm', '--output-format', 'json'))
indexed = {int(item['vmid']): item.get('type') for item in resources if 'vmid' in item}
result = []
for command, guest, kind in (('pct', 9111, 'lxc'), ('pct', 9110, 'lxc'), ('qm', 9100, 'qemu')):
if guest not in indexed:
continue
if indexed[guest] != kind:
raise RuntimeError(f'Guest ID {guest} has an unexpected resource type')
fields = config_fields(run(command, 'config', str(guest)))
if command == 'qm':
if fields.get('name') != 'jeannie-sandbox-openwrt' or fields.get('description') != 'jeannie-network-sandbox-v1':
raise RuntimeError('VM 9100 is not the dedicated sandbox router')
else:
vlan = 10 if guest == 9110 else 20
if fields.get('hostname') != f'jeannie-sandbox-client-{vlan}' or fields.get('unprivileged') != '1':
raise RuntimeError(f'Container {guest} is not the expected sandbox client')
result.append((command, guest))
return result
def main():
if os.geteuid() != 0 or len(sys.argv) != 2 or sys.argv[1] not in ('start', 'stop'):
print('Run as root with start or stop', file=sys.stderr)
return 2
action = sys.argv[1]
started = []
try:
with open('/run/lock/jeannie-network-sandbox.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if action == 'start':
verify_guests()
verify_bridge_and_routes()
for command, guest in (('qm', 9100), ('pct', 9110), ('pct', 9111)):
if not status(command, guest):
run(command, 'start', str(guest))
started.append((command, guest))
if not status(command, guest):
raise RuntimeError(f'{command} guest {guest} did not remain running')
print('Sandbox guests started with the router WAN disconnected; internet access is not enabled.')
print('Guest startup does not prove firewall or VLAN isolation; validate both before connecting WAN.')
else:
for command, guest in owned_existing_guests():
if status(command, guest):
run(command, 'stop', str(guest))
print('Stopped sandbox guests; their disks and configuration were retained.')
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
for command, guest in reversed(started):
try:
run(command, 'stop', str(guest))
except (OSError, RuntimeError, subprocess.SubprocessError):
pass
print(f'Sandbox {action} failed: {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Run the isolated sandbox guest lifecycle over SSH."""
import os
import subprocess
import sys
from pathlib import Path
def main():
if len(sys.argv) != 2 or sys.argv[1] not in ('start', 'stop'):
print('Usage: network-sandbox-lifecycle.py {start|stop}', file=sys.stderr)
return 2
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 = (Path(__file__).resolve().parent / 'network-sandbox-lifecycle-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}',
f'sudo -n python3 - {sys.argv[1]}'], input=source, timeout=420).returncode
except (OSError, subprocess.SubprocessError) as exc:
print(f'Sandbox lifecycle failed: {exc}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())

View File

@ -45,7 +45,7 @@ uname -m
guests[kind] = [line.split()[:3] for line in sections[kind]
if line.split() and line.split()[0].isdigit()]
report = {
'mode': 'read-only planning; sandbox creation is not implemented',
'mode': 'read-only planning; guests are provisioned separately and start offline',
'host_architecture': ' '.join(sections['architecture']),
'proposed_vm': {'id': 9100, 'role': 'OpenWrt router'},
'proposed_containers': [{'id': 9110, 'vlan': 10}, {'id': 9111, 'vlan': 20}],

View File

@ -0,0 +1,24 @@
"""Cluster exclusion does not depend on unrelated sandbox guests."""
import importlib.util
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('runtime_guard', ROOT / 'scripts/cluster-runtime-guard.py')
guard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guard)
class SandboxGuardTests(unittest.TestCase):
def test_unrelated_vms_are_not_cluster_guests(self):
self.assertFalse(guard.is_competing_cluster_vm(9100, 'jeannie-sandbox-openwrt', {9001, 9010, 9011}))
self.assertFalse(guard.is_competing_cluster_vm(9101, 'another-lab', {9001, 9010, 9011}))
def test_declared_and_named_cluster_vms_remain_conflicts(self):
self.assertTrue(guard.is_competing_cluster_vm(9010, 'renamed', {9001, 9010, 9011}))
self.assertTrue(guard.is_competing_cluster_vm(9100, 'renamed', {9100}))
self.assertTrue(guard.is_competing_cluster_vm(9200, 'pimox-worker-03', {9001, 9010, 9011}))
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,38 @@
"""Offline checks for sandbox guest image verification."""
import hashlib
import importlib.util
import tempfile
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_guests', ROOT / 'scripts/network-sandbox-guests-host.py')
guests = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guests)
class SandboxGuestTests(unittest.TestCase):
def test_download_requires_matching_vendor_checksum(self):
content = b'example guest image'
digest = hashlib.sha256(content).hexdigest()
with tempfile.TemporaryDirectory() as directory:
def fetch(url, destination):
destination.write_bytes((digest + ' image.gz\n').encode() if url.endswith('checksum') else content)
with patch.object(guests, 'fetch', side_effect=fetch):
image = guests.verified_download('https://example.invalid/', 'image.gz',
'https://example.invalid/checksum', Path(directory))
self.assertEqual(image.read_bytes(), content)
def test_checksum_mismatch_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
def fetch(url, destination):
destination.write_bytes((('0' * 64) + ' image.gz\n').encode() if url.endswith('checksum') else b'image')
with patch.object(guests, 'fetch', side_effect=fetch):
with self.assertRaisesRegex(RuntimeError, 'Checksum mismatch'):
guests.verified_download('https://example.invalid/', 'image.gz',
'https://example.invalid/checksum', Path(directory))
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,38 @@
"""Checks for sandbox guest identity and network constraints."""
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_lifecycle', ROOT / 'scripts/network-sandbox-lifecycle-host.py')
lifecycle = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lifecycle)
class SandboxLifecycleTests(unittest.TestCase):
def setUp(self):
self.router = ('name: jeannie-sandbox-openwrt\n'
'description: jeannie-network-sandbox-v1\n'
'net0: virtio=00:00:00:00:00:01,bridge=vmbr0,link_down=1\n'
'net1: virtio=00:00:00:00:00:02,bridge=vmbr9,trunks=10;20\n')
self.client10 = 'hostname: jeannie-sandbox-client-10\nunprivileged: 1\nnet0: name=eth0,bridge=vmbr9,tag=10\n'
self.client20 = 'hostname: jeannie-sandbox-client-20\nunprivileged: 1\nnet0: name=eth0,bridge=vmbr9,tag=20\n'
def test_expected_guests_are_accepted(self):
with patch.object(lifecycle, 'run', side_effect=[self.router, self.client10, self.client20]):
lifecycle.verify_guests()
def test_connected_wan_is_rejected(self):
with patch.object(lifecycle, 'run', return_value=self.router.replace(',link_down=1', '')):
with self.assertRaisesRegex(RuntimeError, 'WAN must remain disconnected'):
lifecycle.verify_guests()
def test_extra_client_interface_is_rejected(self):
with patch.object(lifecycle, 'run', side_effect=[self.router, self.client10 + 'net1: name=eth1,bridge=vmbr0\n']):
with self.assertRaisesRegex(RuntimeError, 'unexpected network interface'):
lifecycle.verify_guests()
if __name__ == '__main__':
unittest.main()