#!/usr/bin/env python3 """Local testtask hook: exact safe source copy, isolated state, foreground servers.""" import base64 import hashlib import json import os from pathlib import Path import re import secrets import shutil import subprocess import sys ROOT = Path(os.environ['ROBORTO_PROJECT_ROOT']).resolve() RUN = Path(os.environ['ROBORTO_RUN_DIR']).resolve() TASK = os.environ['ROBORTO_TASK_ID'] SNAPSHOT = Path(os.environ['ROBORTO_WORKTREE']) COMMON = Path(subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', '--path-format=absolute', '--git-common-dir'], text=True).strip()) SHARED = COMMON.parent MARKER = '.testtask-owner' EXCLUDED_DIRS = {'.git', '.worktrees', '.test-worktrees', '.venv', 'venv', 'node_modules', 'share', 'instance', '__pycache__', '.pytest_cache', 'dist', 'dist-ssr', 'build', 'coverage', 'snapshots', 'logs'} SUFFIXES = ('.pyc', '.pyo', '.log', '.zip', '.db', '.sqlite', '.sqlite3', '.pem', '.key', '.p12', '.pfx') def fail(message): raise RuntimeError(message) def source(): entries = subprocess.check_output(['git', '-C', str(ROOT), 'worktree', 'list', '--porcelain', '-z']).decode().split('\0') found, path = [], None for entry in entries: if entry.startswith('worktree '): path = Path(entry[9:]) if entry.startswith('branch refs/heads/') and re.fullmatch(r'(?:task/TASK-' + TASK + r'-[\w-]+)', entry[18:]): found.append(path) if len(found) != 1: fail(f'Expected exactly one checked-out task/TASK-{TASK}-* branch; found {len(found)}') return found[0] def safe_files(src): names = subprocess.check_output(['git', '-C', str(src), 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0') result = {} for raw in names: if not raw: continue relative = Path(os.fsdecode(raw)) path = src / relative if any(part in EXCLUDED_DIRS for part in relative.parts): continue if any(part.startswith('.') and part not in {'.gitignore', '.roborto'} for part in relative.parts): continue if relative.name.lower().startswith(('credentials', 'id_rsa', 'id_ed25519')) or relative.name.lower().endswith(SUFFIXES): continue if any(parent.is_symlink() for parent in [path, *path.parents]) or not path.is_file(): continue result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() return result def dependencies(): node = os.environ.get('FOLDERSHARE_TEST_NODE') or shutil.which('node') if not node: candidates = list((Path.home() / '.nvm/versions/node').glob('v*/bin/node')) candidates.sort(key=lambda p: tuple(int(n) for n in p.parents[1].name[1:].split('.'))) node = str(candidates[-1]) if candidates else None vite = SHARED / 'react/node_modules/vite/bin/vite.js' if not node or not Path(node).is_file() or not vite.is_file(): fail('Need Node >=18 and existing react/node_modules; install dependencies separately') version = subprocess.check_output([node, '-p', 'process.versions.node'], text=True) if int(version.split('.')[0]) < 18: fail('Node >=18 required; set FOLDERSHARE_TEST_NODE') return node, vite def validate(): if not re.fullmatch(r'\d{3}', TASK): fail('Task ID must contain three digits') expected = ROOT / '.test-worktrees' / ('task-' + TASK) if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink() or SNAPSHOT.is_symlink(): fail('Unexpected or symlinked snapshot path') if SNAPSHOT.exists(): fail('Snapshot already exists; preserve it and stop its owning session first') src = source() # Older application settings must never silently fall back to a local DB. if 'FOLDERSHARE_DATABASE_URI' not in (src / 'api/settings.py').read_text(): fail('Candidate lacks isolated database configuration (TASK-002 prerequisite)') dependencies() import flask, flask_sqlalchemy, flask_httpauth, flask_migrate, sqlalchemy_serializer # noqa: F401 print(f'Validated source {src}', file=sys.stderr) def prepare(): validate() src = source() manifest = safe_files(src) SNAPSHOT.parent.mkdir(exist_ok=True) SNAPSHOT.mkdir(mode=0o700) (SNAPSHOT / MARKER).write_text(str(RUN)) for name in manifest: dest = SNAPSHOT / name dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src / name, dest) copied = {name: hashlib.sha256((SNAPSHOT / name).read_bytes()).hexdigest() for name in manifest} if copied != manifest or safe_files(src) != manifest: fail('Source changed during snapshot creation; rerun with a stable candidate') (RUN / 'manifest.json').write_text(json.dumps({'source': str(src), 'files': manifest}, indent=2)) (SNAPSHOT / 'react/node_modules').symlink_to(SHARED / 'react/node_modules', target_is_directory=True) (SNAPSHOT / 'react/testtask.vite.config.mjs').write_text('''import base from './vite.config.js'; export default {...base, cacheDir: process.env.FOLDERSHARE_TEST_CACHE, server: {...base.server, host: '127.0.0.1', port: 5503, strictPort: true, proxy: {'/api': 'http://127.0.0.1:5502'}}}; ''') media = RUN / 'media' (media / 'friends').mkdir(parents=True) (media / 'friends/sample.txt').write_text('Disposable test media only.\n') (RUN / 'password').write_text(secrets.token_urlsafe(18)) print(f'Snapshot verified: {len(manifest)} source files from {src}', file=sys.stderr) def start_backend(): env = os.environ.copy() env.update(FOLDERSHARE_DATABASE_URI='sqlite:///' + str(RUN / 'accounts.sqlite'), ROOT_PATH=str(RUN / 'media'), PYTHON_DOTENV_DISABLED='1', DEBUG='False', SQLALCHEMY_ECHO='False', PYTHONPATH=str(SNAPSHOT / 'api')) bootstrap = '''from pathlib import Path from settings import app, db from models.user import User import os assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ['FOLDERSHARE_DATABASE_URI'], 'Unsafe database configuration' with app.app_context(): db.create_all() for name, admin, root in [('captain', True, None), ('friend', False, '/friends'), ('unassigned', False, None), ('disabled', False, '/friends')]: user = User(username=name, is_admin=admin, root=root, login_disabled=name == 'disabled') user.set_password(Path(os.environ['ROBORTO_RUN_DIR'], 'password').read_text()) db.session.add(user) user.get_token() db.session.commit() import api app.run(host='127.0.0.1', port=5502, debug=False, use_reloader=False) ''' os.chdir(SNAPSHOT / 'api') os.execve(sys.executable, [sys.executable, '-c', bootstrap], env) def start_frontend(): node, vite = dependencies() env = os.environ.copy() env['FOLDERSHARE_TEST_CACHE'] = str(RUN / 'vite-cache') os.chdir(SNAPSHOT / 'react') os.execve(node, [node, str(vite), '--config', 'testtask.vite.config.mjs'], env) def credentials(): # Real HTTP checks, in addition to engine port checks. from urllib.request import Request, urlopen from urllib.error import HTTPError for base in ['http://127.0.0.1:5502', 'http://127.0.0.1:5503']: try: urlopen(base + '/api/file/root', timeout=5) fail('Protected API unexpectedly allowed an anonymous request') except HTTPError as error: if error.code != 401: raise password = (RUN / 'password').read_text() for name in ['captain', 'friend', 'unassigned', 'disabled']: basic = base64.b64encode(f'{name}:{password}'.encode()).decode() request = Request('http://127.0.0.1:5503/api/auth/token', method='POST', headers={'Authorization': 'Basic ' + basic}) try: with urlopen(request, timeout=5) as response: data = json.load(response) if name == 'disabled' or not data.get('token'): fail('Disposable login fixture failed') except HTTPError as error: if name != 'disabled' or error.code != 401: raise manifest = json.loads((RUN / 'manifest.json').read_text()) if safe_files(Path(manifest['source'])) != manifest['files']: fail('Candidate changed since snapshot creation; stop and rerun before testing') with urlopen('http://127.0.0.1:5503', timeout=5) as response: if response.status != 200: fail('Frontend HTTP check failed') print('HTTP readiness passed. Disposable accounts: captain (admin), friend, unassigned, disabled.') print('Shared session password:', (RUN / 'password').read_text()) print('Candidate snapshot:', SNAPSHOT) print('Source must remain unchanged while testing; Ctrl-C stops servers and removes this snapshot.') def cleanup(): expected = ROOT / '.test-worktrees' / ('task-' + TASK) if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink(): fail('Refusing cleanup outside the owned snapshot path') marker = SNAPSHOT / MARKER if not SNAPSHOT.is_symlink() and marker.is_file() and marker.read_text() == str(RUN): shutil.rmtree(SNAPSHOT) if __name__ == '__main__': try: actions = {'validate': validate, 'prepare': prepare, 'start-backend': start_backend, 'start-frontend': start_frontend, 'credentials': credentials, 'cleanup': cleanup} actions[sys.argv[1]]() except Exception as error: print(f'testtask: {error}', file=sys.stderr) sys.exit(1)