diff --git a/.ai/runtime/examples/sandbox-profile.json b/.ai/runtime/examples/sandbox-profile.json index cc92970..e5a6407 100644 --- a/.ai/runtime/examples/sandbox-profile.json +++ b/.ai/runtime/examples/sandbox-profile.json @@ -2,7 +2,7 @@ "protocol_version": "1.0", "profile_id": "task-developer", "isolation_level": "workspace-write", - "platform": "auto", + "platform": "linux", "filesystem": { "workspace_read": true, "workspace_write": true, @@ -49,5 +49,9 @@ ], "direct_workspace_sharing": false, "symlink_policy": "reject-escape" + }, + "runtime": { + "backend": "linux-rootless-oci", + "image": "ghcr.io/easyindie/easyproject-agent@sha256:0000000000000000000000000000000000000000000000000000000000000000" } } diff --git a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md index f61c5ee..ce2baa0 100644 --- a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md +++ b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md @@ -2,38 +2,23 @@ ## Status -This change adds the backend interface, policy validation, capability reporting and fail-closed integration point. **It does not ship a production OS-enforcement backend.** On all hosts, `doctor` must currently report `enforcement_ready: false`. This is expected and must not be worked around by treating a Worktree, Agent permission mode, or tool allowlist as isolation. +The repository now includes a Linux Rootless Podman backend and a conservative capability probe. A host is enforcement-ready only when rootless mode, subordinate UID/GID mappings, cgroup v2, systemd delegation, and cpu/memory/pids controllers are verified. Other platforms remain unavailable. Unit tests do not prove kernel enforcement; dedicated Linux conformance tests are still required. A Worktree, Agent permission mode, or tool allowlist is not isolation. ## Execution invariant The launcher receives the complete harness argv and starts the harness as its child inside one boundary. All descendants—including shell commands, built-in file tools, MCP servers, hooks, language servers and extensions—must remain subject to that boundary. A backend that only wraps Bash is insufficient. -A backend is eligible only if it can enforce all of the following for the requested profile: +A backend is eligible only if it can enforce workspace-only filesystem access, default-deny network, process-tree inheritance and termination, CPU/memory/PID/wall-clock limits, no privilege escalation, no host runtime socket, and a sanitized launcher environment. Egress proxy and scoped-secret broker capabilities are mandatory when requested by the profile. Failure during setup aborts before the Agent starts. -- workspace-only filesystem access, including denial of stable checkout, other task workspaces, shared Git common metadata/object/ref stores, user home, credentials and control-plane runtime; -- default-deny network, no host/LAN access, and explicit egress proxy policy; -- process-tree inheritance and reliable termination, including killing every descendant before the launcher reports task completion; -- CPU, memory, process-count and wall-clock limits; -- no privilege escalation and no host container-runtime socket; -- effective-policy evidence (backend/version, profile digest and platform); -- sanitized launcher environment: never inherit the host environment wholesale; -- egress proxy and scoped-secret broker capabilities when the profile requests them; -- profile wall-clock timeout must cap the Runner timeout. +## Linux Rootless Podman -The manager rejects partial backends. A backend must not claim support based on a binary being installed; `probe()` must verify prerequisites needed to enforce the actual policy. Failure during setup aborts before the Agent starts. +The implementation is in `scripts/sandbox_backends/podman_rootless.py`. It requires rootless Podman, subordinate UID/GID mappings, cgroup v2, systemd cgroup manager and delegated cpu/memory/pids controllers. It uses a digest-pinned image already present locally (`--pull=never`), private namespaces, `--network=none`, read-only rootfs, dropped capabilities, no-new-privileges, a single task workspace mount, private tmpfs and explicit resource limits. -## Python interface +Worktree `.git` pointer files are rejected because they refer to shared Git metadata outside the task. Use an independent clone or a patch-only workflow. The backend does not implement egress proxy or credential brokering; requests requiring either are rejected by backend selection. -Implemented in `scripts/sandbox_runtime.py`: - -- `SandboxBackend.probe() -> SandboxCapabilities` (must prove both process-tree inheritance and descendant cleanup on task exit) -- `SandboxBackend.build_command(command, spec) -> argv` -- `SandboxBackend.build_environment(spec) -> minimal env` -- `SandboxManager.doctor()` -- `SandboxManager.build_command(...)` -- `load_profile(path)` +## Verification boundary -Backends are injected into the manager by trusted application code. A backend must provide both a wrapped argv and a minimal environment; returning `os.environ.copy()` or forwarding host credential variables violates the contract. Task JSON and Agent-controlled configuration cannot register a backend, choose an arbitrary launcher executable, or relax a profile. Task permissions are intersected with the trusted maximum profile: they may narrow workspace read/write, network and brokered-secret access, but cannot expand any of them. +Unit tests prove policy selection, argv construction and fail-closed behavior only. They do not prove namespaces, seccomp, filesystem isolation, network isolation or effective cgroup enforcement. M4.4.4 requires a dedicated Linux worker conformance suite. Do not describe the backend as production-ready until that suite passes. ## CLI @@ -43,19 +28,4 @@ python3 scripts/sandbox_runtime.py validate-profile --profile .ai/runtime/exampl python3 scripts/agent-orchestrate.py --plan .ai/runtime/examples/plan.json --worktrees --require-sandbox ``` -Exit code 3 from `doctor` means no production backend can enforce the complete policy. This is a fail-closed status, not a runtime failure to be ignored. - -## Agent Runner - -`agent-orchestrate.py --require-sandbox --worktrees` is the trusted control-plane switch; sandbox-required runs refuse a shared stable checkout. The Orchestrator pins the profile path and digest in the external run journal and passes the requirement to every Runner invocation. A resume must preserve the requirement and exact profile digest. Direct `agent-run.py --require-sandbox --sandbox-profile ` requests mandatory enforcement. If no complete backend is registered, it exits before spawning Pi, Codex or Claude Code. Without `--require-sandbox`, legacy local execution remains explicitly unsandboxed and is not to be described as secure or isolated. New unattended or untrusted execution flows must pass `--require-sandbox`. - -## Backend implementation sequence - -1. macOS Seatbelt: launch the entire harness process tree, explicit file rules, deny network by default, verify effective policy. Do not rely on Codex's internal command sandbox as a wrapper around Claude/Pi. -2. Linux Rootless OCI: user/mount/PID/network namespaces, read-only root, no-new-privileges, seccomp, LSM, cgroup limits, no Docker socket. -3. Windows: AppContainer or dedicated VM/WSL2 worker; verify each harness's support and process inheritance. -4. Stronger remote backend: gVisor/Kata/Firecracker for hostile multi-tenant workloads. - -## Verification boundary - -Unit tests for this contract use a fake backend and prove selection, sanitized-environment handoff and fail-closed behavior only. They do not prove Seatbelt, namespaces, seccomp, filesystem isolation, network isolation or kernel enforcement. Those claims require backend-specific conformance tests on the supported host OS. +Exit code 3 from `doctor` means no backend can enforce the complete policy. This is fail-closed status, not a runtime failure to ignore. diff --git a/.ai/runtime/sandbox/PODMAN-ROOTLESS.md b/.ai/runtime/sandbox/PODMAN-ROOTLESS.md new file mode 100644 index 0000000..e81d347 --- /dev/null +++ b/.ai/runtime/sandbox/PODMAN-ROOTLESS.md @@ -0,0 +1,21 @@ +# Linux Rootless Podman Backend (M4.4.1–M4.4.2) + +This backend is intentionally narrow: Linux, rootless Podman, cgroup v2, systemd user-service delegation, and delegated cpu/memory/pids controllers. It refuses rootful Podman, cgroup v1, missing subordinate UID/GID mappings, missing resource controllers, mutable image tags, and shared Git worktree pointer files. + +## Runtime image + +Every profile must set `runtime.backend=linux-rootless-oci` and an immutable OCI reference of the form `registry/name@sha256:<64 lowercase hex>`. The image must already exist in rootless Podman's local image store; launch uses `--pull=never`. The example uses a syntactically valid placeholder digest only; it is not a published or verified image. + +## Launch boundary + +The launcher applies rootless user namespaces, private PID/network/IPC/cgroup namespaces, `network=none`, read-only container root, dropped capabilities, no-new-privileges, private tmpfs mounts, one task-workspace bind mount, and explicit CPU/memory/PID limits. The Agent receives a minimal container environment. No host credentials, host home, shared Git metadata, or runtime socket are mounted. + +The trusted Podman client receives only the environment required for its rootless runtime. Egress proxy and scoped-secret broker are not implemented; profiles requesting either remain ineligible. + +## Git metadata + +A worktree whose `.git` is a pointer file is rejected. Use an independent clone with its own `.git` directory, or make the Agent produce patches without Git metadata. Never mount the host shared Git common directory into the container. + +## Verification status + +Unit tests cover launcher argv construction, image pinning, Git pointer rejection and environment shaping. They do not prove kernel enforcement. M4.4.4 still requires a dedicated Linux worker conformance suite against the actual Podman, cgroup and systemd configuration. diff --git a/.ai/runtime/schemas/sandbox-profile.schema.json b/.ai/runtime/schemas/sandbox-profile.schema.json index 2dc9cb2..60f89ca 100644 --- a/.ai/runtime/schemas/sandbox-profile.schema.json +++ b/.ai/runtime/schemas/sandbox-profile.schema.json @@ -5,90 +5,304 @@ "description": "Declarative least-privilege policy for an externally enforced Agent task sandbox. This schema does not itself enforce isolation.", "type": "object", "additionalProperties": false, - "required": ["protocol_version", "profile_id", "isolation_level", "filesystem", "process", "network", "secrets", "artifacts"], + "required": [ + "protocol_version", + "profile_id", + "isolation_level", + "filesystem", + "process", + "network", + "secrets", + "artifacts", + "runtime" + ], "properties": { - "protocol_version": {"const": "1.0"}, - "profile_id": {"type": "string", "pattern": "^[a-z][a-z0-9-]{1,47}$"}, - "isolation_level": {"enum": ["read-only", "workspace-write", "restricted-network", "microvm"]}, - "platform": {"enum": ["auto", "macos", "linux", "windows"]}, + "protocol_version": { + "const": "1.0" + }, + "profile_id": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{1,47}$" + }, + "isolation_level": { + "enum": [ + "read-only", + "workspace-write", + "restricted-network", + "microvm" + ] + }, + "platform": { + "enum": [ + "auto", + "macos", + "linux", + "windows" + ] + }, "filesystem": { - "type": "object", "additionalProperties": false, - "required": ["workspace_read", "workspace_write", "stable_checkout", "other_agent_workspaces", "shared_git_metadata", "user_home", "credentials", "runtime_directory", "temporary_directory"], + "type": "object", + "additionalProperties": false, + "required": [ + "workspace_read", + "workspace_write", + "stable_checkout", + "other_agent_workspaces", + "shared_git_metadata", + "user_home", + "credentials", + "runtime_directory", + "temporary_directory" + ], "properties": { - "workspace_read": {"type": "boolean"}, - "workspace_write": {"type": "boolean"}, - "stable_checkout": {"const": "deny"}, - "other_agent_workspaces": {"const": "deny"}, - "shared_git_metadata": {"const": "deny"}, - "user_home": {"const": "deny"}, - "credentials": {"const": "deny"}, - "runtime_directory": {"const": "deny"}, - "temporary_directory": {"enum": ["private", "none"]}, - "read_only_paths": {"type": "array", "items": {"type": "string"}, "default": []}, - "write_paths": {"type": "array", "items": {"type": "string"}, "default": []} + "workspace_read": { + "type": "boolean" + }, + "workspace_write": { + "type": "boolean" + }, + "stable_checkout": { + "const": "deny" + }, + "other_agent_workspaces": { + "const": "deny" + }, + "shared_git_metadata": { + "const": "deny" + }, + "user_home": { + "const": "deny" + }, + "credentials": { + "const": "deny" + }, + "runtime_directory": { + "const": "deny" + }, + "temporary_directory": { + "enum": [ + "private", + "none" + ] + }, + "read_only_paths": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + }, + "write_paths": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + } } }, "process": { - "type": "object", "additionalProperties": false, - "required": ["isolated_process_tree", "inherit_sandbox", "resource_limits", "timeout_enforced", "privilege_escalation"], + "type": "object", + "additionalProperties": false, + "required": [ + "isolated_process_tree", + "inherit_sandbox", + "resource_limits", + "timeout_enforced", + "privilege_escalation" + ], "properties": { - "isolated_process_tree": {"const": true}, - "inherit_sandbox": {"const": true}, - "resource_limits": {"const": true}, - "timeout_enforced": {"const": true}, - "privilege_escalation": {"const": "deny"}, - "max_cpu": {"type": "number", "exclusiveMinimum": 0}, - "max_memory_mb": {"type": "integer", "minimum": 128}, - "max_processes": {"type": "integer", "minimum": 1}, - "timeout_seconds": {"type": "integer", "minimum": 1} + "isolated_process_tree": { + "const": true + }, + "inherit_sandbox": { + "const": true + }, + "resource_limits": { + "const": true + }, + "timeout_enforced": { + "const": true + }, + "privilege_escalation": { + "const": "deny" + }, + "max_cpu": { + "type": "number", + "exclusiveMinimum": 0 + }, + "max_memory_mb": { + "type": "integer", + "minimum": 128 + }, + "max_processes": { + "type": "integer", + "minimum": 1 + }, + "timeout_seconds": { + "type": "integer", + "minimum": 1 + } } }, "network": { - "type": "object", "additionalProperties": false, - "required": ["default", "allowed_domains", "allow_lan", "allow_host"], + "type": "object", + "additionalProperties": false, + "required": [ + "default", + "allowed_domains", + "allow_lan", + "allow_host" + ], "properties": { - "default": {"const": "deny"}, - "allowed_domains": {"type": "array", "uniqueItems": true, "items": {"type": "string"}}, - "allow_lan": {"const": false}, - "allow_host": {"const": false}, - "egress_proxy_required": {"type": "boolean", "default": true} + "default": { + "const": "deny" + }, + "allowed_domains": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string" + } + }, + "allow_lan": { + "const": false + }, + "allow_host": { + "const": false + }, + "egress_proxy_required": { + "type": "boolean", + "default": true + } } }, "secrets": { - "type": "object", "additionalProperties": false, - "required": ["inherit_host_environment", "credential_mounts", "brokered_credentials"], + "type": "object", + "additionalProperties": false, + "required": [ + "inherit_host_environment", + "credential_mounts", + "brokered_credentials" + ], "properties": { - "inherit_host_environment": {"const": false}, - "credential_mounts": {"const": false}, - "brokered_credentials": {"type": "array", "items": {"type": "string"}, "default": []} + "inherit_host_environment": { + "const": false + }, + "credential_mounts": { + "const": false + }, + "brokered_credentials": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + } } }, "artifacts": { - "type": "object", "additionalProperties": false, - "required": ["export", "direct_workspace_sharing", "symlink_policy"], + "type": "object", + "additionalProperties": false, + "required": [ + "export", + "direct_workspace_sharing", + "symlink_policy" + ], "properties": { - "export": {"type": "array", "uniqueItems": true, "items": {"enum": ["diff", "patch", "handoff", "test-report", "review-evidence"]}}, - "direct_workspace_sharing": {"const": false}, - "symlink_policy": {"const": "reject-escape"} + "export": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "diff", + "patch", + "handoff", + "test-report", + "review-evidence" + ] + } + }, + "direct_workspace_sharing": { + "const": false + }, + "symlink_policy": { + "const": "reject-escape" + } } }, "runtime": { - "type": "object", "additionalProperties": false, + "type": "object", + "additionalProperties": false, + "required": [ + "backend", + "image" + ], "properties": { - "backend": {"enum": ["native", "macos-seatbelt", "linux-rootless-oci", "rootless-docker", "windows-appcontainer", "wsl2-worker", "gvisor", "kata", "firecracker"]}, - "image": {"type": "string"}, - "image_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"} + "backend": { + "enum": [ + "native", + "macos-seatbelt", + "linux-rootless-oci", + "rootless-docker", + "windows-appcontainer", + "wsl2-worker", + "gvisor", + "kata", + "firecracker" + ] + }, + "image": { + "type": "string", + "pattern": "^.+@sha256:[0-9a-f]{64}$" + }, + "image_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } } } }, "allOf": [ { - "if": {"properties": {"isolation_level": {"const": "read-only"}}}, - "then": {"properties": {"filesystem": {"properties": {"workspace_write": {"const": false}}}}} + "if": { + "properties": { + "isolation_level": { + "const": "read-only" + } + } + }, + "then": { + "properties": { + "filesystem": { + "properties": { + "workspace_write": { + "const": false + } + } + } + } + } }, { - "if": {"properties": {"isolation_level": {"const": "microvm"}}}, - "then": {"properties": {"runtime": {"required": ["backend"], "properties": {"backend": {"const": "firecracker"}}}}} + "if": { + "properties": { + "isolation_level": { + "const": "microvm" + } + } + }, + "then": { + "properties": { + "runtime": { + "properties": { + "backend": { + "const": "firecracker" + } + } + } + } + } } ] } diff --git a/scripts/sandbox_backends/__init__.py b/scripts/sandbox_backends/__init__.py new file mode 100644 index 0000000..53e7101 --- /dev/null +++ b/scripts/sandbox_backends/__init__.py @@ -0,0 +1 @@ +# Sandbox backend implementations. diff --git a/scripts/sandbox_backends/podman_rootless.py b/scripts/sandbox_backends/podman_rootless.py new file mode 100644 index 0000000..f0279ce --- /dev/null +++ b/scripts/sandbox_backends/podman_rootless.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Conservative Linux Rootless Podman backend for task-scoped Agent sandboxes.""" +from __future__ import annotations +import os +import re +import shutil +import subprocess +import json +from pathlib import Path +from typing import Sequence +from sandbox_runtime import SandboxCapabilities, SandboxEnforcementError, SandboxLaunchSpec + +PINNED_IMAGE = re.compile(r"^.+@sha256:[0-9a-f]{64}$") +REQUIRED = {"cpu", "memory", "pids"} + +class RootlessPodmanBackend: + backend_id = "linux-rootless-oci" + + def __init__(self, podman: str | None = None) -> None: + self.podman = podman or shutil.which("podman") or "podman" + + @staticmethod + def _host_environment() -> dict[str, str]: + env = { + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "HOME": str(Path.home()), + "LANG": "C", + "LC_ALL": "C", + } + for key in ("XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"): + if os.environ.get(key): + env[key] = os.environ[key] + return env + + @staticmethod + def _delegated_controllers() -> tuple[set[str], str]: + root_file = Path("/sys/fs/cgroup/cgroup.controllers") + if not root_file.is_file(): + return set(), "cgroup v2 is unavailable" + try: + root = set(root_file.read_text().split()) + except OSError as exc: + return set(), f"cannot read cgroup controllers: {exc}" + if not REQUIRED.issubset(root): + return root, "host lacks cpu/memory/pids controllers" + systemctl = shutil.which("systemctl") + if not systemctl: + return set(), "systemctl unavailable; delegation cannot be verified" + try: + result = subprocess.run( + [systemctl, "--user", "show", "--property=ControlGroup", "--value"], + text=True, capture_output=True, check=False, timeout=5, + env=RootlessPodmanBackend._host_environment(), + ) + except (OSError, subprocess.TimeoutExpired) as exc: + return set(), f"cannot inspect user cgroup: {exc}" + rel = result.stdout.strip() + if result.returncode or not rel.startswith("/"): + return set(), "systemd user service cgroup is unavailable" + cgroup = Path("/sys/fs/cgroup") / rel.lstrip("/") + try: + available = set((cgroup / "cgroup.controllers").read_text().split()) + enabled = set((cgroup / "cgroup.subtree_control").read_text().replace("+", "").split()) + except OSError as exc: + return set(), f"user cgroup delegation is unreadable: {exc}" + effective = enabled + if not REQUIRED.issubset(effective): + return effective, "cpu/memory/pids are not delegated to the user service" + return effective, "required systemd user cgroup controllers verified" + + def probe(self) -> SandboxCapabilities: + failures: list[str] = [] + if not Path("/proc/self/uid_map").is_file(): + failures.append("Linux UID namespace mapping is unavailable") + if not shutil.which(self.podman): + failures.append("Podman executable is unavailable") + info: dict = {} + if not failures: + try: + result = subprocess.run( + [self.podman, "info", "--format", "json"], + text=True, capture_output=True, check=False, timeout=8, + env=self._host_environment(), + ) + if result.returncode: + failures.append("podman info failed: " + result.stderr.strip()) + else: + info = json.loads(result.stdout) + except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as exc: + failures.append(f"cannot inspect Podman: {exc}") + host = info.get("host", {}) if info else {} + if info and host.get("security", {}).get("rootless") is not True: + failures.append("Podman is not rootless") + if info and host.get("cgroupVersion") != "v2": + failures.append("Podman is not using cgroup v2") + if info and host.get("cgroupManager") != "systemd": + failures.append("Podman is not using systemd cgroups") + maps = host.get("idMappings", {}) if info else {} + uidmap = maps.get("uidmap", []) if isinstance(maps, dict) else [] + gidmap = maps.get("gidmap", []) if isinstance(maps, dict) else [] + if info and (not uidmap or not gidmap or + not any(int(x.get("size", 0)) > 1 for x in uidmap + gidmap)): + failures.append("subordinate UID/GID mappings are missing") + controllers, reason = self._delegated_controllers() + if not REQUIRED.issubset(controllers): + failures.append(reason) + ready = not failures + return SandboxCapabilities( + backend_id=self.backend_id, platform="linux", available=ready, + enforces_filesystem=ready, enforces_network=ready, + isolates_process_tree=ready, terminates_process_tree_on_exit=ready, + enforces_resource_limits=ready, supports_egress_proxy=False, + supports_secrets_broker=False, status="ready" if ready else "unavailable", + reason="; ".join(failures) if failures else + "rootless Podman, subordinate ID maps and delegated cgroup v2 verified", + ) + + def build_environment(self, spec: SandboxLaunchSpec) -> dict[str, str]: + runtime_dir = os.environ.get("XDG_RUNTIME_DIR", "") + if not runtime_dir or not Path(runtime_dir).is_dir(): + raise SandboxEnforcementError("XDG_RUNTIME_DIR is unavailable.") + return { + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "HOME": str(Path.home()), "XDG_RUNTIME_DIR": runtime_dir, + "LANG": "C", "LC_ALL": "C", + } + + def build_command(self, command: Sequence[str], spec: SandboxLaunchSpec) -> list[str]: + if not command or any(not isinstance(arg, str) for arg in command): + raise SandboxEnforcementError("Agent command must be a non-empty argv.") + runtime = spec.profile.get("runtime", {}) + image = runtime.get("image", "") + if runtime.get("backend") != self.backend_id or not PINNED_IMAGE.fullmatch(image): + raise SandboxEnforcementError("runtime.image must be pinned by sha256 digest.") + workspace = spec.workspace + if not workspace.is_dir() or workspace.is_symlink(): + raise SandboxEnforcementError("Workspace must be an existing real directory.") + if "," in str(workspace): + raise SandboxEnforcementError("Workspace path cannot contain commas in Podman mount syntax.") + git = workspace / ".git" + if git.is_symlink() or git.is_file(): + raise SandboxEnforcementError("Git worktree pointer or symlink detected; shared Git metadata is forbidden.") + if git.exists() and not git.is_dir(): + raise SandboxEnforcementError("Unsupported .git metadata type.") + if git.is_dir() and ((git / "commondir").exists() or (git / "objects/info/alternates").exists()): + raise SandboxEnforcementError("Shared Git common directory or object alternates are forbidden.") + fs = spec.profile["filesystem"] + if not fs["workspace_read"]: + raise SandboxEnforcementError("Workspace read access is required.") + process = spec.profile["process"] + memory = int(process["max_memory_mb"]) + cpu = float(process["max_cpu"]) + pids = int(process["max_processes"]) + if memory < 128 or cpu <= 0 or pids < 1 or spec.timeout_seconds < 1: + raise SandboxEnforcementError("Invalid effective resource limits.") + mode = "rw" if fs["workspace_write"] else "ro" + uid, gid = os.getuid(), os.getgid() + return [ + self.podman, "run", "--rm", "--init", "--pull=never", + "--userns=keep-id", f"--user={uid}:{gid}", + "--network=none", "--pid=private", "--ipc=private", "--cgroupns=private", + "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges", + f"--pids-limit={pids}", f"--memory={memory}m", f"--cpus={cpu:g}", + "--stop-timeout=5", "--ulimit=core=0", + "--tmpfs", "/tmp:rw,noexec,nosuid,nodev,size=256m", + "--tmpfs", "/home/sandbox:rw,noexec,nosuid,nodev,size=64m", + "--mount", f"type=bind,src={workspace},dst=/workspace,{mode}", + "--workdir=/workspace", + "--env=PATH=/usr/local/bin:/usr/bin:/bin", + "--env=HOME=/home/sandbox", "--env=TMPDIR=/tmp", + "--env=LANG=C.UTF-8", "--env=LC_ALL=C.UTF-8", "--env=CI=1", + image, *command, + ] diff --git a/scripts/sandbox_runtime.py b/scripts/sandbox_runtime.py index c811dd5..cf62295 100644 --- a/scripts/sandbox_runtime.py +++ b/scripts/sandbox_runtime.py @@ -11,6 +11,7 @@ import hashlib import json import platform +import sys from dataclasses import asdict, dataclass from pathlib import Path from typing import Protocol, Sequence @@ -106,7 +107,18 @@ def host_platform() -> str: class SandboxManager: """Selects only backends that explicitly prove complete policy support.""" - def __init__(self, backends: Sequence[SandboxBackend] = ()) -> None: + def __init__(self, backends: Sequence[SandboxBackend] | None = None) -> None: + if backends is None: + backends = () + if host_platform() == "linux": + try: + scripts_dir = str(ROOT / "scripts") + if scripts_dir not in sys.path: + sys.path.insert(0, scripts_dir) + from sandbox_backends.podman_rootless import RootlessPodmanBackend + backends = (RootlessPodmanBackend(),) + except ImportError: + backends = () self._backends = {backend.backend_id: backend for backend in backends} def capabilities(self) -> list[SandboxCapabilities]: diff --git a/scripts/validate-repo.sh b/scripts/validate-repo.sh index c9922f5..8641c63 100644 --- a/scripts/validate-repo.sh +++ b/scripts/validate-repo.sh @@ -22,6 +22,10 @@ required_files=( "scripts/agent-run.py" "scripts/sandbox_runtime.py" "tests/test_sandbox_runtime.py" + "scripts/sandbox_backends/__init__.py" + "scripts/sandbox_backends/podman_rootless.py" + "tests/test_sandbox_podman.py" + ".ai/runtime/sandbox/PODMAN-ROOTLESS.md" "scripts/artifact_broker.py" "tests/test_artifact_broker.py" ".ai/runtime/schemas/artifact-manifest.schema.json" @@ -66,6 +70,7 @@ for name in ( "scripts/bootstrap.py", "tests/test_bootstrap.py", "scripts/agent-run.py", "tests/test_agent_runner.py", "scripts/sandbox_runtime.py", "tests/test_sandbox_runtime.py", + "scripts/sandbox_backends/podman_rootless.py", "tests/test_sandbox_podman.py", "scripts/artifact_broker.py", "tests/test_artifact_broker.py", "scripts/agent-orchestrate.py", "tests/test_agent_orchestrator.py", "scripts/evolution.py", "tests/test_evolution.py", diff --git a/tasks/evolution/M4-sandbox-runtime.md b/tasks/evolution/M4-sandbox-runtime.md index 091663a..dcea11c 100644 --- a/tasks/evolution/M4-sandbox-runtime.md +++ b/tasks/evolution/M4-sandbox-runtime.md @@ -10,7 +10,7 @@ Introduce OS-enforced, task-scoped isolation so multiple cooperating Agents cann - `scripts/agent-run.py` is a process dispatcher, not a sandbox. - Codex has an OS-enforced sandbox mode; Claude Code's Bash sandbox does not cover all built-in tools and helpers. - Pi's tool allowlist is not a security boundary. The current Evolution path automatically adds `harness_options.pi_unsandboxed_write=true`, which is not genuine human opt-in and must be removed in M4.1. -- The repository has task orchestration, approval artifacts, cancellation and review evidence, but no OS-enforced universal backend or artifact broker. +- The repository has task orchestration, approval artifacts, cancellation and review evidence. The Linux Rootless Podman launcher is now implemented behind a fail-closed capability probe; kernel-level conformance is still pending. ## Work breakdown @@ -22,7 +22,10 @@ Introduce OS-enforced, task-scoped isolation so multiple cooperating Agents cann | M4.2b | Backend decision | Accepted platform ADR; Linux Rootless Podman selected for full profile; shared Git metadata and credential-broker dependencies documented | | M4.3a | Artifact Broker core | Content-addressed export, manifest/hash verification, read-only reviewer materialization, path/symlink/type/size validation | | M4.3b | Artifact Broker integration | Sandbox-required Orchestrator exports immutable review artifacts after Agent and checks exit; approval and Integrator verify task/base/fingerprint binding | -| M4.4 | Linux Rootless OCI backend | Rootless Podman, cgroup-v2 delegated limits, namespaces, seccomp/LSM, network deny, private Git metadata, conformance suite | +| M4.4.1 | Rootless Podman capability probe | Verify rootless mode, subordinate UID/GID mappings, cgroup v2, systemd delegation and cpu/memory/pids controllers | +| M4.4.2 | Rootless OCI launcher | Pinned image, network none, namespaces, read-only rootfs, workspace-only mount, limits, sanitized Agent environment | +| M4.4.3 | Git metadata isolation | Reject shared worktree pointer metadata; move toward independent task clones or patch-only Agent workspaces | +| M4.4.4 | Linux conformance suite | Prove filesystem, network, process-tree and effective resource enforcement on a dedicated Linux worker | | M4.5 | Strong isolation backends | gVisor/Kata/Firecracker plugin interface and documented deployment profiles | | M4.6 | Brokers and audit | Scoped credential/network broker, policy hash, denial evidence, operational guide | @@ -32,7 +35,7 @@ The platform selection and prerequisites are recorded in [ADR-001: Production Sa ## Execution order -M4.0 is documentation and schema only. M4.1 is merged. M4.2a defines the backend interface and fail-closed launch path, but does not provide OS enforcement. M4.2b adds a real host backend and must not be marked complete until process-tree tests prove that file tools, shell tools, MCP/hooks and descendants share the boundary. M4.3 can be developed independently after the immutable artifact contract is agreed. Linux backend work follows the broker and policy interfaces. +M4.0 is documentation and schema only. M4.1 is merged. M4.2a defines the backend interface and fail-closed launch path, but does not provide OS enforcement. M4.2b records the platform decision. M4.3a/b artifact exchange is complete. M4.4.1/4.4.2 now provide a conservative Rootless Podman probe and launcher, but M4.4 remains incomplete until independent Git metadata handling and dedicated Linux kernel-conformance tests pass. The backend deliberately does not support network egress or credential brokering; those remain M4.6 work. ## Explicit non-goals diff --git a/tests/test_agent_orchestrator.py b/tests/test_agent_orchestrator.py index 57463be..2c71d06 100644 --- a/tests/test_agent_orchestrator.py +++ b/tests/test_agent_orchestrator.py @@ -153,16 +153,19 @@ def test_sandboxed_acceptance_checks_fail_closed_without_backend(self): root = Path(tmp) workspace = root / "workspace" workspace.mkdir() - with self.assertRaisesRegex(RuntimeError, "No registered backend"): - orchestrator.run_acceptance_checks( - ["python-unittest"], workspace, root / "runs", - "task-a", 1, require_sandbox=True, - sandbox_profile=ROOT / ".ai/runtime/examples/sandbox-profile.json", - task_permissions={ - "repository_read": True, "repository_write": True, - "network_access": False, "secret_access": False, - }, - ) + import sandbox_runtime + empty_manager = sandbox_runtime.SandboxManager(backends=[]) + with patch("sandbox_runtime.SandboxManager", return_value=empty_manager): + with self.assertRaisesRegex(RuntimeError, "No registered backend"): + orchestrator.run_acceptance_checks( + ["python-unittest"], workspace, root / "runs", + "task-a", 1, require_sandbox=True, + sandbox_profile=ROOT / ".ai/runtime/examples/sandbox-profile.json", + task_permissions={ + "repository_read": True, "repository_write": True, + "network_access": False, "secret_access": False, + }, + ) def test_review_artifact_is_portable_and_bound_to_review_evidence(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/test_agent_runner.py b/tests/test_agent_runner.py index eb26211..158899c 100644 --- a/tests/test_agent_runner.py +++ b/tests/test_agent_runner.py @@ -57,10 +57,11 @@ def test_required_sandbox_fails_closed_before_any_agent_process_starts(self): "artifacts": { "export": ["diff"], "direct_workspace_sharing": False, "symlink_policy": "reject-escape" - } + }, + "runtime": {"backend": "linux-rootless-oci", "image": "registry.example/agent@sha256:" + "a" * 64} }), encoding="utf-8") with self.assertRaises(sandbox_runtime.SandboxBackendUnavailable): - sandbox_runtime.SandboxManager().build_command( + sandbox_runtime.SandboxManager(backends=[]).build_command( ["pi", "--print"], profile_path, "task-1", Path(tmp), Path(tmp) / "runtime", {"repository_read": True, "repository_write": True, diff --git a/tests/test_sandbox_podman.py b/tests/test_sandbox_podman.py new file mode 100644 index 0000000..b13dd48 --- /dev/null +++ b/tests/test_sandbox_podman.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Podman launcher unit tests; not kernel conformance.""" +from __future__ import annotations +import importlib.util, tempfile, unittest, sys +from pathlib import Path +from unittest.mock import patch +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/"scripts")) +SPEC=importlib.util.spec_from_file_location("podman_rootless",ROOT/"scripts/sandbox_backends/podman_rootless.py") +podman=importlib.util.module_from_spec(SPEC) +assert SPEC and SPEC.loader +sys.modules["podman_rootless"]=podman +SPEC.loader.exec_module(podman) +from sandbox_runtime import SandboxLaunchSpec, SandboxEnforcementError +def spec_for(ws,writable=True,image=None): + profile={"runtime":{"backend":"linux-rootless-oci","image":image or ("registry.example/agent@sha256:"+"a"*64)},"filesystem":{"workspace_read":True,"workspace_write":writable},"process":{"max_memory_mb":2048,"max_cpu":2,"max_processes":128},"network":{"default":"deny"}} + return SandboxLaunchSpec("task-1",profile,"b"*64,ws,ws/"runtime",600) +class PodmanTests(unittest.TestCase): + def test_rootless_private_networkless_and_limits(self): + with tempfile.TemporaryDirectory() as tmp: + ws=Path(tmp)/"ws"; ws.mkdir() + cmd=podman.RootlessPodmanBackend("/usr/bin/podman").build_command(["python","-m","pytest"],spec_for(ws)); joined=" ".join(cmd) + for flag in ("--userns=keep-id","--network=none","--pid=private","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=2048m","--cpus=2","--pull=never","dst=/workspace,rw"): self.assertIn(flag,joined) + self.assertEqual(cmd[-3:],["python","-m","pytest"]) + def test_read_only_workspace(self): + with tempfile.TemporaryDirectory() as tmp: + cmd=podman.RootlessPodmanBackend().build_command(["true"],spec_for(Path(tmp),False)); self.assertIn("dst=/workspace,ro"," ".join(cmd)) + def test_git_worktree_pointer_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + ws=Path(tmp); (ws/".git").write_text("gitdir: /shared/.git/worktrees/task") + with self.assertRaises(SandboxEnforcementError): podman.RootlessPodmanBackend().build_command(["true"],spec_for(ws)) + def test_mutable_image_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + for image in ("agent:latest","agent:1.0","agent@sha256:abc"): + with self.subTest(image=image), self.assertRaises(SandboxEnforcementError): podman.RootlessPodmanBackend().build_command(["true"],spec_for(Path(tmp),image=image)) + def test_agent_environment_is_minimal(self): + with tempfile.TemporaryDirectory() as tmp: + with patch.dict("os.environ",{"XDG_RUNTIME_DIR":tmp,"PATH":"/usr/bin"},clear=True): env=podman.RootlessPodmanBackend().build_environment(spec_for(Path(tmp))) + self.assertEqual(set(env),{"PATH","HOME","XDG_RUNTIME_DIR","LANG","LC_ALL"}); self.assertNotIn("API_KEY",env) +if __name__=="__main__": unittest.main(verbosity=2) diff --git a/tests/test_sandbox_profile.py b/tests/test_sandbox_profile.py index 35eba9d..06597d6 100644 --- a/tests/test_sandbox_profile.py +++ b/tests/test_sandbox_profile.py @@ -59,6 +59,10 @@ def baseline_profile() -> dict: "direct_workspace_sharing": False, "symlink_policy": "reject-escape", }, + "runtime": { + "backend": "linux-rootless-oci", + "image": "registry.example/agent@sha256:" + "a" * 64, + }, } diff --git a/tests/test_sandbox_runtime.py b/tests/test_sandbox_runtime.py index c0aa3f9..670f096 100644 --- a/tests/test_sandbox_runtime.py +++ b/tests/test_sandbox_runtime.py @@ -47,12 +47,13 @@ def profile() -> dict: "artifacts": { "export": ["diff"], "direct_workspace_sharing": False, "symlink_policy": "reject-escape" - } + }, + "runtime": {"backend": "linux-rootless-oci", "image": "registry.example/agent@sha256:" + "a" * 64} } class FakeBackend: - backend_id = "test-backend" + backend_id = "linux-rootless-oci" def probe(self): return sandbox.SandboxCapabilities( @@ -74,7 +75,7 @@ def probe(self): class SandboxRuntimeTests(unittest.TestCase): def test_doctor_fails_closed_when_no_backend_is_registered(self): - doctor = sandbox.SandboxManager().doctor() + doctor = sandbox.SandboxManager(backends=[]).doctor() self.assertFalse(doctor["enforcement_ready"]) self.assertEqual(doctor["fallback"], "forbidden") self.assertEqual(doctor["backends"][0]["status"], "not-implemented") @@ -114,7 +115,7 @@ def test_missing_backend_refuses_to_launch(self): profile_path = Path(tmp) / "profile.json" profile_path.write_text(json.dumps(profile()), encoding="utf-8") with self.assertRaises(sandbox.SandboxBackendUnavailable): - sandbox.SandboxManager().build_command( + sandbox.SandboxManager(backends=[]).build_command( ["pi"], profile_path, "task-1", Path(tmp), Path(tmp) / "runtime", {"repository_read": True, "repository_write": True, "network_access": False, "secret_access": False} @@ -159,7 +160,7 @@ def test_registered_backend_receives_frozen_policy_and_wraps_whole_command(self) self.assertEqual(command, ["sandbox-test-wrapper", "claude", "-p"]) self.assertEqual(environment, {"PATH": "/sandbox/bin", "HOME": "/sandbox/home"}) self.assertEqual(evidence["status"], "enforced") - self.assertEqual(evidence["backend"], "test-backend") + self.assertEqual(evidence["backend"], "linux-rootless-oci") self.assertEqual(len(evidence["profile_sha256"]), 64)