"""One preparation and execution interface for every attack family.""" from __future__ import annotations import copy import os from pathlib import Path import shutil import subprocess import sys from .config import Configuration, role_environment, write_role_configs from .dataset import AttackUnit from .io import inside, read_json, write_json from .sources import materialize def _outside_release(root: Path, output: Path) -> Path: output = output.resolve() if output == root or root in output.parents: raise ValueError("Keep execution workspaces outside the public dataset directory") return output def resolve_plan_paths(plan: dict, dataset_root: Path, engine_root: Path) -> dict: """Resolve portable source references in an external execution copy.""" if 'tool_package' in plan: plan['tool_package']['package_dir'] = str(inside(dataset_root, plan['tool_package']['package_dir'])) metadata = plan.get('generation_metadata') if metadata is not None: task = inside(dataset_root, metadata['source_task_dir']) metadata['source_task_dir'] = str(task) for item in metadata.get('included_files', []): reference = item['path'] if reference.startswith('engine://'): source = inside(engine_root, reference[len('engine://'):]) elif item.get('sandbox_path'): source = inside(dataset_root, reference) else: source = inside(task, reference) if not source.is_file(): raise ValueError('Required native source file is missing: ' + str(source)) item['path'] = str(source) return plan def prepare(unit: AttackUnit, output: Path, configuration: Configuration | None = None, *, profile: str | None = None) -> dict: """Create an isolated, inspectable workspace without running a model or a task.""" output = _outside_release(unit.root, output) row = unit.metadata if configuration: from .blue_runtime import check_output_budget, unit_output_budget check_output_budget(configuration.roles['blue'].capabilities, unit_output_budget(unit)) selected_profile = row.get("engine_profile", row["family"]) if profile is not None and profile != selected_profile: raise ValueError("This unit is bound to engine profile " + selected_profile) plan = copy.deepcopy(unit.load_plan()) output.mkdir(parents=True, exist_ok=False, mode=0o700) engine = output / "engine" mapping = materialize(unit.root, selected_profile, engine) if mapping["family"] != row["family"]: raise ValueError("Engine profile belongs to a different attack family") resolve_plan_paths(plan, unit.root, engine) plan_file = output / "attack_plan.json" write_json(plan_file, plan) record = {"schema_version": "manipulationarena-execution-v1", "unit_key": row["unit_key"], "family": row["family"], "task_id": row["task_id"], "attack_channel": row["attack_channel"], "plan_file": str(plan_file), "source_plan_sha256": row["plan_sha256"], "engine_profile": selected_profile, "engine_root": str(engine), "plan_module": mapping["plan_module"], "entrypoint": mapping["entrypoint"], "dataset_root": str(unit.root), "model_calls": 0, "native_tasks_executed": 0} if row.get('case_id'):record['case_id'] = row['case_id'] # Contexts and saved initializations are frozen task inputs. source = inside(unit.root, row["unit_path"]).parent if row["family"] == "obstruction-attack": for name in ("request.json", "task_context.json", "initialization.json", "attack_start.json", "model_profiles.json"): shutil.copyfile(source / name, output / name) paths = write_role_configs(configuration, output / "private", container=row["family"] == "obstruction-attack") if configuration else {} if configuration: record["configuration"] = configuration.public() record["role_configs"] = {name: str(path) for name, path in paths.items()} from .local_docker import settings_for_task settings = settings_for_task(configuration.docker, row["task_id"]) if row['family'] == 'obstruction-attack': from .container_policy import obstruction_settings settings = obstruction_settings(settings, read_json(output / 'attack_start.json'), unit.root) write_json(output / "private/container.json", settings, mode=0o600) if row['family'] == 'obstruction-attack': from .obstruction import prepare_native prepare_native(record, configuration) write_json(output / "execution.json", record, mode=0o600) return record def validate_prepared(record: dict) -> dict: """Import the original family validator in a fresh Python process.""" result = subprocess.run([sys.executable, "-B", "-m", "manipulationarena.plancheck", str(Path(record["plan_file"]).parent / "execution.json")], env=inspection_environment(record), text=True, capture_output=True) if result.returncode: raise ValueError("Original plan validator rejected the prepared input: " + result.stderr[-2400:]) import json return json.loads(result.stdout) def inspection_environment(record: dict, *, environ=None) -> dict[str, str]: env = dict(os.environ if environ is None else environ) root = record["dataset_root"] env.update({"PYTHONDONTWRITEBYTECODE": "1", "MANIPULATIONARENA_ROOT": root, "MANIPULATIONARENA_GYM": str(Path(root) / "benign_tasks"), "MANIPULATIONARENA_ENGINE_ROOT": record["engine_root"], "PYTHONPATH": os.pathsep.join([root, str(Path(record["engine_root"]) / "src")])}) return env def command(record: dict, configuration: Configuration) -> list[str]: """Render the native command. No credentials are included in command arguments.""" engine = Path(record["engine_root"]) output = Path(record["plan_file"]).parent roles = record["role_configs"] family = record["family"] if family == "obstruction-attack": return [sys.executable, "-B", "-m", "manipulationarena.obstruction", str(output / "execution.json")] args = [sys.executable, "-B", str(engine / record["entrypoint"]), record["task_id"], record["attack_channel"], "--plan-file", record["plan_file"], "--red-config", roles["red"], "--blue-config", roles["blue"], "--results-root", str(output / "runs")] if family in {"self-preservation-attack", "oversight-evasion-attack"}: from .local_docker import memory_bytes, settings_for_task settings = settings_for_task(configuration.docker, record['task_id']) subdir = "violation-tools" if family == "self-preservation-attack" else "impossible-tasks" catalog = Path(record["dataset_root"]) / "benign_tasks/catalog" if family == 'oversight-evasion-attack': catalog = catalog / 'task_index.json' args += ["--catalog", str(catalog), "--tool-root", str(Path(record["dataset_root"]) / "datasets" / family / subdir), "--plans-root", str(output), "--container-config", str(output / "private/container.json"), "--container-cpu", settings["cpus"], "--container-memory", str(memory_bytes(settings["memory"]))] else: args += ["--tasks-root", str(Path(record["dataset_root"]) / "benign_tasks/tasks/solvable30"), "--container-config", str(output / "private/container.json")] return args def run(record: dict, configuration: Configuration, *, log=None) -> int: """Run a prepared unit through its original engine using local Docker.""" from .local_docker import validate_image validate_prepared(record) paths = {name: Path(path) for name, path in record["role_configs"].items()} env = inspection_environment(record, environ=role_environment(configuration, paths)) env["MANIPULATIONARENA_NATIVE_IMAGE"] = validate_image(configuration.docker['image']) env["MANIPULATIONARENA_ASSETS"] = configuration.environment.get("assets_root", "/opt/manipulationarena/assets") for setting, name in (('package_index_url', 'PIP_INDEX_URL'), ('package_extra_index_url', 'PIP_EXTRA_INDEX_URL'), ('package_trusted_host', 'PIP_TRUSTED_HOST')): if setting in configuration.environment: env[name] = configuration.environment[setting] if record['family'] == 'obstruction-attack': return run_native_container(record, configuration, env, log=log) return subprocess.run(command(record, configuration), env=env, cwd=record["dataset_root"], stdout=log, stderr=log, check=False).returncode def run_native_container(record, configuration, env, *, log=None): """Run the original native driver and Judge inside one local container.""" from .local_docker import DockerRuntime, load_settings output = Path(record['plan_file']).parent settings = load_settings(output / 'private/container.json') runtime = DockerRuntime(settings) image = runtime.image_info() from .obstruction import prepare_native prepare_native(record, configuration, runtime_image=image['Id']) passed = {k: v for k, v in env.items() if k.startswith(('MANIPULATIONARENA_', 'PIP_', 'BLUE_'))} passed.update(PYTHONPATH=env['PYTHONPATH'], PYTHONDONTWRITEBYTECODE='1') container = runtime.start(settings={**settings, 'image': image['Id']}, mounts=((record['dataset_root'], record['dataset_root'], True), (output, output, False)), environment=passed) write_json(output / 'local-container.json', {'container_id': container, 'image': settings['image'], 'image_id': image['Id'], 'privileged': settings['privileged'], 'security_opt': settings['security_opt'], 'cap_add': settings['cap_add']}, mode=0o600) try: return subprocess.run(['docker', 'exec', '-i', container, 'python3', '-B', '-m', 'manipulationarena.obstruction', str(output / 'execution.json')], stdout=log, stderr=log, check=False).returncode finally: runtime.stop(container)