#!/usr/bin/env python3 """Small reference report, not the full private production audit.""" import argparse import datetime as dt import json import multiprocessing as mp import os from pathlib import Path import re import socket import subprocess import sys import time import urllib.error from common import atomic_json, hostname, https_url, opener, timeout_value def validate_check(item): kind = item.get('kind') allowed = {'name', 'kind', 'timeout', 'ca_file', 'url', 'expected_status'} if kind == 'http' else {'name', 'kind', 'timeout', 'host', 'port'} if kind not in {'http', 'tcp'} or set(item) - allowed or not isinstance(item.get('name'), str) or not item['name']: raise ValueError('Invalid check schema') timeout_value(item.get('timeout', 5)) if kind == 'http': https_url(item['url']) if type(item.get('expected_status')) is not int or not 100 <= item['expected_status'] <= 599: raise ValueError('Set an expected HTTP status') else: hostname(item['host']) if type(item['port']) is not int or not 1 <= item['port'] <= 65535: raise ValueError('Invalid TCP port') return item def perform_check(item): validate_check(item) timeout = timeout_value(item.get('timeout', 5)) if item['kind'] == 'http': try: with opener(item.get('ca_file')).open(item['url'], timeout=timeout) as response: status = response.status except urllib.error.HTTPError as exc: status = exc.code exc.close() return {'ok': status == item['expected_status'], 'status': status, 'expected_status': item['expected_status'], 'scope': 'http-response-only'} with socket.create_connection((item['host'], item['port']), timeout=timeout): return {'ok': True, 'scope': 'tcp-connect-only'} def _worker(pipe, item): try: pipe.send(perform_check(item)) except Exception as exc: pipe.send({'ok': False, 'error': type(exc).__name__}) finally: pipe.close() def bounded_check(item, worker=_worker): validate_check(item) # Parent hard deadline includes DNS, connect, TLS and slow headers. No orphan check threads. context = mp.get_context('spawn') receive, send = context.Pipe(duplex=False) process = context.Process(target=worker, args=(send, item), daemon=True) start = time.monotonic() try: process.start() send.close() if receive.poll(timeout_value(item.get('timeout', 5))): try: result = receive.recv() except EOFError: result = {'ok': False, 'error': 'WorkerExited'} else: result = {'ok': False, 'error': 'DeadlineExceeded'} result['name'] = item['name'] result['elapsed_seconds'] = round(time.monotonic() - start, 3) return result finally: if process.pid is not None: process.join(timeout=0.05) if process.is_alive(): process.terminate() process.join(timeout=1) if process.is_alive(): process.kill() process.join() receive.close() send.close() def docker_inventory(env): # Opt-in only. Fixed remote command, no sudo, no install, no permission changes. host = hostname(env['DOCKER_SSH_HOST']) user = env['DOCKER_SSH_USER'] if not re.fullmatch(r'[a-z_][a-z0-9_-]*', user): raise ValueError('Invalid SSH user') known = Path(env['DOCKER_KNOWN_HOSTS']).expanduser() if not known.is_file(): raise ValueError('Existing verified known_hosts file required') command = ['ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'PasswordAuthentication=no', '-o', 'KbdInteractiveAuthentication=no', '-o', 'StrictHostKeyChecking=yes', '-o', f'UserKnownHostsFile={known}', '-o', 'ConnectTimeout=5', '-o', 'ConnectionAttempts=1', '-o', 'ClearAllForwardings=yes', f'{user}@{host}', 'docker ps --format "{{json .}}"'] result = subprocess.run(command, text=True, capture_output=True, timeout=15, check=False) if result.returncode: return {'ok': False, 'error': 'SSHOrDockerPermissionFailure', 'exit_code': result.returncode} rows = [json.loads(line) for line in result.stdout.splitlines() if line.strip()] return {'ok': True, 'scope': 'inventory-not-application-health', 'containers': [{k: row.get(k) for k in ('Names', 'Image', 'Status')} for row in rows]} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('config') parser.add_argument('--output-dir', default='~/.local/state/homelab-weekly') args = parser.parse_args() with open(args.config, encoding='utf-8') as f: config = json.load(f) if set(config) != {'checks'} or not isinstance(config['checks'], list) or not 1 <= len(config['checks']) <= 50: raise ValueError('Expected 1..50 checks') names = set() for item in config['checks']: validate_check(item) if item['name'] in names: raise ValueError('Duplicate check name') names.add(item['name']) report = {'generated_at': dt.datetime.now(dt.timezone.utc).isoformat(), 'scope': 'simplified-reference-not-full-production-audit', 'checks': [bounded_check(item) for item in config['checks']]} if os.environ.get('DOCKER_SSH_ENABLED') == '1': try: report['docker_inventory'] = docker_inventory(os.environ) except Exception as exc: report['docker_inventory'] = {'ok': False, 'error': type(exc).__name__} report['ok'] = all(r['ok'] for r in report['checks']) and report.get('docker_inventory', {'ok': True})['ok'] atomic_json(args.output_dir, 'latest.json', report) return 0 if report['ok'] else 1 if __name__ == '__main__': try: sys.exit(main()) except Exception as exc: print('Weekly report failed: ' + type(exc).__name__, file=sys.stderr) sys.exit(1)