diff --git a/doc/code/framework.md b/doc/code/framework.md index c10332e3eb..222a43c684 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -262,6 +262,10 @@ If you are contributing to PyRIT, that work will most likely land in one of the persists it. Outbound request metadata is separate from chat role, so missing trace links remain detectable on tool and assistant continuations. - Because targets are so varied, it is reasonable to return multiple tool calls, or none at all. +- A target that runs tools itself bounds its tool loop. When a tool raises `ToolInfrastructureError`, + such as a `SandboxToolProvider` tool whose sandbox failed, the target answers every pending call and + ends the turn with an error response whose metadata says why (`ToolLoopStop`), rather than asking + the model to fix infrastructure. `OpenAIResponseTarget` does this today. - One attack can have many targets (and in fact, converters and scorers can also use targets to convert/score the prompt). - **Does not own**: what to send or what to do with the response. A target sends a prepared `Message` and returns a response — it doesn't convert prompts (converters), score (scorers), manage the conversation or decide the next turn (attacks), apply attack logic, or persist prompts and responses to memory (the `prompt_normalizer` owns that). Its retries stay at the target layer (e.g. `RateLimitException`). @@ -304,6 +308,10 @@ If you are contributing to PyRIT, that work will most likely land in one of the evidence; a sandbox that cannot run it is an acquisition error, so the verdict is undetermined rather than false. Each scoring call runs afresh; an observation identifies the run and supports explicit replay. +- `SandboxCheckScorer` runs a fixed check program in the stateful sandbox where a model's tool calls + ran, and scores the judged response by what the check finds. It never runs the response's text, and + never reuses a stored verdict, because the sandbox can change. The caller owns isolation between + attempts, for example by resetting the sandbox. - Observation lifecycle is optional. A scorer that implements `AttemptObserver`, whether it is a root scorer or wrapped inside one, is asked by the attack to start observing after setup, once its attempt ID is allocated and before anything is sent, and to stop when the attempt ends. A @@ -382,15 +390,24 @@ The below talks about responsibilities of most modules in the PyRIT library ## Code Execution (Experimental) -**Responsibility**: Connect to caller-configured execution backends and return typed invocation results. +**Responsibility**: Connect to caller-configured execution backends, run programs in them by the same +rules whatever the backend, and return typed invocation results. -- The client API is private and experimental in `pyrit._code_execution`; it may change without a deprecation cycle. +- The API is private and experimental in `pyrit._code_execution`; it may change without a deprecation cycle. - Targets, converters, dataset generators, and scorers can inject the same `SandboxClient` contract from `pyrit._code_execution`. Execution inputs and results are private types in `pyrit.models.code_execution`. - `runtime_profile_name` selects a client-owned configuration by name, not by supplying an image or command. Clients advertise the available names through `get_runtime_profile_names()`. +- `Sandbox` is the base class for backends. An adapter translates a few hooks into its infrastructure's + API; the base class owns the rules: validation against declared limits, one shared session per + `environment` sandbox (state persists, callers take turns), retries only when nothing ran, renewal, + idle close, cancellation, reset, quarantine and evidence. A `call` sandbox keeps nothing between calls. + `SandboxRegistry` names sandboxes so every caller shares one `Sandbox` object per sandbox. +- A sandbox may keep state between calls, so a program can see what earlier calls left. Runs are + reproducible only in a `call` sandbox, such as the Docker example. - PyRIT does not own environments. The one-image Docker example is the only exception: `DockerSandboxClient` manages disposable containers; callers supply the daemon and pinned image. +- `SandboxToolProvider` (in targets) and `SandboxCheckScorer` (in scorers) build on `Sandbox`. - **Does not own**: interpreting results, scoring criteria, message or seed creation, memory persistence, or infrastructure setup. Those remain with the consumer or caller. diff --git a/doc/code/scoring/7_program_execution_scorer.ipynb b/doc/code/scoring/7_program_execution_scorer.ipynb index 2c79fe18c4..a78c789b2e 100644 --- a/doc/code/scoring/7_program_execution_scorer.ipynb +++ b/doc/code/scoring/7_program_execution_scorer.ipynb @@ -151,6 +151,18 @@ "Real execution and fault coverage is in `tests/integration/score/test_program_execution_scorer_integration.py`.\n", "Opt in with `RUN_ALL_TESTS=true`; the tests require the daemon and pinned image above." ] + }, + { + "cell_type": "markdown", + "id": "7", + "metadata": {}, + "source": [ + "## Check what a model's code did\n", + "\n", + "`ProgramExecutionScorer` runs the program a response contains. To score a response by what the model's\n", + "code did in a sandbox instead, `SandboxCheckScorer` runs a fixed check program in that sandbox after the\n", + "turn, and never runs the response itself. See [Sandboxed tool calls](../targets/12_sandboxed_tool_calls.md)." + ] } ], "metadata": { diff --git a/doc/code/scoring/7_program_execution_scorer.py b/doc/code/scoring/7_program_execution_scorer.py index 12775a87ec..8d456704a3 100644 --- a/doc/code/scoring/7_program_execution_scorer.py +++ b/doc/code/scoring/7_program_execution_scorer.py @@ -94,3 +94,10 @@ # %% [markdown] # Real execution and fault coverage is in `tests/integration/score/test_program_execution_scorer_integration.py`. # Opt in with `RUN_ALL_TESTS=true`; the tests require the daemon and pinned image above. + +# %% [markdown] +# ## Check what a model's code did +# +# `ProgramExecutionScorer` runs the program a response contains. To score a response by what the model's +# code did in a sandbox instead, `SandboxCheckScorer` runs a fixed check program in that sandbox after the +# turn, and never runs the response itself. See [Sandboxed tool calls](../targets/12_sandboxed_tool_calls.md). diff --git a/doc/code/targets/12_sandboxed_tool_calls.md b/doc/code/targets/12_sandboxed_tool_calls.md new file mode 100644 index 0000000000..706f23c216 --- /dev/null +++ b/doc/code/targets/12_sandboxed_tool_calls.md @@ -0,0 +1,185 @@ +# Sandboxed Tool Calls + +To test a model that acts by running code, its code has to run somewhere isolated that can keep its work +across a conversation, and something other than the model has to say what that code did. PyRIT has three +pieces for this: + +- a **`Sandbox`**, which runs programs on some infrastructure, such as a container, a VM or a hosted service; +- **`SandboxToolProvider`**, which turns a sandbox into tools a model can call, such as `run_python`; +- **`SandboxCheckScorer`**, which runs a fixed check program in the same sandbox after a turn and scores the + response by what the check finds. + +`pyrit._code_execution` is experimental, and so are the two classes built on it: their API may change +without a deprecation cycle. + +## Give a model tools that run in a sandbox + +Register each sandbox once, under a name, so that targets, scorers and operators share one `Sandbox` +object, and with it one session. An initializer is a good place to do it. Then give a tool-calling target the +sandbox's tools: + +```python +from pyrit._code_execution import SandboxRegistry +from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider + +SandboxRegistry.get_registry_singleton().register(MySandbox(...), name="windows-1") + +target = OpenAIResponseTarget( + tool_providers=[SandboxToolProvider(sandbox="windows-1")], + max_tool_rounds=20, +) +``` + +The model sees ordinary tools in its own API: + +| Tool | What it does | +|------|--------------| +| `run_` | Runs a program once, such as `run_python` or `run_powershell`, with optional arguments, standard input and timeout | +| `write_file`, `read_file`, `list_dir` | Work with files, in sandboxes whose files persist between calls | + +Results are JSON. `run_` returns the exit code, the output of each stream (cut at +`max_output_chars`, and marked when cut), whether the program timed out, and how long it took. A program +that fails is an ordinary result the model can read and fix. + +Arguments are checked against the sandbox's limits before anything runs, so a call rejected there goes back to +the model as an error, with the reason, and is never recorded as invoked. When the sandbox itself fails, the +tool raises `ToolInfrastructureError`, and `OpenAIResponseTarget` ends the turn with an error response +instead of asking the model to fix a problem that isn't its own. Every call the model made still gets a +result, so the conversation's history stays valid; the model is told only that the tool's infrastructure +failed, while the error response, which is never replayed to the model, keeps the details. Its `ToolLoopStop` +metadata says why the turn ended. `max_tool_rounds` bounds how many responses with tool calls one send runs; +it defaults to 10. + +When a script is done with its sandboxes, close them so no session is left open: + +```python +await SandboxRegistry.get_registry_singleton().close_all_async() +``` + +`close_async` is final. To end a session and keep using the sandbox, use `release_async`, which can also +retry a close that couldn't be confirmed, even after `close_async`. + +## Check what the code did + +A model's claim that it succeeded is not evidence. A check program, run in the same sandbox after the turn, +verifies the effect itself: + +```python +from pyrit.models import Equals, ProgramBehaves, ProgramCase, ProgramResult +from pyrit.score import SandboxCheckScorer + +check = SandboxCheckScorer( + sandbox="windows-1", + check_program="import os\nprint('present' if os.path.exists('C:/task.flag') else 'absent')\n", + condition=ProgramBehaves( + runtime_profile_name="windows-python", + cases=(ProgramCase(expected=ProgramResult(stdout=Equals(value="present"))),), + ), +) +``` + +Use it as an attack's objective scorer. It scores the response being judged true when every case of the +check produces its expected result, and false when one doesn't. When the sandbox fails, or the check times +out, the score is undetermined, so an infrastructure problem is never counted as the model failing. The +response's own text never runs. The check's program and output are stored as an observation linked to the +score. + +The check reads the sandbox as it is when it runs. So it runs again on every call rather than reusing a +stored verdict, and isolation is the caller's job, since a later attempt could otherwise score true on an +earlier attempt's effect: run one attempt at a time per sandbox (`max_concurrency=1`), turn off automatic +retries of failed attempts (`max_attempts_on_failure=0`), and reset the sandbox between attempts. It needs a +sandbox whose state persists. + +The check runs as the same account as the model's code, so it must not trust anything the model could have +written. For example, run Python checks in isolated mode, so a module the model saved in the working +directory can't stand in for a standard one. + +## The Docker example + +`DockerSandboxClient` runs each program in a disposable, network-less container, so nothing persists +between calls, and it offers `run_` tools only. It needs a Docker daemon and pre-pulled, pinned +images; [Program execution and scoring](../scoring/7_program_execution_scorer.ipynb) shows how to configure +it. PyRIT includes it as an example of an adapter, not as a hardened sandbox. + +```python +from pyrit._code_execution import DockerRuntimeProfile, DockerSandboxClient +from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider + +docker = DockerSandboxClient( + profiles={ + "python": DockerRuntimeProfile( + image="python@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1", + command=("python3", "-I"), + ) + } +) +target = OpenAIResponseTarget(tool_providers=[SandboxToolProvider(sandbox=docker)]) +``` + +## Bring your own sandbox + +An adapter is a small `Sandbox` subclass that translates a few calls into an infrastructure's own API. +PyRIT does the rest, so every sandbox behaves the same: + +```python +from pyrit._code_execution import ProcessResult, Sandbox, SandboxCapabilities, SandboxStatus + + +class MySandbox(Sandbox): + def _build_identifier(self): ... # static configuration only, never session ids or secrets + def _get_capabilities(self) -> SandboxCapabilities: ... # runtimes, state kind, limits + + async def _execute_async( + self, *, session_id, runtime_profile_name, program, arguments, stdin, timeout_seconds + ) -> ProcessResult: ... + + async def _open_session_async(self, *, owner) -> str: ... # not needed when nothing persists + async def _close_session_async(self, *, session_id) -> None: ... # closing twice must be safe + async def _get_status_async(self) -> SandboxStatus: ... # optional + async def _reset_async(self, *, expected_revision) -> None: ... # optional; returns when done +``` + +The capabilities name the runtimes (optionally with a `tool_name`, such as `powershell` for a runtime +called `windows-powershell`), the limits, and the **state kind**, which tells PyRIT whether work persists, +and so how to share the sandbox: + +| State kind | Meaning | What PyRIT does | +|------------|---------|-----------------| +| `environment` | State lives in the machine and survives closing a session | One shared session, which callers take turns using | +| `call` | Nothing persists between calls | No sessions; calls run concurrently; no file tools | + +Adapters raise these errors, so PyRIT knows what is safe to retry: + +| Error | Meaning | What PyRIT does | +|-------|---------|-----------------| +| `SandboxInputError` | The request was invalid, and nothing ran | Reports it to the caller, or to the model | +| `SandboxBusyError` | The sandbox can't start the work right now, and nothing ran | Retries opening a session until the deadline; reports a busy run | +| `SandboxSessionLostError` | The session is gone, and nothing ran | Reopens the session and retries once | +| `SandboxRevisionChangedError` | A reset was refused, because the revision changed | Reports it to the caller | +| anything else | The outcome is unknown | Closes the session and never retries | + +For every adapter, PyRIT validates the runtime, the size of the input and the timeout before anything +runs, and reports status, with its own session state, through `get_status_async`. For an `environment` +sandbox, it also: + +- opens the session on first use, closes it after ten idle minutes, and renews it before a session time + limit could cut a call short; +- lets one call at a time use the sandbox, first come first served, and waits up to five minutes for a turn; +- when a caller gives up, lets its running program finish, holding the sandbox so nothing runs beside it, + and starts nothing more for it, not even a run that was waiting out a busy sandbox; +- quarantines the sandbox when it can't confirm that a session closed, that a run's processes stopped, or + that a reset finished, until `release_async`, which retries the close, or `reset_async`; +- resets only after the running call finishes, closing the session first, and records the outcome. + +A `call` sandbox's calls run in their callers' tasks, so the adapter cleans up when a caller gives up. + +`FakeSandbox` is an in-memory sandbox that never runs code. It stands in for a real one when you test code +that uses a sandbox. To check an adapter itself, run the contract-test kit against a live sandbox you can +discard or reset: it writes files, resets the sandbox when it can, and runs real programs to check the +declared limits, error mapping, state, status, reset, and closing twice. + +```python +from pyrit._code_execution import SandboxProbes, check_sandbox_contract_async + +await check_sandbox_contract_async(sandbox=MySandbox(...), probes=SandboxProbes.python()) +``` diff --git a/doc/myst.yml b/doc/myst.yml index ac484e320c..e80e18faf8 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -155,6 +155,7 @@ project: - file: code/targets/10_2_playwright_target_copilot.ipynb - file: code/targets/10_3_websocket_copilot_target.ipynb - file: code/targets/11_message_normalizer.ipynb + - file: code/targets/12_sandboxed_tool_calls.md - file: code/targets/hack_a_prompt_target.ipynb - file: code/targets/open_ai_completions.ipynb - file: code/targets/github_copilot_target.ipynb diff --git a/pyrit/_code_execution/__init__.py b/pyrit/_code_execution/__init__.py index 84ed3c54a7..ae2fe98565 100644 --- a/pyrit/_code_execution/__init__.py +++ b/pyrit/_code_execution/__init__.py @@ -13,14 +13,58 @@ from pyrit.common.lazy_imports import get_lazy_dir, resolve_lazy_export if TYPE_CHECKING: - from pyrit._code_execution.client import SandboxClient, SandboxExecutionError + from pyrit._code_execution.client import ( + SandboxBusyError, + SandboxClient, + SandboxExecutionError, + SandboxInputError, + SandboxRevisionChangedError, + SandboxSessionLostError, + SandboxUnavailableError, + ) from pyrit._code_execution.docker_client import DockerRuntimeProfile, DockerSandboxClient + from pyrit._code_execution.fake_sandbox import FakeRun, FakeSandbox, FakeSandboxHook + from pyrit._code_execution.sandbox import ( + ProcessResult, + RuntimeProfile, + Sandbox, + SandboxCapabilities, + SandboxCondition, + SandboxResetRecord, + SandboxStateKind, + SandboxStatus, + SandboxView, + ) + from pyrit._code_execution.sandbox_contract import SandboxContractError, SandboxProbes, check_sandbox_contract_async + from pyrit._code_execution.sandbox_registry import SandboxRegistry, resolve_sandbox _LAZY_EXPORTS: dict[str, str] = { "SandboxClient": "pyrit._code_execution.client", "SandboxExecutionError": "pyrit._code_execution.client", + "SandboxInputError": "pyrit._code_execution.client", + "SandboxBusyError": "pyrit._code_execution.client", + "SandboxSessionLostError": "pyrit._code_execution.client", + "SandboxRevisionChangedError": "pyrit._code_execution.client", + "SandboxUnavailableError": "pyrit._code_execution.client", "DockerRuntimeProfile": "pyrit._code_execution.docker_client", "DockerSandboxClient": "pyrit._code_execution.docker_client", + "FakeRun": "pyrit._code_execution.fake_sandbox", + "FakeSandbox": "pyrit._code_execution.fake_sandbox", + "FakeSandboxHook": "pyrit._code_execution.fake_sandbox", + "ProcessResult": "pyrit._code_execution.sandbox", + "RuntimeProfile": "pyrit._code_execution.sandbox", + "Sandbox": "pyrit._code_execution.sandbox", + "SandboxCapabilities": "pyrit._code_execution.sandbox", + "SandboxCondition": "pyrit._code_execution.sandbox", + "SandboxResetRecord": "pyrit._code_execution.sandbox", + "SandboxStateKind": "pyrit._code_execution.sandbox", + "SandboxStatus": "pyrit._code_execution.sandbox", + "SandboxView": "pyrit._code_execution.sandbox", + "SandboxContractError": "pyrit._code_execution.sandbox_contract", + "SandboxProbes": "pyrit._code_execution.sandbox_contract", + "check_sandbox_contract_async": "pyrit._code_execution.sandbox_contract", + "SandboxRegistry": "pyrit._code_execution.sandbox_registry", + "resolve_sandbox": "pyrit._code_execution.sandbox_registry", } __all__ = list(_LAZY_EXPORTS) diff --git a/pyrit/_code_execution/client.py b/pyrit/_code_execution/client.py index ff1fdf51f8..d38a127d6b 100644 --- a/pyrit/_code_execution/client.py +++ b/pyrit/_code_execution/client.py @@ -22,14 +22,35 @@ class SandboxExecutionError(Exception): """ +class SandboxInputError(ValueError): + """The request was invalid, so nothing ran. The caller, or a model, can correct it.""" + + +class SandboxBusyError(SandboxExecutionError): + """The sandbox could not start the work right now, and nothing ran.""" + + +class SandboxSessionLostError(SandboxExecutionError): + """The session ended or expired before the work started, so nothing ran.""" + + +class SandboxUnavailableError(SandboxExecutionError): + """PyRIT refused the work, and nothing ran: the sandbox is closed, or quarantined until an operator acts.""" + + +class SandboxRevisionChangedError(SandboxExecutionError): + """A reset was refused because the sandbox's revision is not the one the caller expected.""" + + @runtime_checkable class SandboxClient(Protocol): """ Connect to a caller-configured backend that runs code in isolation. - Each invocation runs in a fresh environment. The client requests execution and cleanup, - and waits for cleanup before a cancelled call returns. It does not set up the backend - service, build images, or retain environments between calls. + A sandbox may keep state between calls: files a program writes can still be there for the + next call, until the sandbox is reset. Clients built on the ``Sandbox`` base class report + which kind they are in their capabilities. The client requests execution and cleanup, and does + not leave a cancelled call's work behind. It does not set up the backend service or build images. A runtime profile is a trusted name the client maps to its own configuration; the program cannot choose an image or a command. The caller supplies the running backend and trusted runtimes, and decides how to use the returned results. @@ -47,7 +68,7 @@ async def execute_async( self, *, program: str, runtime_profile_name: _RuntimeProfileName, invocations: tuple[_ProgramInvocation, ...] ) -> _SandboxRun: """ - Run each invocation of the program once, in order, in a fresh isolated environment. + Run each invocation of the program once, in order, in an isolated environment. Args: program (str): The code to run, without extracting it from surrounding prose. diff --git a/pyrit/_code_execution/docker_client.py b/pyrit/_code_execution/docker_client.py index 435d5c8adf..4eb09a1199 100644 --- a/pyrit/_code_execution/docker_client.py +++ b/pyrit/_code_execution/docker_client.py @@ -20,14 +20,21 @@ from typing import TYPE_CHECKING, TypeVar from pyrit._code_execution.client import SandboxExecutionError +from pyrit._code_execution.sandbox import ( + ProcessResult, + RuntimeProfile, + Sandbox, + SandboxCapabilities, + SandboxStateKind, +) from pyrit.common.task_utils import gather_with_cleanup_async from pyrit.models import ComponentIdentifier -from pyrit.models.code_execution import _ProgramExecutionEvent, _SandboxRun +from pyrit.models.code_execution import _ProgramInvocation if TYPE_CHECKING: from collections.abc import Awaitable, Mapping - from pyrit.models.code_execution import _ProgramInvocation, _RuntimeProfileName + from pyrit.models.code_execution import _RuntimeProfileName logger = logging.getLogger(__name__) @@ -142,10 +149,11 @@ class _InvocationResult: timed_out: bool = False -class DockerSandboxClient: +class DockerSandboxClient(Sandbox): """ Run each invocation in a disposable container on a caller-provided Docker daemon. + This is the example ``Sandbox`` adapter: a ``call`` sandbox, where nothing persists between calls. Profiles require pre-pulled, pinned images with no declared volumes. The daemon must support cgroup memory, swap, CPU, and process limits; unsupported backends are rejected before execution. Containers have no network or privileges, run as an unprivileged user, and have memory, CPU, @@ -163,6 +171,12 @@ class DockerSandboxClient: _READ_CHUNK_BYTES = 1 << 16 _CONTROL_TIMEOUT_SECONDS = 30.0 + # The program and its input travel through files and pipes; its arguments go on a command line. + _MAX_INPUT_BYTES = 64 << 20 + _MAX_ARGUMENTS_BYTES = 16_384 + # Backend checks, a stalled client and container removal each take up to the control timeout. + _EXECUTE_GRACE_SECONDS = 180.0 + _BACKEND_CHECK_SECONDS = 60.0 def __init__( self, @@ -200,6 +214,7 @@ def __init__( raise ValueError("timeout_seconds, cpus, pids_limit and max_output_bytes must be positive.") if not re.fullmatch(r"[1-9][0-9]*[bkmg]?", memory): raise ValueError(f"Memory limit {memory!r} must look like 256m or 1g.") + super().__init__() self._profiles = dict(profiles) self._docker = docker_executable self._timeout_seconds = timeout_seconds @@ -208,8 +223,10 @@ def __init__( self._pids_limit = pids_limit self._max_output_bytes = max_output_bytes self._temp_root = Path(tempfile.gettempdir()) + self._backend_checked_at: dict[str, float] = {} + self.get_capabilities() - def get_identifier(self) -> ComponentIdentifier: + def _build_identifier(self) -> ComponentIdentifier: """ Return the profiles and limits. @@ -236,42 +253,58 @@ def get_identifier(self) -> ComponentIdentifier: }, ) - def get_runtime_profile_names(self) -> frozenset[_RuntimeProfileName]: + def _get_capabilities(self) -> SandboxCapabilities: """ - Return the configured runtime profile names. + Describe the configured runtimes and limits of a sandbox that keeps nothing between calls. Returns: - frozenset[_RuntimeProfileName]: Names that select the configured runtimes. - """ - return frozenset(self._profiles) + SandboxCapabilities: One runtime per profile; the configured timeout is the default and the limit. + """ + return SandboxCapabilities( + runtime_profiles=tuple(RuntimeProfile(name=name) for name in sorted(self._profiles)), + state_kind=SandboxStateKind.CALL, + description="a disposable Docker container with no network", + max_input_bytes=self._MAX_INPUT_BYTES, + max_arguments_bytes=self._MAX_ARGUMENTS_BYTES, + max_output_bytes=self._max_output_bytes, + max_timeout_seconds=self._timeout_seconds, + default_timeout_seconds=self._timeout_seconds, + ) - async def execute_async( - self, *, program: str, runtime_profile_name: _RuntimeProfileName, invocations: tuple[_ProgramInvocation, ...] - ) -> _SandboxRun: + async def _execute_async( + self, + *, + session_id: str | None, + runtime_profile_name: str, + program: str, + arguments: tuple[str, ...], + stdin: str | None, + timeout_seconds: float, + ) -> ProcessResult: """ - Run each invocation in a fresh container, in order. + Run the program once in a fresh container, then remove the container and the program file. Args: + session_id (str | None): Unused; this sandbox has no sessions. + runtime_profile_name (str): A key from ``profiles``; it selects a trusted image and command. program (str): The program text, written to a read-only file in the container. - runtime_profile_name (_RuntimeProfileName): A key from ``profiles``, also returned by - ``get_runtime_profile_names``. The key selects a trusted image and command. - invocations (tuple[_ProgramInvocation, ...]): The arguments and input of each run. + arguments (tuple[str, ...]): The program's command-line arguments. + stdin (str | None): The program's standard input, if any. + timeout_seconds (float): The time limit of the run. Returns: - _SandboxRun: One event per invocation that ran. If the sandbox fails after some - invocations ran, the run holds those events and the reason it stopped. + ProcessResult: What the run did. If the container could not be removed, cleanup is unconfirmed. Raises: - ValueError: If the runtime profile is not configured or there are no invocations. SandboxExecutionError: If the backend cannot enforce the limits, the image declares - volumes, or no invocation could be run. - """ - profile = self._profiles.get(runtime_profile_name) - if profile is None: - raise ValueError(f"Runtime profile name {runtime_profile_name!r} is not configured.") - if not invocations: - raise ValueError("At least one program invocation is required.") - await self._validate_backend_async(profile=profile) + volumes, or the container could not be run. + """ + del session_id + profile = self._profiles[runtime_profile_name] + checked_at = self._backend_checked_at.get(profile.image) + if checked_at is None or time.monotonic() - checked_at >= self._BACKEND_CHECK_SECONDS: + await self._validate_backend_async(profile=profile) + self._backend_checked_at[profile.image] = time.monotonic() workspace_dir = self._temp_root / f"pyrit-program-{uuid.uuid4().hex}" program_dir = workspace_dir / "program" program_path = program_dir / profile.program_filename @@ -281,27 +314,12 @@ async def execute_async( self._write_program, workspace_dir=workspace_dir, program_path=program_path, program=program ) ) - events: list[_ProgramExecutionEvent] = [] - for index, invocation in enumerate(invocations): - try: - event, cleanup_warning = await self._run_invocation_async( - invocation_index=index, - runtime_profile_name=runtime_profile_name, - profile=profile, - program_dir=program_dir, - invocation=invocation, - ) - except SandboxExecutionError as error: - if not events: - raise - return _SandboxRun(events=tuple(events), reasons=(f"sandbox error at invocation {index}: {error}",)) - events.append(event) - if cleanup_warning is not None: - # The environment may still be running, so no further invocation starts beside it. - remaining = len(invocations) - len(events) - reasons = (f"stopped after invocation {index}: {cleanup_warning}",) if remaining else () - return _SandboxRun(events=tuple(events), reasons=reasons, warnings=(cleanup_warning,)) - return _SandboxRun(events=tuple(events)) + return await self._run_invocation_async( + profile=profile, + program_dir=program_dir, + invocation=_ProgramInvocation(arguments=arguments, stdin=stdin), + timeout_seconds=timeout_seconds, + ) finally: await _finish_work_async( asyncio.to_thread(self._remove_workspace, workspace_dir=workspace_dir, program_path=program_path) @@ -358,18 +376,17 @@ def _remove_workspace(*, workspace_dir: Path, program_path: Path) -> None: async def _run_invocation_async( self, *, - invocation_index: int, - runtime_profile_name: _RuntimeProfileName, profile: DockerRuntimeProfile, program_dir: Path, invocation: _ProgramInvocation, - ) -> tuple[_ProgramExecutionEvent, str | None]: + timeout_seconds: float, + ) -> ProcessResult: """ Run one invocation in a new container and remove the container afterwards. Returns: - tuple[_ProgramExecutionEvent, str | None]: What the invocation did, and a warning when - the container could not be removed. + ProcessResult: What the invocation did; cleanup is unconfirmed, with a warning, when the + container could not be removed. Raises: SandboxExecutionError: If Docker cannot start or inspect the container, or the @@ -381,7 +398,7 @@ async def _run_invocation_async( name=name, profile=profile, program_dir=program_dir, resolved_command=resolved_command ) started = time.monotonic() - deadline = started + self._timeout_seconds + deadline = started + timeout_seconds startup = asyncio.create_task(self._start_client_async(argv=argv)) cleanup_warning: str | None = None try: @@ -397,9 +414,7 @@ async def _run_invocation_async( finally: cleanup_warning = await _finish_work_async(self._cleanup_invocation_async(startup=startup, name=name)) output, container = result.output, result.container - event = _ProgramExecutionEvent( - invocation_index=invocation_index, - runtime_profile_name=runtime_profile_name, + return ProcessResult( runtime_image_digest=profile.image_digest, resolved_command=resolved_command, exit_code=None if (result.timed_out or container.oom_killed) else container.exit_code, @@ -410,8 +425,9 @@ async def _run_invocation_async( timed_out=result.timed_out, resource_limit_exceeded=container.oom_killed and not result.timed_out, duration_ms=duration_ms, + warnings=(cleanup_warning,) if cleanup_warning is not None else (), + cleanup_confirmed=cleanup_warning is None, ) - return event, cleanup_warning async def _start_client_async(self, *, argv: list[str]) -> asyncio.subprocess.Process: """ diff --git a/pyrit/_code_execution/fake_sandbox.py b/pyrit/_code_execution/fake_sandbox.py new file mode 100644 index 0000000000..5e2f833fe0 --- /dev/null +++ b/pyrit/_code_execution/fake_sandbox.py @@ -0,0 +1,196 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""An in-memory ``Sandbox`` for tests and examples. It never runs code.""" + +from __future__ import annotations + +import asyncio +import inspect +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING, ClassVar + +from pyrit._code_execution.client import SandboxRevisionChangedError, SandboxSessionLostError +from pyrit._code_execution.sandbox import ( + ProcessResult, + RuntimeProfile, + Sandbox, + SandboxCapabilities, + SandboxCondition, + SandboxStateKind, + SandboxStatus, +) +from pyrit.models import ComponentIdentifier + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + + +@dataclass(frozen=True) +class FakeRun: + """One run a ``FakeSandbox`` was asked to do.""" + + session_id: str | None + runtime_profile_name: str + program: str + arguments: tuple[str, ...] + stdin: str | None + timeout_seconds: float + + +class FakeSandboxHook(str, Enum): + """The adapter hook a ``FakeSandbox`` fault applies to.""" + + OPEN = "open" + EXECUTE = "execute" + CLOSE = "close" + STATUS = "status" + RESET = "reset" + + +class FakeSandbox(Sandbox): + """ + An in-memory sandbox for tests and examples. It never runs code. + + A handler decides what each run returns; by default every run exits 0 with no output. The fake keeps + real session rules (a run in a closed or expired session is lost), a ``revision`` that resets check, + a ``state`` dictionary that handlers may use and resets clear, and a record of every run. + ``fail_next`` makes a hook raise, and ``gate`` holds runs until a test opens it. + """ + + DEFAULT_CAPABILITIES: ClassVar[SandboxCapabilities] = SandboxCapabilities( + runtime_profiles=( + RuntimeProfile(name="python", description="Python 3"), + RuntimeProfile(name="bash", description="bash"), + ), + state_kind=SandboxStateKind.ENVIRONMENT, + description="a fake sandbox that runs nothing", + supports_reset=True, + file_runtime_profile_name="python", + ) + + def __init__( + self, + *, + name: str = "fake", + capabilities: SandboxCapabilities | None = None, + handler: Callable[[FakeRun], ProcessResult | Awaitable[ProcessResult]] | None = None, + acquire_timeout_seconds: float = Sandbox.DEFAULT_ACQUIRE_TIMEOUT_SECONDS, + idle_timeout_seconds: float = Sandbox.DEFAULT_IDLE_TIMEOUT_SECONDS, + ) -> None: + """ + Initialize the fake. + + Args: + name (str): Distinguishes fakes in identifiers and registries. Defaults to ``"fake"``. + capabilities (SandboxCapabilities | None): What the fake offers. Defaults to + ``DEFAULT_CAPABILITIES``: Python and bash in a resettable ``environment`` sandbox. + handler (Callable[[FakeRun], ProcessResult | Awaitable[ProcessResult]] | None): Decides each run's + result. Defaults to exit code 0 with no output. + acquire_timeout_seconds (float): Passed to ``Sandbox``. + idle_timeout_seconds (float): Passed to ``Sandbox``. + """ + super().__init__(acquire_timeout_seconds=acquire_timeout_seconds, idle_timeout_seconds=idle_timeout_seconds) + self._name = name + self._fake_capabilities = capabilities or self.DEFAULT_CAPABILITIES + self._handler = handler or (lambda run: ProcessResult(exit_code=0)) + self._faults: dict[FakeSandboxHook, list[BaseException]] = {hook: [] for hook in FakeSandboxHook} + self._session_count = 0 + self.runs: list[FakeRun] = [] + self.state: dict[str, object] = {} + self.revision = "fake-revision-1" + self.condition = SandboxCondition.READY + self.open_sessions: set[str] = set() + self.closed_sessions: list[str] = [] + self.reset_count = 0 + self.gate: asyncio.Event | None = None + self.run_started = asyncio.Event() + + def fail_next(self, *, hook: FakeSandboxHook, error: BaseException, times: int = 1) -> None: + """ + Make the next calls to a hook raise an error. + + Args: + hook (FakeSandboxHook): The hook that fails. + error (BaseException): The error it raises. + times (int): How many calls fail. Defaults to 1. + """ + self._faults[hook].extend([error] * times) + + def expire_sessions(self) -> None: + """End every open session, as an infrastructure that expires sessions would.""" + self.open_sessions.clear() + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of( + self, params={"name": self._name, "state_kind": self._fake_capabilities.state_kind.value} + ) + + def _get_capabilities(self) -> SandboxCapabilities: + return self._fake_capabilities + + async def _execute_async( + self, + *, + session_id: str | None, + runtime_profile_name: str, + program: str, + arguments: tuple[str, ...], + stdin: str | None, + timeout_seconds: float, + ) -> ProcessResult: + self._raise_fault(FakeSandboxHook.EXECUTE) + if self._fake_capabilities.state_kind is SandboxStateKind.ENVIRONMENT and session_id not in self.open_sessions: + raise SandboxSessionLostError(f"Session {session_id} is not open; nothing ran.") + run = FakeRun( + session_id=session_id, + runtime_profile_name=runtime_profile_name, + program=program, + arguments=arguments, + stdin=stdin, + timeout_seconds=timeout_seconds, + ) + self.runs.append(run) + self.run_started.set() + if self.gate is not None: + await self.gate.wait() + result = self._handler(run) + if inspect.isawaitable(result): + result = await result + if not isinstance(result, ProcessResult): + raise TypeError(f"A FakeSandbox handler must return a ProcessResult, not {type(result).__name__}.") + return result + + async def _open_session_async(self, *, owner: str) -> str: + self._raise_fault(FakeSandboxHook.OPEN) + self._session_count += 1 + session_id = f"fake-session-{self._session_count}" + self.open_sessions.add(session_id) + return session_id + + async def _close_session_async(self, *, session_id: str) -> None: + self._raise_fault(FakeSandboxHook.CLOSE) + self.open_sessions.discard(session_id) + self.closed_sessions.append(session_id) + + async def _get_status_async(self) -> SandboxStatus: + self._raise_fault(FakeSandboxHook.STATUS) + return SandboxStatus(condition=self.condition, revision=self.revision, details={"fake_sandbox": self._name}) + + async def _reset_async(self, *, expected_revision: str | None) -> None: + self._raise_fault(FakeSandboxHook.RESET) + if expected_revision is not None and expected_revision != self.revision: + raise SandboxRevisionChangedError(f"The revision is {self.revision}, not {expected_revision}.") + self.state.clear() + self.reset_count += 1 + + def _raise_fault(self, hook: FakeSandboxHook) -> None: + """ + Raise the next fault queued for a hook, if any. + + Raises: + BaseException: The queued fault. + """ + if self._faults[hook]: + raise self._faults[hook].pop(0) diff --git a/pyrit/_code_execution/sandbox.py b/pyrit/_code_execution/sandbox.py new file mode 100644 index 0000000000..f5caea767a --- /dev/null +++ b/pyrit/_code_execution/sandbox.py @@ -0,0 +1,1360 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +The experimental ``Sandbox`` base class: one interface for any infrastructure that runs code. + +An adapter subclasses ``Sandbox`` and implements a few hooks that translate PyRIT's calls into its +infrastructure's API. This class enforces the rules every sandbox follows, so callers get the same +behavior from any of them: sharing, waiting, retries, renewal, cancellation, idle close, reset, and +evidence. +""" + +from __future__ import annotations + +import asyncio +import logging +import time +import uuid +from abc import ABC, abstractmethod +from dataclasses import dataclass +from datetime import UTC, datetime +from enum import Enum +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +from pyrit._code_execution.client import ( + SandboxBusyError, + SandboxExecutionError, + SandboxInputError, + SandboxRevisionChangedError, + SandboxSessionLostError, + SandboxUnavailableError, +) +from pyrit.models import Identifiable +from pyrit.models.code_execution import ( + _ProgramExecutionEvent, + _ProgramInvocation, + _RuntimeProfileName, + _SandboxRun, +) + +if TYPE_CHECKING: + from collections.abc import Awaitable, Coroutine, Sequence + +logger = logging.getLogger(__name__) + +_T = TypeVar("_T") + + +class SandboxStateKind(str, Enum): + """ + Whether a sandbox keeps state between calls, which decides how PyRIT shares it. + + ``ENVIRONMENT``: state lives in the machine and survives closing a session, so callers share one + session and take turns. ``CALL``: nothing persists between calls, so there are no sessions and + calls run concurrently. + """ + + ENVIRONMENT = "environment" + CALL = "call" + + +class SandboxCondition(str, Enum): + """Whether a sandbox can be used now: ready, unavailable, or quarantined until an operator acts.""" + + READY = "ready" + UNAVAILABLE = "unavailable" + QUARANTINED = "quarantined" + + +class RuntimeProfile(BaseModel): + """ + One trusted way a sandbox runs program text, such as Python or PowerShell. + + ``name`` is what callers pass; the adapter maps it to its own configuration. ``tool_name`` + optionally names the runtime for model tools (``run_``), such as ``powershell`` for a + profile named ``windows-powershell``. ``description`` tells a model what the runtime is, such as + "Python 3.12". + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + name: _RuntimeProfileName + tool_name: str | None = Field(default=None, pattern=r"^[A-Za-z0-9_]{1,60}$") + description: str = Field(default="", max_length=200) + + +class SandboxCapabilities(BaseModel): + """ + What a sandbox offers, and its limits. They stay the same for the sandbox's lifetime. + + Limits apply to each call. ``max_input_bytes`` bounds the UTF-8 size of the program text, its + standard input and its arguments together; ``max_arguments_bytes``, when set, also bounds the + arguments alone, for infrastructures that pass them on a command line. ``max_output_bytes`` is the + most output of each stream the sandbox returns before marking it truncated. Timeouts are in seconds. + ``max_session_seconds`` + is set when the infrastructure ends sessions after a fixed time, so PyRIT can renew a session + before a call could run past it. ``file_runtime_profile_name`` names a Python 3 runtime that file + tools run in. ``description`` tells a model where its code runs. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + runtime_profiles: tuple[RuntimeProfile, ...] = Field(min_length=1) + state_kind: SandboxStateKind + description: str = Field(default="an isolated sandbox", min_length=1, max_length=500) + supports_reset: bool = False + file_runtime_profile_name: _RuntimeProfileName | None = None + max_input_bytes: int = Field(default=65_536, ge=1) + max_arguments_bytes: int | None = Field(default=None, ge=1) + max_output_bytes: int = Field(default=32_768, ge=1) + max_timeout_seconds: float = Field(default=120.0, gt=0) + default_timeout_seconds: float = Field(default=30.0, gt=0) + max_session_seconds: float | None = Field(default=None, gt=0) + + @model_validator(mode="after") + def _validate_consistency(self) -> SandboxCapabilities: + """ + Reject capabilities that contradict each other. + + Returns: + SandboxCapabilities: The validated capabilities. + + Raises: + ValueError: If names repeat, a default exceeds its limit, or a feature needs persistent state. + """ + names = [profile.name for profile in self.runtime_profiles] + if len(set(names)) != len(names): + raise ValueError("Runtime profile names must be unique.") + if self.default_timeout_seconds > self.max_timeout_seconds: + raise ValueError("default_timeout_seconds cannot exceed max_timeout_seconds.") + if self.file_runtime_profile_name is not None and self.file_runtime_profile_name not in names: + raise ValueError("file_runtime_profile_name must name one of the runtime profiles.") + stateful = (self.file_runtime_profile_name, self.max_session_seconds, self.supports_reset or None) + if self.state_kind is SandboxStateKind.CALL and any(value is not None for value in stateful): + raise ValueError("File tools, session limits and reset need an environment sandbox.") + return self + + def get_runtime_profile(self, name: str) -> RuntimeProfile: + """ + Return the runtime profile with this name. + + Args: + name (str): A runtime profile name. + + Returns: + RuntimeProfile: The matching profile. + + Raises: + SandboxInputError: If no runtime profile has this name. + """ + for profile in self.runtime_profiles: + if profile.name == name: + return profile + available = sorted(profile.name for profile in self.runtime_profiles) + raise SandboxInputError(f"Runtime profile {name!r} is not offered by this sandbox; available: {available}.") + + +class SandboxStatus(BaseModel): + """ + What the infrastructure reports about a sandbox. + + ``revision`` names its current baseline or configuration, which a reset can pin. ``owner`` is who + holds its session, when the infrastructure knows. ``details`` carries nonsecret identifiers, such as + those that find the infrastructure's own records of the sandbox. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + condition: SandboxCondition = SandboxCondition.READY + reason: str | None = None + revision: str | None = None + owner: str | None = None + details: dict[str, str] = Field(default_factory=dict) + + +class ProcessResult(BaseModel): + """ + What one program run did, as an adapter reports it. + + ``exit_code`` is None when the program did not exit on its own, for example because it timed out. + Each stream is marked truncated when the sandbox cut it. ``duration_ms`` defaults to the time PyRIT + measured. ``execution_id`` is the infrastructure's identifier for the run, if it has one. + ``runtime_image_digest`` and ``resolved_command`` are optional provenance. ``warnings`` report + problems that do not invalidate the result. ``cleanup_confirmed`` is False when the sandbox could not + confirm that the run's processes or resources were removed; PyRIT then starts nothing beside them: no + further invocation of the request, and in an ``environment`` sandbox no further call, since the sandbox + is quarantined until it is released or reset. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + exit_code: int | None + stdout: str = "" + stderr: str = "" + stdout_truncated: bool = False + stderr_truncated: bool = False + timed_out: bool = False + resource_limit_exceeded: bool = False + duration_ms: int | None = Field(default=None, ge=0) + execution_id: str | None = Field(default=None, min_length=1) + runtime_image_digest: str | None = Field(default=None, min_length=1) + resolved_command: tuple[str, ...] | None = Field(default=None, min_length=1) + warnings: tuple[str, ...] = () + cleanup_confirmed: bool = True + + @model_validator(mode="after") + def _validate_exit_state(self) -> ProcessResult: + """ + Keep the exit state consistent with how the run ended. + + Returns: + ProcessResult: The validated result. + + Raises: + ValueError: If a run that timed out also reports an exit code of its own. + """ + if self.timed_out and self.exit_code is not None: + raise ValueError("A timed-out run did not exit on its own and has no exit code.") + return self + + +class SandboxResetRecord(BaseModel): + """The latest reset: when it started and finished, and whether it succeeded.""" + + model_config = ConfigDict(frozen=True, extra="forbid") + + started_at: datetime + finished_at: datetime | None = None + succeeded: bool | None = None + error: str | None = None + + +class SandboxView(BaseModel): + """ + A sandbox as PyRIT sees it: the infrastructure's status plus PyRIT's own session state. + + ``status`` is the last status read when ``status_is_current`` is False, because a call held the + sandbox. ``condition`` is ``QUARANTINED`` while PyRIT refuses calls because it could not confirm a + session closed or a reset finished, with the reason in ``quarantine_reason``; otherwise it is the + status's condition. ``closed`` is True once ``close_async`` has been called. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + status: SandboxStatus + status_is_current: bool + condition: SandboxCondition + quarantine_reason: str | None = None + closed: bool = False + session_open: bool + session_age_seconds: float | None = None + idle_seconds: float | None = None + busy: bool + resetting: bool + last_reset: SandboxResetRecord | None = None + + +_CALLER_GAVE_UP_REASON = "the caller gave up" + + +class _CallerGaveUpError(SandboxUnavailableError): + """The caller gave up before a run started, so PyRIT never started it.""" + + def __init__(self) -> None: + super().__init__("The caller gave up before the run started; nothing ran.") + + +@dataclass +class _ExecutionRequest: + program: str + runtime_profile_name: str + invocations: tuple[_ProgramInvocation, ...] + timeout_seconds: float + caller: asyncio.Future[Any] | None = None + """What the caller awaits, in an ``environment`` sandbox. Cancelling the caller cancels it at once.""" + + def abandoned(self) -> bool: + """ + Whether the caller gave up, so no more work should start for it. + + Returns: + bool: True if the caller stopped waiting. + """ + return self.caller is not None and self.caller.cancelled() + + async def sleep_unless_abandoned_async(self, seconds: float) -> None: + """Wait, waking early if the caller gives up.""" + if self.caller is None: + await asyncio.sleep(seconds) + else: + await asyncio.wait({self.caller}, timeout=seconds) + + +def _log_abandoned_outcome(task: asyncio.Task[Any]) -> None: + """Retrieve the outcome of work whose caller gave up, so a failure is logged, not lost.""" + if task.cancelled(): + return + error = task.exception() + if isinstance(error, _CallerGaveUpError): + logger.info("A sandbox call did not run: %s", error) + elif error is not None: + logger.warning("A sandbox operation whose caller gave up failed: %s", error) + elif isinstance(result := task.result(), _SandboxRun) and result.reasons: + gave_up = all(reason.endswith(_CALLER_GAVE_UP_REASON) for reason in result.reasons) + logger.log( + logging.INFO if gave_up else logging.WARNING, + "A sandbox call whose caller gave up stopped early: %s", + "; ".join(result.reasons), + ) + + +def _cancellation_requested() -> bool: + """ + Whether the current task was asked to stop, as opposed to an adapter raising ``CancelledError`` by itself. + + Like ``asyncio.timeout``, this reads the task's count of pending cancellations, so a task that swallowed + an earlier cancellation without ``uncancel()`` still counts as cancelled. + + Returns: + bool: True if the task itself is being cancelled. + """ + task = asyncio.current_task() + return task is None or task.cancelling() > 0 + + +class Sandbox(Identifiable, ABC): + """ + Base class for sandboxes: a subclass adapts one infrastructure, and this class enforces the rules. + + Adapters implement ``_build_identifier`` (static configuration only, never session ids or secrets), + ``_get_capabilities`` and ``_execute_async``. ``environment`` sandboxes also implement + ``_open_session_async`` and ``_close_session_async`` (closing twice must be safe), and may implement + ``_get_status_async`` and ``_reset_async``. Adapters raise ``SandboxInputError`` for bad input, + ``SandboxBusyError`` when work can't start right now, ``SandboxSessionLostError`` when the session is + gone and nothing ran, and ``SandboxRevisionChangedError`` when a reset is refused. Any other failure, + including a ``CancelledError`` a hook raises by itself, is uncertain: it is never retried and reaches + callers as a ``SandboxExecutionError``. + + An ``environment`` sandbox has one shared session that callers take turns using. A lock admits one + call at a time, first come first served, within one deadline for waiting and retries. The first call + opens the session; it closes after ``idle_timeout_seconds`` without use and at ``release_async`` or + ``close_async``, and it is renewed before ``max_session_seconds`` could cut a call short. Runs, session + closes and resets happen in tasks this class owns: a caller that gives up returns at once, while the + work finishes and holds the lock until it does. Runs that have not started when their caller gives up, + such as one waiting out a busy sandbox, never start. A busy open is retried with backoff, a lost + session is reopened and the call retried once, and after an uncertain failure the session is closed + before the next call. If a close or a reset can't be confirmed, the sandbox is quarantined: calls are + refused until ``release_async``, which retries the close, or ``reset_async``. ``close_async`` is final. + + A ``call`` sandbox shares nothing between calls, so its calls run concurrently in the caller's task, + and its adapter cleans up when a call is cancelled. + + Each sandbox should be represented by one ``Sandbox`` object, used from one event loop, in one process; + ``SandboxRegistry`` helps. + """ + + DEFAULT_ACQUIRE_TIMEOUT_SECONDS: ClassVar[float] = 300.0 + DEFAULT_IDLE_TIMEOUT_SECONDS: ClassVar[float] = 600.0 + _RENEWAL_MARGIN_SECONDS: ClassVar[float] = 60.0 + _EXECUTE_GRACE_SECONDS: ClassVar[float] = 60.0 + _HOOK_TIMEOUT_SECONDS: ClassVar[float] = 120.0 + _RESET_TIMEOUT_SECONDS: ClassVar[float] = 1_800.0 + _STATUS_LOCK_WAIT_SECONDS: ClassVar[float] = 1.0 + _BUSY_RETRY_INITIAL_SECONDS: ClassVar[float] = 1.0 + _BUSY_RETRY_MAX_SECONDS: ClassVar[float] = 15.0 + + def __init__( + self, + *, + acquire_timeout_seconds: float = DEFAULT_ACQUIRE_TIMEOUT_SECONDS, + idle_timeout_seconds: float = DEFAULT_IDLE_TIMEOUT_SECONDS, + owner: str | None = None, + ) -> None: + """ + Initialize the shared state that enforces the sandbox rules. + + Args: + acquire_timeout_seconds (float): How long a call may wait for its turn and for a busy + sandbox, in total. Defaults to 300 seconds. + idle_timeout_seconds (float): How long an unused session stays open. Defaults to 600 seconds. + owner (str | None): The name sessions are opened under. Defaults to a random + ``pyrit-`` name for this object. + + Raises: + ValueError: If a timeout is not positive or the owner is empty. + """ + if acquire_timeout_seconds <= 0 or idle_timeout_seconds <= 0: + raise ValueError("acquire_timeout_seconds and idle_timeout_seconds must be positive.") + if owner is not None and not owner.strip(): + raise ValueError("owner must not be empty.") + self._acquire_timeout_seconds = acquire_timeout_seconds + self._idle_timeout_seconds = idle_timeout_seconds + self._owner = owner or f"pyrit-{uuid.uuid4().hex[:12]}" + self._capabilities: SandboxCapabilities | None = None + self._lock = asyncio.Lock() + self._session_id: str | None = None + self._session_opened_at: float | None = None + self._last_used_at: float | None = None + self._uses = 0 + self._closed = False + self._quarantine_reason: str | None = None + self._unconfirmed_session_ids: list[str] = [] + self._resetting = False + self._last_reset: SandboxResetRecord | None = None + self._last_status: SandboxStatus | None = None + self._idle_handle: asyncio.TimerHandle | None = None + self._tasks: set[asyncio.Task[Any]] = set() + + # ---- public API ---------------------------------------------------------------------------- + + def get_capabilities(self) -> SandboxCapabilities: + """ + Return what this sandbox offers and its limits. + + Returns: + SandboxCapabilities: The adapter's capabilities, read once. + + Raises: + TypeError: If the adapter declares a feature without implementing its hooks. + """ + if self._capabilities is None: + capabilities = self._get_capabilities() + self._validate_hooks(capabilities=capabilities) + self._capabilities = capabilities + return self._capabilities + + def get_runtime_profile_names(self) -> frozenset[str]: + """ + Return the runtime profile names this sandbox offers. + + Returns: + frozenset[str]: Names that select the sandbox's runtimes. + """ + return frozenset(profile.name for profile in self.get_capabilities().runtime_profiles) + + def validate_request( + self, + *, + program: str, + runtime_profile_name: str, + invocations: Sequence[_ProgramInvocation], + timeout_seconds: float | None = None, + ) -> None: + """ + Check a request against this sandbox's runtimes and limits, without running anything. + + Args: + program (str): The program text. + runtime_profile_name (str): The runtime to run it in. + invocations (Sequence[_ProgramInvocation]): The arguments and input of each run. + timeout_seconds (float | None): The time limit of each run. Defaults to the sandbox's default. + + Raises: + SandboxInputError: If the request does not fit this sandbox. + """ + capabilities = self.get_capabilities() + capabilities.get_runtime_profile(runtime_profile_name) + if not invocations: + raise SandboxInputError("At least one program invocation is required.") + program_bytes = self._utf8_size(program, field="program") + for invocation in invocations: + arguments_bytes = sum(self._utf8_size(argument, field="argument") for argument in invocation.arguments) + if capabilities.max_arguments_bytes is not None and arguments_bytes > capabilities.max_arguments_bytes: + raise SandboxInputError( + f"The arguments take {arguments_bytes} bytes; this sandbox accepts at most " + f"{capabilities.max_arguments_bytes}. Pass long data through standard input instead." + ) + size = program_bytes + arguments_bytes + self._utf8_size(invocation.stdin or "", field="stdin") + if size > capabilities.max_input_bytes: + raise SandboxInputError( + f"The program, its input and its arguments take {size} bytes; " + f"this sandbox accepts at most {capabilities.max_input_bytes}." + ) + self._resolve_timeout(timeout_seconds) + + async def execute_async( + self, + *, + program: str, + runtime_profile_name: _RuntimeProfileName, + invocations: tuple[_ProgramInvocation, ...] | None = None, + timeout_seconds: float | None = None, + ) -> _SandboxRun: + """ + Run each invocation of the program once, in order. + + In an ``environment`` sandbox the runs share the session, so they see what earlier calls left. + + Args: + program (str): The program text, run verbatim. + runtime_profile_name (_RuntimeProfileName): One of ``get_runtime_profile_names``. + invocations (tuple[_ProgramInvocation, ...] | None): The arguments and input of each run. + Defaults to one run with neither. + timeout_seconds (float | None): The time limit of each run. Defaults to the sandbox's default. + + Returns: + _SandboxRun: One event per run that happened. If the sandbox fails after some runs, the + result holds those events and the reason it stopped. + + Raises: + SandboxInputError: If the request does not fit this sandbox; nothing ran. + SandboxUnavailableError: If the sandbox is closed or quarantined; nothing ran. + SandboxExecutionError: If the sandbox could not run the first invocation. + """ + invocations = invocations if invocations is not None else (_ProgramInvocation(),) + self.validate_request( + program=program, + runtime_profile_name=runtime_profile_name, + invocations=invocations, + timeout_seconds=timeout_seconds, + ) + request = _ExecutionRequest( + program=program, + runtime_profile_name=runtime_profile_name, + invocations=tuple(invocations), + timeout_seconds=self._resolve_timeout(timeout_seconds), + ) + self._raise_if_unusable() + if self.get_capabilities().state_kind is SandboxStateKind.CALL: + return await self._run_invocations_async(request=request, deadline=None) + deadline = time.monotonic() + self._acquire_timeout_seconds + await self._acquire_lock_async(deadline=deadline) + try: + self._raise_if_unusable() + task = self._spawn(self._run_locked_async(request=request, deadline=deadline)) + except BaseException: + self._unlock() + raise + # Recorded before the run can start (the task yields first), so it starts nothing for a caller + # that has given up: cancelling the caller cancels this shield at once. + waiter = asyncio.shield(task) + request.caller = waiter + return await self._await_owned_async(task, waiter=waiter) + + async def get_status_async(self) -> SandboxView: + """ + Return the sandbox's status and PyRIT's session state, without waiting for a running call. + + Returns: + SandboxView: The current view. If a call holds the sandbox, the last status read is reused. + """ + status = await self._read_status_without_waiting_async() + if status is None: + last = self._last_status or SandboxStatus(reason="The status has not been read yet.") + return self._build_view(status=last, status_is_current=False) + return self._build_view(status=status, status_is_current=True) + + async def release_async(self) -> None: + """ + End the session if no call is running, and clear a quarantine. The sandbox's state is kept. + + Release first closes again every session whose close was not confirmed, which also works after + ``close_async``; the quarantine stays while any of those closes still fails. Release never opens a + session. Once started, it runs to the end even if the caller gives up. + + Raises: + SandboxBusyError: If a call or reset holds the sandbox. + """ + if self.get_capabilities().state_kind is SandboxStateKind.CALL: + return + if not await self._try_lock_async(): + raise SandboxBusyError("A call or reset holds the sandbox; release it after that finishes.") + await self._await_owned_async(self._spawn(self._release_locked_async())) + + async def reset_async(self, *, expected_revision: str | None = None) -> None: + """ + Restore the sandbox's baseline, after the running call finishes. + + The session is closed first. Once started, a reset runs to the end even if the caller gives up. + A successful reset clears a quarantine; a session whose close is still unconfirmed is closed again + at the next release or close. + + Args: + expected_revision (str | None): The revision the caller read; the reset is refused if the + sandbox's revision changed since. None resets whatever the current revision is. + + Raises: + SandboxInputError: If this sandbox does not support reset. + SandboxUnavailableError: If the sandbox is closed. + SandboxBusyError: If a reset is already running, or the sandbox stayed busy too long. + SandboxRevisionChangedError: If the revision is not the expected one. + SandboxExecutionError: If the reset failed. + """ + if not self.get_capabilities().supports_reset: + raise SandboxInputError("This sandbox does not support reset.") + if self._closed: + raise SandboxUnavailableError("The sandbox is closed.") + if self._resetting: + raise SandboxBusyError("A reset of this sandbox is already running.") + self._resetting = True + try: + await self._acquire_lock_async(deadline=time.monotonic() + self._acquire_timeout_seconds) + except BaseException: + self._resetting = False + raise + if self._closed: + self._resetting = False + self._unlock() + raise SandboxUnavailableError("The sandbox was closed while the reset waited.") + task = self._spawn(self._reset_locked_async(expected_revision=expected_revision)) + await self._await_owned_async(task) + + async def close_async(self) -> None: + """ + Stop using the sandbox for good, and close its session once the running call finishes. + + Calls that are waiting or arrive later are refused; use ``release_async`` to end the session and + keep using the sandbox. The sandbox's state is kept. If a call still holds the sandbox after the + acquire timeout, the session is left to the idle close. This never raises an error. + """ + self._closed = True + self._cancel_idle_close() + if self.get_capabilities().state_kind is SandboxStateKind.CALL: + return + if not await self._wait_for_lock_async(timeout_seconds=self._acquire_timeout_seconds): + logger.warning("Sandbox %s stayed busy; its session closes when it is idle.", type(self).__name__) + return + await self._await_owned_async(self._spawn(self._close_locked_async())) + + # ---- adapter hooks ------------------------------------------------------------------------- + + @abstractmethod + def _get_capabilities(self) -> SandboxCapabilities: + """ + Describe the sandbox's runtimes, state kind and limits. Called once. + + Returns: + SandboxCapabilities: The sandbox's capabilities. + """ + + @abstractmethod + async def _execute_async( + self, + *, + session_id: str | None, + runtime_profile_name: str, + program: str, + arguments: tuple[str, ...], + stdin: str | None, + timeout_seconds: float, + ) -> ProcessResult: + """ + Run the program once and report what it did. + + Stop the processes the program started directly when the run ends. Report the program's own + failures, timeouts and limits in the result; raise only when the sandbox itself failed. + + Args: + session_id (str | None): The open session, or None in a ``call`` sandbox. + runtime_profile_name (str): One of the sandbox's runtime profile names. + program (str): The program text, run verbatim. + arguments (tuple[str, ...]): The program's command-line arguments. + stdin (str | None): The program's standard input, if any. + timeout_seconds (float): The time limit of the run. + + Returns: + ProcessResult: What the run did. + """ + + async def _open_session_async(self, *, owner: str) -> str: + """ + Open a session on the sandbox. Required for ``environment`` sandboxes. + + Args: + owner (str): The name to open the session under. + + Returns: + str: The session's identifier. + + Raises: + NotImplementedError: If the adapter has no sessions. + """ + raise NotImplementedError(f"{type(self).__name__} does not open sessions.") + + async def _close_session_async(self, *, session_id: str) -> None: + """ + Close a session, keeping the sandbox's state. Closing a closed session must succeed. + + Args: + session_id (str): The session to close. + + Raises: + NotImplementedError: If the adapter has no sessions. + """ + raise NotImplementedError(f"{type(self).__name__} does not close sessions.") + + async def _get_status_async(self) -> SandboxStatus: + """ + Report the sandbox's condition, revision and nonsecret details. Defaults to ready. + + Returns: + SandboxStatus: The sandbox's status. + """ + return SandboxStatus() + + async def _reset_async(self, *, expected_revision: str | None) -> None: + """ + Restore the sandbox's baseline, and return when it is done. Required when reset is supported. + + Args: + expected_revision (str | None): Refuse with ``SandboxRevisionChangedError`` unless the + revision is this one. None resets whatever the current revision is. + + Raises: + NotImplementedError: If the adapter can't reset. + """ + raise NotImplementedError(f"{type(self).__name__} does not reset.") + + # ---- running calls ------------------------------------------------------------------------- + + async def _run_locked_async(self, *, request: _ExecutionRequest, deadline: float) -> _SandboxRun: + """ + Run a request that holds the lock, and release the lock when the adapter has returned. + + Returns: + _SandboxRun: The request's runs. + """ + try: + # Yield first: with an eager task factory, this task would otherwise start before + # execute_async records the caller, and could not see the caller give up. + await asyncio.sleep(0) + return await self._run_invocations_async(request=request, deadline=deadline) + finally: + self._last_used_at = time.monotonic() + self._uses += 1 + self._unlock() + + async def _run_invocations_async(self, *, request: _ExecutionRequest, deadline: float | None) -> _SandboxRun: + """ + Run each invocation in order, stopping at the first failure or unconfirmed cleanup, or when the + caller has given up. + + Returns: + _SandboxRun: The runs that happened, with any reasons, warnings and execution ids. + + Raises: + SandboxInputError: If the first invocation was rejected. + _CallerGaveUpError: If the caller gave up before the first invocation started. + SandboxExecutionError: If the first invocation could not run. + """ + events: list[_ProgramExecutionEvent] = [] + warnings: list[str] = [] + execution_ids: list[str] = [] + reasons: tuple[str, ...] = () + for index, invocation in enumerate(request.invocations): + try: + if request.abandoned(): + raise _CallerGaveUpError + result = await self._invoke_async(request=request, invocation=invocation, deadline=deadline) + events.append(self._to_event(index=index, request=request, result=result)) + except _CallerGaveUpError: + if not events: + raise + reasons = (f"stopped after invocation {index - 1}: {_CALLER_GAVE_UP_REASON}",) + break + except (SandboxExecutionError, SandboxInputError) as error: + if not events: + raise + reasons = (f"sandbox error at invocation {index}: {error}",) + break + warnings.extend(result.warnings) + if result.execution_id is not None: + execution_ids.append(result.execution_id) + if not result.cleanup_confirmed: + detail = "; ".join(result.warnings) or "cleanup was not confirmed" + if deadline is not None: + self._quarantine(reason=f"A run's processes may still be running: {detail}") + if index + 1 < len(request.invocations): + reasons = (f"stopped after invocation {index}: {detail}",) + break + return _SandboxRun( + events=tuple(events), reasons=reasons, warnings=tuple(warnings), execution_ids=tuple(execution_ids) + ) + + async def _invoke_async( + self, *, request: _ExecutionRequest, invocation: _ProgramInvocation, deadline: float | None + ) -> ProcessResult: + """ + Run one invocation, in the session when the sandbox has one. + + Returns: + ProcessResult: What the run did. + """ + if deadline is None: + return await self._call_execute_async(session_id=None, request=request, invocation=invocation) + return await self._invoke_in_session_async(request=request, invocation=invocation, deadline=deadline) + + async def _invoke_in_session_async( + self, *, request: _ExecutionRequest, invocation: _ProgramInvocation, deadline: float + ) -> ProcessResult: + """ + Run one invocation in the shared session, reopening a lost session and retrying once. + + Returns: + ProcessResult: What the run did. + """ + try: + return await self._attempt_in_session_async(request=request, invocation=invocation, deadline=deadline) + except SandboxSessionLostError: + logger.info("Sandbox %s lost its session before a run; reopening once.", type(self).__name__) + return await self._attempt_in_session_async(request=request, invocation=invocation, deadline=deadline) + + async def _attempt_in_session_async( + self, *, request: _ExecutionRequest, invocation: _ProgramInvocation, deadline: float + ) -> ProcessResult: + """ + Run one invocation in the open session, opening or renewing it first. + + Returns: + ProcessResult: What the run did. + + Raises: + SandboxInputError: If the adapter rejected the input; nothing ran. + SandboxUnavailableError: If the sandbox is closed or quarantined; nothing ran. + _CallerGaveUpError: If the caller gave up while the session opened; nothing ran. + SandboxBusyError: If the sandbox could not start the run; nothing ran. + SandboxSessionLostError: If the session was gone; it is forgotten and nothing ran. + SandboxExecutionError: If the outcome is uncertain; the session is closed first. + """ + session_id = await self._ensure_session_async(request=request, deadline=deadline) + if request.abandoned(): + raise _CallerGaveUpError + try: + return await self._call_execute_async(session_id=session_id, request=request, invocation=invocation) + except (SandboxInputError, SandboxBusyError): + raise + except SandboxSessionLostError: + self._forget_session() + raise + except SandboxExecutionError: + await self._discard_session_async() + raise + + async def _call_execute_async( + self, *, session_id: str | None, request: _ExecutionRequest, invocation: _ProgramInvocation + ) -> ProcessResult: + """ + Call the adapter, bounded by the run's timeout plus a grace period, with failures classified. + + Returns: + ProcessResult: What the run did, validated, with its duration filled in. + + Raises: + SandboxInputError: If the adapter rejected the input. + SandboxExecutionError: If the adapter failed, did not answer in time, or returned an invalid result. + CancelledError: If this task is being cancelled. + """ + started = time.monotonic() + try: + async with asyncio.timeout(request.timeout_seconds + self._EXECUTE_GRACE_SECONDS): + result = await self._execute_async( + session_id=session_id, + runtime_profile_name=request.runtime_profile_name, + program=request.program, + arguments=tuple(invocation.arguments), + stdin=invocation.stdin, + timeout_seconds=request.timeout_seconds, + ) + # Validate again: model_copy and model_construct skip validation. + result = ProcessResult.model_validate(result.model_dump()) + except (SandboxExecutionError, SandboxInputError): + raise + except TimeoutError as error: + raise SandboxExecutionError("The sandbox did not answer in time; the outcome is uncertain.") from error + except asyncio.CancelledError as error: + if _cancellation_requested(): + raise + raise SandboxExecutionError("The sandbox cancelled the run by itself; the outcome is uncertain.") from error + except Exception as error: + message = ( + f"The sandbox failed during the run, or returned an invalid result; the outcome is uncertain: {error}" + ) + raise SandboxExecutionError(message) from error + if result.duration_ms is None: + result = result.model_copy(update={"duration_ms": int((time.monotonic() - started) * 1000)}) + return result + + def _to_event(self, *, index: int, request: _ExecutionRequest, result: ProcessResult) -> _ProgramExecutionEvent: + """ + Record an adapter's result as an execution event. + + Returns: + _ProgramExecutionEvent: The event. + + Raises: + SandboxExecutionError: If the result can't be recorded. + """ + try: + return _ProgramExecutionEvent( + invocation_index=index, + runtime_profile_name=request.runtime_profile_name, + runtime_image_digest=result.runtime_image_digest, + resolved_command=result.resolved_command, + exit_code=result.exit_code, + stdout=result.stdout, + stderr=result.stderr, + stdout_truncated=result.stdout_truncated, + stderr_truncated=result.stderr_truncated, + timed_out=result.timed_out, + resource_limit_exceeded=result.resource_limit_exceeded, + duration_ms=result.duration_ms or 0, + ) + except ValidationError as error: + raise SandboxExecutionError(f"The sandbox returned a result that can't be recorded: {error}") from error + + # ---- sessions ------------------------------------------------------------------------------ + + async def _ensure_session_async(self, *, request: _ExecutionRequest, deadline: float) -> str: + """ + Return the open session, renewing it first if the request's run could outlast it. + + Returns: + str: The session identifier. + """ + if self._session_id is not None and not self._needs_renewal(timeout_seconds=request.timeout_seconds): + return self._session_id + if self._session_id is not None: + await self._discard_session_async() + return await self._open_session_with_retry_async(request=request, deadline=deadline) + + def _needs_renewal(self, *, timeout_seconds: float) -> bool: + """ + Whether the session could end before a run of this length finishes. + + Returns: + bool: True if the session should be reopened first. + """ + limit = self.get_capabilities().max_session_seconds + if limit is None or self._session_opened_at is None: + return False + remaining = self._session_opened_at + limit - time.monotonic() + return remaining < timeout_seconds + self._RENEWAL_MARGIN_SECONDS + + async def _open_session_with_retry_async(self, *, request: _ExecutionRequest, deadline: float) -> str: + """ + Open a session for a request, retrying a busy sandbox with backoff until the deadline. + + Returns: + str: The new session's identifier. + + Raises: + SandboxUnavailableError: If the sandbox is closed or quarantined. + _CallerGaveUpError: If the caller gave up. + SandboxBusyError: If the sandbox is still busy at the deadline. + SandboxExecutionError: If the open failed. + """ + delay = self._BUSY_RETRY_INITIAL_SECONDS + while True: + self._raise_if_unusable() + if request.abandoned(): + raise _CallerGaveUpError + sent_at = time.monotonic() + try: + session_id = await self._call_control_async( + self._open_session_async(owner=self._owner), action="open a session" + ) + except SandboxBusyError: + if time.monotonic() + delay > deadline: + raise + await request.sleep_unless_abandoned_async(delay) + delay = min(delay * 2, self._BUSY_RETRY_MAX_SECONDS) + continue + self._session_id, self._session_opened_at = session_id, sent_at + return session_id + + async def _discard_session_async(self) -> None: + """Close the session and forget it; quarantine the sandbox if the close can't be confirmed.""" + session_id = self._session_id + self._forget_session() + if session_id is not None: + await self._close_or_quarantine_async(session_id=session_id) + + async def _close_or_quarantine_async(self, *, session_id: str) -> bool: + """ + Close a session. Until a close is confirmed, the session stays listed as unconfirmed, and a close + that fails quarantines the sandbox. + + Returns: + bool: Whether the session is known to be closed. + """ + if session_id not in self._unconfirmed_session_ids: + self._unconfirmed_session_ids.append(session_id) + try: + await self._call_control_async(self._close_session_async(session_id=session_id), action="close a session") + except SandboxSessionLostError: + pass + except SandboxExecutionError as error: + self._quarantine(reason=f"Closing session {session_id} could not be confirmed: {error}") + return False + self._unconfirmed_session_ids.remove(session_id) + return True + + async def _retry_unconfirmed_closes_async(self) -> bool: + """ + Close again each session whose close was not confirmed. + + Returns: + bool: Whether every such session is now known to be closed. + """ + for session_id in list(self._unconfirmed_session_ids): + await self._close_or_quarantine_async(session_id=session_id) + return not self._unconfirmed_session_ids + + def _quarantine(self, *, reason: str) -> None: + """Refuse calls until an operator releases or resets the sandbox.""" + self._quarantine_reason = reason + logger.warning("Sandbox %s is quarantined: %s", type(self).__name__, reason) + + def _forget_session(self) -> None: + """Drop the session without closing it, when it is already gone.""" + self._session_id = None + self._session_opened_at = None + self._cancel_idle_close() + + async def _release_locked_async(self) -> None: + """ + Retry each unconfirmed close, clear the quarantine once none remains, and end the session while + holding the lock, then release the lock. + """ + try: + if await self._retry_unconfirmed_closes_async(): + self._quarantine_reason = None + await self._discard_session_async() + finally: + self._unlock() + + async def _close_locked_async(self) -> None: + """Retry each unconfirmed close and end the session while holding the lock, then release it.""" + try: + await self._retry_unconfirmed_closes_async() + await self._discard_session_async() + if not self._unconfirmed_session_ids: + self._quarantine_reason = None + finally: + self._lock.release() + + # ---- status, reset and idle close ---------------------------------------------------------- + + async def _read_status_without_waiting_async(self) -> SandboxStatus | None: + """ + Read the status unless a call holds the sandbox. + + Returns: + SandboxStatus | None: The status, or None if the sandbox is held. + """ + if self.get_capabilities().state_kind is SandboxStateKind.CALL: + return await self._read_status_async() + if not await self._try_lock_async(): + return None + try: + return await self._read_status_async() + finally: + self._unlock() + + async def _read_status_async(self) -> SandboxStatus: + """ + Call the adapter for its status, reporting a failure as unavailable. + + Returns: + SandboxStatus: The status, which is also kept as the last one read. + """ + try: + status = await self._call_control_async(self._get_status_async(), action="read the status") + except SandboxExecutionError as error: + status = SandboxStatus(condition=SandboxCondition.UNAVAILABLE, reason=str(error)) + self._last_status = status + return status + + def _build_view(self, *, status: SandboxStatus, status_is_current: bool) -> SandboxView: + """ + Combine a status with PyRIT's own session state. + + Returns: + SandboxView: The view. + """ + now = time.monotonic() + session_open = self._session_id is not None + return SandboxView( + status=status, + status_is_current=status_is_current, + condition=SandboxCondition.QUARANTINED if self._quarantine_reason else status.condition, + quarantine_reason=self._quarantine_reason, + closed=self._closed, + session_open=session_open, + session_age_seconds=now - self._session_opened_at if self._session_opened_at is not None else None, + idle_seconds=now - self._last_used_at if session_open and self._last_used_at is not None else None, + busy=self._lock.locked(), + resetting=self._resetting, + last_reset=self._last_reset, + ) + + async def _reset_locked_async(self, *, expected_revision: str | None) -> None: + """ + Close the session and reset while holding the lock, recording the outcome. + + A reset that was refused changed nothing. Any other failure leaves the sandbox in an unknown state, + so it is quarantined. + + Raises: + SandboxExecutionError: If the reset failed or was refused. + """ + started_at = datetime.now(UTC) + self._last_reset = SandboxResetRecord(started_at=started_at) + try: + await self._retry_unconfirmed_closes_async() + await self._discard_session_async() + await self._call_reset_async(expected_revision=expected_revision) + except Exception as error: + if not isinstance(error, (SandboxInputError, SandboxBusyError, SandboxRevisionChangedError)): + self._quarantine(reason=f"The reset did not finish: {error}") + self._last_reset = SandboxResetRecord( + started_at=started_at, finished_at=datetime.now(UTC), succeeded=False, error=str(error) + ) + raise + else: + self._quarantine_reason = None + if self._unconfirmed_session_ids: + logger.warning( + "Sandbox %s was reset, but closing sessions %s is unconfirmed; release and close retry it.", + type(self).__name__, + ", ".join(self._unconfirmed_session_ids), + ) + self._last_reset = SandboxResetRecord(started_at=started_at, finished_at=datetime.now(UTC), succeeded=True) + finally: + self._resetting = False + self._last_status = None + self._unlock() + + async def _call_reset_async(self, *, expected_revision: str | None) -> None: + """ + Call the adapter's reset, bounded in time, with failures classified. + + Raises: + SandboxInputError: If the adapter rejected the request. + SandboxExecutionError: If the reset failed or did not finish in time. + CancelledError: If this task is being cancelled. + """ + try: + async with asyncio.timeout(self._RESET_TIMEOUT_SECONDS): + await self._reset_async(expected_revision=expected_revision) + except (SandboxExecutionError, SandboxInputError): + raise + except TimeoutError as error: + raise SandboxExecutionError(f"The reset did not finish in {self._RESET_TIMEOUT_SECONDS:g} s.") from error + except asyncio.CancelledError as error: + if _cancellation_requested(): + raise + raise SandboxExecutionError("The reset failed: the sandbox cancelled it by itself.") from error + except Exception as error: + raise SandboxExecutionError(f"The reset failed: {error}") from error + + def _schedule_idle_close(self) -> None: + """Close the session once it has been idle long enough.""" + self._cancel_idle_close() + if self._session_id is None or self._last_used_at is None: + return + delay = max(self._last_used_at + self._idle_timeout_seconds - time.monotonic(), 0.0) + self._idle_handle = asyncio.get_running_loop().call_later(delay, self._on_idle_timer, self._uses) + + def _cancel_idle_close(self) -> None: + """Cancel a scheduled idle close.""" + if self._idle_handle is not None: + self._idle_handle.cancel() + self._idle_handle = None + + def _on_idle_timer(self, uses: int) -> None: + """Start closing an idle session, unless something holds the sandbox; its holder reschedules.""" + self._idle_handle = None + if self._session_id is not None and not self._lock.locked(): + self._spawn(self._close_if_idle_async(uses=uses)) + + async def _close_if_idle_async(self, *, uses: int) -> None: + """ + Close the session if no call has used it since the idle timer was set. + + Counting uses rather than reading the clock keeps this correct when a timer fires a clock tick early + and when two uses fall in one tick. A call that used the session in the meantime rescheduled the + timer when it released the lock. + """ + async with self._lock: + if self._session_id is not None and self._uses == uses: + await self._discard_session_async() + + # ---- helpers ------------------------------------------------------------------------------- + + def _raise_if_unusable(self) -> None: + """ + Refuse new work, including a new session, once the sandbox is closed or while it is quarantined. + + Raises: + SandboxUnavailableError: If the sandbox is closed or quarantined; nothing ran. + """ + if self._closed: + raise SandboxUnavailableError("The sandbox is closed; no new calls start.") + if self._quarantine_reason is not None: + raise SandboxUnavailableError( + f"The sandbox is quarantined until it is released or reset: {self._quarantine_reason}" + ) + + def _resolve_timeout(self, timeout_seconds: float | None) -> float: + """ + Apply the default timeout and check the limits. + + Returns: + float: The timeout to use. + + Raises: + SandboxInputError: If the timeout is out of range or can't fit in a session. + """ + capabilities = self.get_capabilities() + timeout = capabilities.default_timeout_seconds if timeout_seconds is None else timeout_seconds + if isinstance(timeout, bool) or not 0 < timeout <= capabilities.max_timeout_seconds: + raise SandboxInputError( + f"timeout_seconds must be more than 0 and at most {capabilities.max_timeout_seconds:g}." + ) + limit = capabilities.max_session_seconds + if limit is not None and timeout + self._RENEWAL_MARGIN_SECONDS > limit: + raise SandboxInputError( + f"timeout_seconds must be at most {limit - self._RENEWAL_MARGIN_SECONDS:g} for this sandbox's " + "session limit." + ) + return float(timeout) + + @staticmethod + def _utf8_size(text: str, *, field: str) -> int: + """ + Return the UTF-8 size of a text. + + Returns: + int: The size in bytes. + + Raises: + SandboxInputError: If the text can't be encoded as UTF-8. + """ + try: + return len(text.encode("utf-8")) + except UnicodeEncodeError as error: + raise SandboxInputError(f"The {field} is not valid UTF-8 text.") from error + + async def _acquire_lock_async(self, *, deadline: float) -> None: + """ + Wait for the sandbox's turn, up to the deadline. Nothing has started if this raises. + + Raises: + SandboxBusyError: If the deadline passed first. + """ + if not await self._wait_for_lock_async(timeout_seconds=deadline - time.monotonic()): + raise SandboxBusyError(f"The sandbox stayed busy for {self._acquire_timeout_seconds:g} s; nothing ran.") + + async def _try_lock_async(self) -> bool: + """ + Take the lock if nothing holds it, without waiting for a call. + + Returns: + bool: Whether the lock is now held. + """ + if self._lock.locked(): + return False + return await self._wait_for_lock_async(timeout_seconds=self._STATUS_LOCK_WAIT_SECONDS) + + async def _wait_for_lock_async(self, *, timeout_seconds: float) -> bool: + """ + Wait up to a time limit for the lock. + + ``asyncio.timeout`` rather than ``asyncio.wait_for``: on Python 3.11, ``wait_for`` can drop a + caller's cancellation that arrives as the lock is handed over, so a caller that gave up would run. + + Returns: + bool: Whether the lock is now held. + """ + try: + async with asyncio.timeout(max(timeout_seconds, 0.0)): + await self._lock.acquire() + except TimeoutError: + return False + return True + + def _unlock(self) -> None: + """Release the lock and reschedule the idle close, which skips a held sandbox.""" + self._lock.release() + self._schedule_idle_close() + + async def _call_control_async(self, work: Awaitable[_T], *, action: str) -> _T: + """ + Await an adapter's session or status call, bounded in time, with failures classified. + + Returns: + _T: The call's result. + + Raises: + SandboxExecutionError: If the call failed or did not answer in time. + CancelledError: If this task is being cancelled. + """ + try: + async with asyncio.timeout(self._HOOK_TIMEOUT_SECONDS): + return await work + except SandboxExecutionError: + raise + except TimeoutError as error: + raise SandboxExecutionError(f"Could not {action}: no answer in time.") from error + except asyncio.CancelledError as error: + if _cancellation_requested(): + raise + raise SandboxExecutionError(f"Could not {action}: the sandbox cancelled the call by itself.") from error + except Exception as error: + raise SandboxExecutionError(f"Could not {action}: {error}") from error + + def _spawn(self, work: Coroutine[Any, Any, _T]) -> asyncio.Task[_T]: + """ + Start work this sandbox owns, keeping a reference until it finishes. + + Returns: + asyncio.Task[_T]: The started task. + """ + task = asyncio.get_running_loop().create_task(work) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + return task + + @staticmethod + async def _await_owned_async(task: asyncio.Task[_T], *, waiter: asyncio.Future[_T] | None = None) -> _T: + """ + Wait for owned work; a caller that gives up returns at once, and the work finishes alone. + + Args: + task (asyncio.Task[_T]): The owned work. + waiter (asyncio.Future[_T] | None): The shield over ``task`` to wait on, when the work watches + it to see whether its caller gave up. Defaults to a new shield. + + Returns: + _T: The work's result. + + Raises: + CancelledError: If the caller was cancelled; the work continues. + """ + try: + return await (waiter if waiter is not None else asyncio.shield(task)) + except asyncio.CancelledError: + # Even when the work finished at the same moment: the shield marked its error as retrieved. + task.add_done_callback(_log_abandoned_outcome) + raise + + def _validate_hooks(self, *, capabilities: SandboxCapabilities) -> None: + """ + Check that the adapter implements the hooks its capabilities need. + + Raises: + TypeError: If a needed hook is missing. + """ + needed = [] + if capabilities.state_kind is SandboxStateKind.ENVIRONMENT: + needed += ["_open_session_async", "_close_session_async"] + if capabilities.supports_reset: + needed.append("_reset_async") + sandbox_type = type(self) + missing = [hook for hook in needed if getattr(sandbox_type, hook) is getattr(Sandbox, hook)] + if missing: + raise TypeError(f"{sandbox_type.__name__} must implement {', '.join(missing)} for its capabilities.") diff --git a/pyrit/_code_execution/sandbox_contract.py b/pyrit/_code_execution/sandbox_contract.py new file mode 100644 index 0000000000..1fa9a665da --- /dev/null +++ b/pyrit/_code_execution/sandbox_contract.py @@ -0,0 +1,340 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +A contract-test kit for ``Sandbox`` adapters. + +Run ``check_sandbox_contract_async`` against a live sandbox, from your adapter's own tests, to check the +rules PyRIT relies on: declared limits, error mapping, state, status, reset, closing twice, and a +static identifier. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +import uuid +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pyrit._code_execution.client import ( + SandboxBusyError, + SandboxExecutionError, + SandboxRevisionChangedError, + SandboxSessionLostError, +) +from pyrit._code_execution.sandbox import SandboxCondition, SandboxStateKind +from pyrit.models.code_execution import _ProgramInvocation + +if TYPE_CHECKING: + from collections.abc import Callable + + from pyrit._code_execution.sandbox import Sandbox + from pyrit.models.code_execution import _ProgramExecutionEvent + + +class SandboxContractError(AssertionError): + """An adapter broke a rule of the ``Sandbox`` contract.""" + + +@dataclass(frozen=True) +class SandboxProbes: + """ + Programs, in one of a sandbox's runtimes, that the contract checks run. + + Each builder returns program text. ``print_text`` writes its text to standard output as UTF-8; + ``print_repeated`` writes one ASCII character many times; ``fail_with`` writes ASCII text to standard + error and exits with a code; ``echo_arguments`` prints each argument on its own line; ``echo_stdin`` + copies standard input to standard output; ``write_marker`` writes text to a file, relative to the + working directory, and ``read_marker`` prints that file, or nothing if it is missing; ``sleep_then_write`` + sleeps, then writes a marker, which shows whether a run past its timeout was really stopped. + ``comment_prefix`` starts a comment, which pads a program to a size. + """ + + runtime_profile_name: str + print_text: Callable[[str], str] + print_repeated: Callable[[str, int], str] + fail_with: Callable[[str, int], str] + echo_arguments: str + echo_stdin: str + write_marker: Callable[[str, str], str] + read_marker: Callable[[str], str] + sleep_then_write: Callable[[float, str, str], str] + comment_prefix: str = "#" + + @classmethod + def python(cls, *, runtime_profile_name: str = "python") -> SandboxProbes: + """ + Return probes for a Python 3 runtime. + + Args: + runtime_profile_name (str): The sandbox's Python runtime. Defaults to ``"python"``. + + Returns: + SandboxProbes: The probes. + """ + return cls( + runtime_profile_name=runtime_profile_name, + print_text=lambda text: f"import sys\nsys.stdout.buffer.write({text!r}.encode('utf-8'))\n", + print_repeated=lambda character, count: f"import sys\nsys.stdout.write({character!r} * {count})\n", + fail_with=lambda text, code: f"import sys\nsys.stderr.write({text!r})\nsys.exit({code})\n", + echo_arguments="import sys\nsys.stdout.write('\\n'.join(sys.argv[1:]))\n", + echo_stdin="import sys\nsys.stdout.write(sys.stdin.read())\n", + write_marker=lambda name, text: ( + f"from pathlib import Path\nPath({name!r}).write_text({text!r}, encoding='utf-8')\n" + ), + read_marker=lambda name: ( + "import sys\nfrom pathlib import Path\n" + f"path = Path({name!r})\n" + "sys.stdout.write(path.read_text(encoding='utf-8') if path.exists() else '')\n" + ), + sleep_then_write=lambda seconds, name, text: ( + f"import time\nfrom pathlib import Path\ntime.sleep({seconds!r})\n" + f"Path({name!r}).write_text({text!r}, encoding='utf-8')\n" + ), + ) + + +async def check_sandbox_contract_async( + *, sandbox: Sandbox, probes: SandboxProbes, timeout_probe_seconds: float = 2.0 +) -> None: + """ + Check that an adapter honors the ``Sandbox`` contract by running real programs in it. + + Use a sandbox you can reset or discard: the checks write files, and reset the sandbox when it supports + reset. They take a few seconds, plus a run that times out and, for an ``environment`` sandbox, a wait + to show that run was stopped. The session is released at the end, pass or fail. + + Args: + sandbox (Sandbox): The adapter to check, connected to a live sandbox. + probes (SandboxProbes): Programs in one of the sandbox's runtimes. + timeout_probe_seconds (float): The timeout of the run that must time out. Defaults to 2 seconds. + + Raises: + SandboxContractError: Naming the first rule the adapter breaks. + """ + _require( + probes.runtime_profile_name in sandbox.get_runtime_profile_names(), + f"The probes use runtime {probes.runtime_profile_name!r}, which the sandbox does not offer.", + ) + try: + await _check_all_async(sandbox=sandbox, probes=probes, timeout_probe_seconds=timeout_probe_seconds) + finally: + with contextlib.suppress(SandboxBusyError): + await sandbox.release_async() + + +async def _check_all_async(*, sandbox: Sandbox, probes: SandboxProbes, timeout_probe_seconds: float) -> None: + capabilities = sandbox.get_capabilities() + identity = sandbox._build_identifier().hash + await _check_round_trip_async(sandbox=sandbox, probes=probes) + _require( + sandbox._build_identifier().hash == identity, + "An identifier must hold static configuration only; it changed once the sandbox was used.", + ) + await _check_arguments_and_input_async(sandbox=sandbox, probes=probes) + await _check_status_async(sandbox=sandbox) + if capabilities.state_kind is SandboxStateKind.ENVIRONMENT: + await _check_state_persists_async(sandbox=sandbox, probes=probes) + await _check_session_hooks_async(sandbox=sandbox, probes=probes) + else: + await _check_nothing_persists_async(sandbox=sandbox, probes=probes) + if capabilities.supports_reset: + await _check_reset_async(sandbox=sandbox, probes=probes) + await _check_limits_async(sandbox=sandbox, probes=probes) + await _check_timeout_async(sandbox=sandbox, probes=probes, timeout_seconds=timeout_probe_seconds) + + +async def _check_round_trip_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + text = "contract check: h\u00e9llo \u2713" + event = await _run_async(sandbox=sandbox, probes=probes, program=probes.print_text(text), check="round trip") + _require(event.exit_code == 0, f"A program that succeeds must exit 0, not {event.exit_code}: {event.stderr!r}") + _require(_lines(event.stdout) == text, f"Standard output must come back exactly as UTF-8; got {event.stdout!r}.") + event = await _run_async( + sandbox=sandbox, probes=probes, program=probes.fail_with("contract failure", 3), check="exit code" + ) + _require(event.exit_code == 3, f"The program's own exit code must come back; expected 3, got {event.exit_code}.") + _require("contract failure" in event.stderr, f"Standard error must come back; got {event.stderr!r}.") + _require(event.stdout == "", f"Standard output must not include standard error; got {event.stdout!r}.") + + +async def _check_arguments_and_input_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + arguments = ("alpha", "two words", 'quote\'s "mark"') + event = await _run_async( + sandbox=sandbox, probes=probes, program=probes.echo_arguments, arguments=arguments, check="arguments" + ) + _require(_lines(event.stdout) == "\n".join(arguments), f"Arguments must reach the program; got {event.stdout!r}.") + text = "line one\nline two\n" + event = await _run_async(sandbox=sandbox, probes=probes, program=probes.echo_stdin, stdin=text, check="stdin") + _require(_lines(event.stdout) == text, f"Standard input must reach the program; got {event.stdout!r}.") + + +async def _check_status_async(*, sandbox: Sandbox) -> None: + view = await sandbox.get_status_async() + _require(view.status_is_current, "The status must be readable when nothing holds the sandbox.") + _require( + view.condition is SandboxCondition.READY, + f"A sandbox under test must report ready; it reports {view.condition.value}: {view.status.reason}", + ) + + +async def _check_state_persists_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + name, token = await _write_marker_async(sandbox=sandbox, probes=probes) + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == token, + "An environment sandbox must keep files between calls.", + ) + await sandbox.release_async() + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == token, + "An environment sandbox's files must survive closing its session.", + ) + + +async def _check_nothing_persists_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + name, _ = await _write_marker_async(sandbox=sandbox, probes=probes) + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == "", + "A call sandbox must not keep files between calls.", + ) + + +async def _check_session_hooks_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + await sandbox.release_async() + session_id = await sandbox._open_session_async(owner="pyrit-contract-check") + await sandbox._close_session_async(session_id=session_id) + try: + await sandbox._close_session_async(session_id=session_id) + except Exception as error: + raise SandboxContractError(f"Closing a closed session must succeed; it raised {error!r}.") from error + try: + await sandbox._execute_async( + session_id=session_id, + runtime_profile_name=probes.runtime_profile_name, + program=probes.print_text("must not run"), + arguments=(), + stdin=None, + timeout_seconds=sandbox.get_capabilities().default_timeout_seconds, + ) + except SandboxSessionLostError: + return + except Exception as error: + raise SandboxContractError( + f"A run in a closed session must raise SandboxSessionLostError, so PyRIT knows nothing ran; " + f"it raised {error!r}." + ) from error + raise SandboxContractError("A run in a closed session must raise SandboxSessionLostError; it ran.") + + +async def _check_reset_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + name, token = await _write_marker_async(sandbox=sandbox, probes=probes) + revision = (await sandbox.get_status_async()).status.revision + _require(revision is not None, "A sandbox that resets must report its revision, so a reset can pin it.") + try: + await sandbox.reset_async(expected_revision=f"pyrit-contract-unexpected-{uuid.uuid4().hex}") + except SandboxRevisionChangedError: + pass + except SandboxExecutionError as error: + raise SandboxContractError( + f"A reset to another revision must raise SandboxRevisionChangedError; got {error!r}." + ) from error + else: + raise SandboxContractError("A reset to another revision must be refused with SandboxRevisionChangedError.") + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == token, + "A refused reset must leave the sandbox unchanged.", + ) + await sandbox.reset_async(expected_revision=revision) + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == "", + "A reset must remove files written since the baseline.", + ) + + +async def _check_limits_async(*, sandbox: Sandbox, probes: SandboxProbes) -> None: + capabilities = sandbox.get_capabilities() + program = probes.print_text("padded") + padding = capabilities.max_input_bytes - len(program.encode("utf-8")) - len(probes.comment_prefix) - 1 + _require(padding >= 0, "max_input_bytes must fit the probe program.") + program += probes.comment_prefix + "x" * padding + "\n" + event = await _run_async(sandbox=sandbox, probes=probes, program=program, check="largest program") + _require(event.stdout == "padded", f"A program of max_input_bytes ({capabilities.max_input_bytes}) must run.") + limit = capabilities.max_output_bytes + event = await _run_async(sandbox=sandbox, probes=probes, program=probes.print_repeated("x", limit), check="output") + _require( + event.stdout == "x" * limit and not event.stdout_truncated, + f"Output of max_output_bytes ({limit}) must come back whole; got {len(event.stdout)} characters.", + ) + program = probes.print_repeated("x", limit + 1024) + event = await _run_async(sandbox=sandbox, probes=probes, program=program, check="long output") + _require(event.stdout_truncated, "Output longer than max_output_bytes must be marked truncated.") + _require(len(event.stdout) <= limit, f"No more than max_output_bytes ({limit}) of output may come back.") + + +async def _check_timeout_async(*, sandbox: Sandbox, probes: SandboxProbes, timeout_seconds: float) -> None: + timeout = min(timeout_seconds, sandbox.get_capabilities().max_timeout_seconds) + name, _ = _marker() + program = probes.sleep_then_write(timeout + 1, name, "late") + started = time.monotonic() + event = await _run_async(sandbox=sandbox, probes=probes, program=program, timeout_seconds=timeout, check="timeout") + elapsed = time.monotonic() - started + _require(event.timed_out and event.exit_code is None, "A run past its timeout must be marked timed out.") + _require(elapsed < timeout + 20, f"A run with a {timeout:g} s timeout took {elapsed:.0f} s to come back.") + if sandbox.get_capabilities().state_kind is SandboxStateKind.ENVIRONMENT: + # The probe writes its marker one second after its timeout; give a stray run one more second. + await asyncio.sleep(max(timeout + 2 - elapsed, 0.5)) + _require( + await _read_marker_async(sandbox=sandbox, probes=probes, name=name) == "", + "A run past its timeout must be stopped, not left running.", + ) + + +async def _write_marker_async(*, sandbox: Sandbox, probes: SandboxProbes) -> tuple[str, str]: + name, token = _marker() + event = await _run_async(sandbox=sandbox, probes=probes, program=probes.write_marker(name, token), check="write") + _require(event.exit_code == 0, f"Writing a file in the working directory must succeed: {event.stderr!r}") + return name, token + + +async def _read_marker_async(*, sandbox: Sandbox, probes: SandboxProbes, name: str) -> str: + event = await _run_async(sandbox=sandbox, probes=probes, program=probes.read_marker(name), check="read") + _require(event.exit_code == 0, f"Reading a file in the working directory must succeed: {event.stderr!r}") + return event.stdout + + +async def _run_async( + *, + sandbox: Sandbox, + probes: SandboxProbes, + program: str, + check: str, + arguments: tuple[str, ...] = (), + stdin: str | None = None, + timeout_seconds: float | None = None, +) -> _ProgramExecutionEvent: + try: + run = await sandbox.execute_async( + program=program, + runtime_profile_name=probes.runtime_profile_name, + invocations=(_ProgramInvocation(arguments=arguments, stdin=stdin),), + timeout_seconds=timeout_seconds, + ) + except SandboxExecutionError as error: + raise SandboxContractError(f"The {check} check could not run: {error}") from error + _require(len(run.events) == 1, f"The {check} check must produce one result; got {len(run.events)}.") + return run.events[0] + + +def _marker() -> tuple[str, str]: + token = uuid.uuid4().hex + return f"pyrit_contract_{token}.txt", token + + +def _lines(text: str) -> str: + return text.replace("\r\n", "\n") + + +def _require(condition: bool, message: str) -> None: + if not condition: + raise SandboxContractError(message) diff --git a/pyrit/_code_execution/sandbox_registry.py b/pyrit/_code_execution/sandbox_registry.py new file mode 100644 index 0000000000..760809edf7 --- /dev/null +++ b/pyrit/_code_execution/sandbox_registry.py @@ -0,0 +1,137 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Name the sandboxes a process uses, so every caller shares one ``Sandbox`` object per sandbox.""" + +from __future__ import annotations + +import asyncio +import re +import threading +from typing import ClassVar + +from pyrit._code_execution.sandbox import Sandbox +from pyrit.registry import DefaultInstanceRegistry + + +class SandboxRegistry: + """ + The sandboxes this process uses, by name. + + Targets, scorers and operators refer to a sandbox by its name, so they share one ``Sandbox`` object, + and with it one session and one lock. A second object with the same identifier would let two locks + govern one sandbox, so it is refused. Names are letters, digits, dots, hyphens and underscores. + """ + + _NAME_PATTERN: ClassVar[re.Pattern[str]] = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") + _singleton: ClassVar[SandboxRegistry | None] = None + _singleton_lock: ClassVar[threading.Lock] = threading.Lock() + + def __init__(self) -> None: + """Initialize an empty registry.""" + self._entries: DefaultInstanceRegistry[Sandbox] = DefaultInstanceRegistry(instance_type=Sandbox) + self._lock = threading.RLock() + + @classmethod + def get_registry_singleton(cls) -> SandboxRegistry: + """ + Return the process-wide registry, creating it on first use. + + Returns: + SandboxRegistry: The shared registry. + """ + with cls._singleton_lock: + if cls._singleton is None: + cls._singleton = cls() + return cls._singleton + + @classmethod + def reset_registry_singleton(cls) -> None: + """Forget the process-wide registry, without closing its sandboxes.""" + with cls._singleton_lock: + cls._singleton = None + + def register(self, sandbox: Sandbox, *, name: str, tags: dict[str, str] | list[str] | None = None) -> None: + """ + Register a sandbox under a name. + + Args: + sandbox (Sandbox): The sandbox. Its capabilities are checked now. + name (str): The name callers use. + tags (dict[str, str] | list[str] | None): Optional tags for filtering. + + Raises: + ValueError: If the name is invalid or taken, or the sandbox is already registered. + """ + if not self._NAME_PATTERN.fullmatch(name): + raise ValueError(f"Sandbox name {name!r} must be 1-128 letters, digits, dots, hyphens or underscores.") + sandbox.get_capabilities() + identity = sandbox.get_identifier().hash + with self._lock: + if name in self._entries: + raise ValueError(f"Another sandbox is already registered as {name!r}.") + for entry in self._entries.get_all_instances(): + if entry.instance is sandbox or entry.instance.get_identifier().hash == identity: + raise ValueError(f"This sandbox is already registered as {entry.name!r}.") + self._entries.register(sandbox, name=name, tags=tags) + + def get(self, name: str) -> Sandbox | None: + """ + Return the sandbox registered under a name. + + Args: + name (str): The registry name. + + Returns: + Sandbox | None: The sandbox, or None if no sandbox has this name. + """ + return self._entries.get(name) + + def get_names(self) -> list[str]: + """ + Return the registered names. + + Returns: + list[str]: The names, sorted. + """ + return self._entries.get_names() + + def unregister(self, name: str) -> Sandbox | None: + """ + Remove a sandbox from the registry, without closing it. + + Args: + name (str): The registry name. + + Returns: + Sandbox | None: The removed sandbox, or None if no sandbox had this name. + """ + with self._lock: + return self._entries.unregister(name) + + async def close_all_async(self) -> None: + """Close every registered sandbox's session once its running call finishes. This never raises.""" + sandboxes = [entry.instance for entry in self._entries.get_all_instances()] + await asyncio.gather(*(sandbox.close_async() for sandbox in sandboxes)) + + +def resolve_sandbox(sandbox: Sandbox | str) -> Sandbox: + """ + Return a sandbox, looking a name up in the process-wide registry. + + Args: + sandbox (Sandbox | str): A sandbox, or the name it is registered under. + + Returns: + Sandbox: The sandbox. + + Raises: + ValueError: If no sandbox is registered under the name. + """ + if not isinstance(sandbox, str): + return sandbox + registry = SandboxRegistry.get_registry_singleton() + found = registry.get(sandbox) + if found is None: + raise ValueError(f"No sandbox is registered as {sandbox!r}; registered: {registry.get_names()}.") + return found diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index ebaebdd636..31d258f386 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -335,7 +335,7 @@ unregister_common_json_schema, ) from pyrit.models.target.request_trace_context import RequestTraceContext - from pyrit.models.target.tool_execution_metadata import ToolExecutionMetadata + from pyrit.models.target.tool_execution_metadata import ToolExecutionMetadata, ToolLoopStop, ToolLoopStopReason _LAZY_EXPORTS: dict[str, str] = { "AdversarialPrompts": "pyrit.models.seeds.adversarial_prompts", @@ -390,6 +390,8 @@ "scenario_dataset_size_from_limit": "pyrit.models.scenario_dataset_size_estimate", "RequestTraceContext": "pyrit.models.target.request_trace_context", "ToolExecutionMetadata": "pyrit.models.target.tool_execution_metadata", + "ToolLoopStop": "pyrit.models.target.tool_execution_metadata", + "ToolLoopStopReason": "pyrit.models.target.tool_execution_metadata", "AttackAnalyticsCell": "pyrit.models.analytics", "AttackAnalyticsConverterDirection": "pyrit.models.analytics", "AttackAnalyticsDimension": "pyrit.models.analytics", diff --git a/pyrit/models/code_execution.py b/pyrit/models/code_execution.py index 10a86ca0e2..50cf6e49e9 100644 --- a/pyrit/models/code_execution.py +++ b/pyrit/models/code_execution.py @@ -81,9 +81,11 @@ class _SandboxRun: ``events`` holds one event per invocation that ran, in invocation order. ``reasons`` explains why any invocations did not run. ``warnings`` reports cleanup problems that do not invalidate - the results already collected. + the results already collected. ``execution_ids`` holds the identifiers a sandbox reported for + the invocations that ran, so its own records can be found; it is empty when it reports none. """ events: tuple[_ProgramExecutionEvent, ...] = () reasons: tuple[str, ...] = () warnings: tuple[str, ...] = () + execution_ids: tuple[str, ...] = () diff --git a/pyrit/models/target/tool_execution_metadata.py b/pyrit/models/target/tool_execution_metadata.py index fe7c165ac1..e505c0237c 100644 --- a/pyrit/models/target/tool_execution_metadata.py +++ b/pyrit/models/target/tool_execution_metadata.py @@ -3,6 +3,7 @@ from __future__ import annotations +from enum import Enum from typing import Any, ClassVar, Self from pydantic import BaseModel, ConfigDict, Field @@ -34,3 +35,38 @@ def from_metadata(cls, *, metadata: dict[str, Any]) -> Self | None: if cls.METADATA_KEY not in metadata: return None return cls.model_validate(metadata[cls.METADATA_KEY]) + + +class ToolLoopStopReason(str, Enum): + """Why a target's tool loop ended a turn before the model gave its answer.""" + + MAX_TOOL_ROUNDS_EXHAUSTED = "max_tool_rounds_exhausted" + TOOL_INFRASTRUCTURE_ERROR = "tool_infrastructure_error" + + +class ToolLoopStop(BaseModel): + """The reason a target recorded on the error response that ended a tool loop early.""" + + METADATA_KEY: ClassVar[str] = "pyrit_tool_loop_stop" + model_config = ConfigDict(frozen=True, extra="forbid") + + reason: ToolLoopStopReason + + def to_metadata(self) -> dict[str, str | int]: + """Return the metadata fragment for the error response.""" + return {self.METADATA_KEY: self.reason.value} + + @classmethod + def from_metadata(cls, *, metadata: dict[str, Any]) -> Self | None: + """ + Read the reason a tool loop stopped. + + Returns: + Self | None: The recorded reason, or None if the loop did not stop early. + + Raises: + ValueError: If the stored reason is unknown. + """ + if cls.METADATA_KEY not in metadata: + return None + return cls(reason=ToolLoopStopReason(metadata[cls.METADATA_KEY])) diff --git a/pyrit/prompt_target/__init__.py b/pyrit/prompt_target/__init__.py index 4615f2552b..76a0a707c8 100644 --- a/pyrit/prompt_target/__init__.py +++ b/pyrit/prompt_target/__init__.py @@ -28,6 +28,7 @@ ) from pyrit.prompt_target.common.prompt_target import PromptTarget from pyrit.prompt_target.common.realtime_audio import ServerVadConfig + from pyrit.prompt_target.common.sandbox_tool_provider import SandboxToolProvider from pyrit.prompt_target.common.target_capabilities import ( CapabilityHandlingPolicy, CapabilityName, @@ -41,6 +42,7 @@ from pyrit.prompt_target.common.tool_provider import ( FunctionTool, Tool, + ToolInfrastructureError, ToolProvider, collect_tools_async, tool, @@ -118,10 +120,12 @@ "RealtimeTarget": "pyrit.prompt_target.openai.openai_realtime_target", "ServerVadConfig": "pyrit.prompt_target.common.realtime_audio", "RoundRobinTarget": "pyrit.prompt_target.round_robin_target", + "SandboxToolProvider": "pyrit.prompt_target.common.sandbox_tool_provider", "TargetCapabilities": "pyrit.prompt_target.common.target_capabilities", "TargetConfiguration": "pyrit.prompt_target.common.target_configuration", "TargetRequirements": "pyrit.prompt_target.common.target_requirements", "Tool": "pyrit.prompt_target.common.tool_provider", + "ToolInfrastructureError": "pyrit.prompt_target.common.tool_provider", "ToolProvider": "pyrit.prompt_target.common.tool_provider", "UnsupportedCapabilityBehavior": "pyrit.prompt_target.common.target_capabilities", "TextTarget": "pyrit.prompt_target.text_target", diff --git a/pyrit/prompt_target/common/sandbox_tool_provider.py b/pyrit/prompt_target/common/sandbox_tool_provider.py new file mode 100644 index 0000000000..2db33ba33a --- /dev/null +++ b/pyrit/prompt_target/common/sandbox_tool_provider.py @@ -0,0 +1,573 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Give a model tools that run its code in a ``Sandbox``.""" + +from __future__ import annotations + +import base64 +import binascii +import json +import re +from typing import TYPE_CHECKING, Any, ClassVar + +from pydantic import BaseModel, ConfigDict, Field + +from pyrit._code_execution import ( + SandboxBusyError, + SandboxExecutionError, + SandboxInputError, + SandboxSessionLostError, + SandboxStateKind, + SandboxUnavailableError, + resolve_sandbox, +) +from pyrit.models.code_execution import _ProgramInvocation +from pyrit.prompt_target.common.tool_provider import Tool, ToolInfrastructureError + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pyrit._code_execution import RuntimeProfile, Sandbox + from pyrit.models.code_execution import _SandboxRun + +_PATH_PATTERN = r"^[^\x00-\x1f\x7f]+$" + +# Every file program starts here. It drops the working directory and the program's own folder from the +# module search path, so a file the model wrote (say, json.py) can't stand in for a standard module, and it +# reports errors briefly, without repeating the path. +_FILE_PROGRAM_PRELUDE = """import os, sys +_ours = {os.getcwd()} | ({os.path.dirname(os.path.abspath(__file__))} if "__file__" in globals() else set()) +sys.path[:] = [entry for entry in sys.path if entry and os.path.abspath(entry) not in _ours] +import base64, json + + +def _report(error): + message = getattr(error, "strerror", None) or str(error) + print(json.dumps({"error": type(error).__name__, "message": message[:300]})) + + +""" + +_WRITE_FILE_PROGRAM = """from pathlib import Path +try: + path = Path({path!r}) + path.parent.mkdir(parents=True, exist_ok=True) + data = base64.b64decode({data!r}) + with path.open({mode!r}) as handle: + handle.write(data) + print(json.dumps({{"bytes_written": len(data)}})) +except (OSError, ValueError) as error: + _report(error) +""" + +_READ_FILE_PROGRAM = """from pathlib import Path +try: + with Path({path!r}).open("rb") as handle: + data = handle.read({limit} + 1) + print(json.dumps({{"data": base64.b64encode(data[:{limit}]).decode("ascii"), "truncated": len(data) > {limit}}})) +except (OSError, ValueError) as error: + _report(error) +""" + +_LIST_DIR_PROGRAM = """try: + entries, size, truncated = [], 0, False + with os.scandir({path!r}) as iterator: + for entry in iterator: + name = entry.name + ("/" if entry.is_dir() else "") + size += len(json.dumps(name)) + 2 + if size > {budget}: + truncated = True + break + entries.append(name) + print(json.dumps({{"entries": sorted(entries), "truncated": truncated}})) +except (OSError, ValueError) as error: + _report(error) +""" + + +class _RunArguments(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + program: str = Field(min_length=1) + arguments: list[str] = Field(default_factory=list, max_length=128) + stdin: str | None = None + timeout_seconds: float | None = Field(default=None, gt=0) + + +class _WriteFileArguments(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + path: str = Field(max_length=1024, pattern=_PATH_PATTERN) + content: str + append: bool = False + + +class _ReadFileArguments(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + path: str = Field(max_length=1024, pattern=_PATH_PATTERN) + + +class _ListDirArguments(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + path: str = Field(default=".", max_length=1024, pattern=_PATH_PATTERN) + + +def _path_schema(description: str) -> dict[str, object]: + return {"type": "string", "description": description, "maxLength": 1024} + + +class _SandboxTool(Tool): + """A tool that runs one program in a sandbox.""" + + def __init__(self, *, sandbox: Sandbox, name: str, description: str, parameters: dict[str, object]) -> None: + super().__init__(name=name, description=description, parameters=parameters) + self._sandbox = sandbox + + async def _run_async( + self, *, program: str, runtime_profile_name: str, invocation: _ProgramInvocation, timeout_seconds: float | None + ) -> _SandboxRun: + """ + Run the program once, turning a sandbox failure into a failure of the tool's infrastructure. + + Returns: + _SandboxRun: The run, with exactly one event. + + Raises: + SandboxInputError: If the sandbox rejected the input; nothing ran. + ToolInfrastructureError: If the sandbox failed, so the model can't fix it. It records whether + anything may have run. + """ + try: + run = await self._sandbox.execute_async( + program=program, + runtime_profile_name=runtime_profile_name, + invocations=(invocation,), + timeout_seconds=timeout_seconds, + ) + except (SandboxBusyError, SandboxSessionLostError, SandboxUnavailableError) as error: + message = f"The sandbox could not run {self.name}, and nothing ran: {error}" + raise ToolInfrastructureError(message, invoked=False) from error + except SandboxExecutionError as error: + raise ToolInfrastructureError(f"The sandbox could not run {self.name}: {error}") from error + if len(run.events) != 1: + raise ToolInfrastructureError(f"The sandbox returned {len(run.events)} results for one run of {self.name}.") + return run + + +class _RunProgramTool(_SandboxTool): + """``run_``: run a program the model wrote.""" + + def __init__(self, *, sandbox: Sandbox, profile: RuntimeProfile, max_output_chars: int) -> None: + capabilities = sandbox.get_capabilities() + if capabilities.state_kind is SandboxStateKind.ENVIRONMENT: + persistence = "Files it writes stay for later calls until the sandbox is reset." + else: + persistence = "Nothing persists between calls." + runtime = profile.description or profile.name + default_timeout = f"{capabilities.default_timeout_seconds:g}" + super().__init__( + sandbox=sandbox, + name=f"run_{profile.tool_name or re.sub(r'[^A-Za-z0-9_]', '_', profile.name)[:60]}", + description=( + f"Run a {runtime} program in {capabilities.description}. Each call runs the program once and returns " + f"its exit code and output as JSON. {persistence} Output past {max_output_chars} characters per " + "stream is cut." + ), + parameters={ + "type": "object", + "properties": { + "program": {"type": "string", "description": f"The {runtime} program to run, verbatim."}, + "arguments": { + "type": "array", + "items": {"type": "string"}, + "description": "Command-line arguments passed to the program.", + }, + "stdin": {"type": "string", "description": "Text passed to the program's standard input."}, + "timeout_seconds": { + "type": "number", + "exclusiveMinimum": 0, + "maximum": capabilities.max_timeout_seconds, + "description": f"Seconds before the program is stopped. Defaults to {default_timeout}.", + }, + }, + "required": ["program"], + "additionalProperties": False, + }, + ) + self._profile_name = profile.name + self._max_output_chars = max_output_chars + + def validate_arguments(self, *, arguments: dict[str, object]) -> None: + """ + Check the call against the schema and the sandbox's limits, without running anything. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Raises: + ValueError: If the arguments are invalid or exceed the sandbox's limits. + """ + values = _RunArguments.model_validate(arguments) + if not values.program.strip(): + raise ValueError("program must not be blank.") + self._sandbox.validate_request( + program=values.program, + runtime_profile_name=self._profile_name, + invocations=(_ProgramInvocation(arguments=tuple(values.arguments), stdin=values.stdin),), + timeout_seconds=values.timeout_seconds, + ) + + async def execute_async(self, *, arguments: dict[str, object]) -> object: + """ + Run the program once. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Returns: + object: The exit code and bounded output, or the reason the sandbox rejected the call. + """ + values = _RunArguments.model_validate(arguments) + invocation = _ProgramInvocation(arguments=tuple(values.arguments), stdin=values.stdin) + try: + run = await self._run_async( + program=values.program, + runtime_profile_name=self._profile_name, + invocation=invocation, + timeout_seconds=values.timeout_seconds, + ) + except SandboxInputError as error: + return {"error": "SandboxInputError", "message": str(error)} + return self._result(run=run) + + def _result(self, *, run: _SandboxRun) -> dict[str, object]: + event, limit = run.events[0], self._max_output_chars + result: dict[str, object] = { + "exit_code": event.exit_code, + "stdout": event.stdout[:limit], + "stderr": event.stderr[:limit], + "stdout_truncated": event.stdout_truncated or len(event.stdout) > limit, + "stderr_truncated": event.stderr_truncated or len(event.stderr) > limit, + "timed_out": event.timed_out, + "resource_limit_exceeded": event.resource_limit_exceeded, + "duration_ms": event.duration_ms, + } + if run.warnings: + result["warnings"] = list(run.warnings) + if run.execution_ids: + result["execution_id"] = run.execution_ids[0] + return result + + +class _FileTool(_SandboxTool): + """A file operation, run as a fixed Python program in the sandbox's file runtime.""" + + def __init__( + self, *, sandbox: Sandbox, name: str, description: str, properties: dict[str, object], required: list[str] + ) -> None: + super().__init__( + sandbox=sandbox, + name=name, + description=description, + parameters={ + "type": "object", + "properties": properties, + "required": required, + "additionalProperties": False, + }, + ) + runtime = sandbox.get_capabilities().file_runtime_profile_name + if runtime is None: + raise ValueError("File tools need a sandbox with a file runtime.") + self._runtime = runtime + + def _validate_program(self, *, program: str) -> None: + """ + Check that the file program fits the sandbox. + + Raises: + SandboxInputError: If it does not. + """ + self._sandbox.validate_request( + program=program, runtime_profile_name=self._runtime, invocations=(_ProgramInvocation(),) + ) + + async def _run_file_program_async(self, *, program: str) -> dict[str, Any]: + """ + Run a file program and read the JSON result it prints. + + Returns: + dict[str, Any]: The result, or the error the model caused. + + Raises: + ToolInfrastructureError: If the program reported no result. + """ + try: + run = await self._run_async( + program=program, + runtime_profile_name=self._runtime, + invocation=_ProgramInvocation(), + timeout_seconds=None, + ) + except SandboxInputError as error: + return {"error": "SandboxInputError", "message": str(error)} + event = run.events[0] + if event.timed_out: + return {"error": "TimeoutError", "message": f"{self.name} did not finish in time."} + try: + result = json.loads(event.stdout) + except ValueError: + result = None + if not isinstance(result, dict): + detail = event.stderr.strip()[:500] or "no output" + raise ToolInfrastructureError(f"{self.name} reported no result (exit code {event.exit_code}): {detail}") + return result + + +class _WriteFileTool(_FileTool): + def __init__(self, *, sandbox: Sandbox) -> None: + super().__init__( + sandbox=sandbox, + name="write_file", + description=( + "Write UTF-8 text to a file in the sandbox, creating missing folders. Paths are relative to the " + "working directory unless absolute. Use append to add to a file, for content too long for one call." + ), + properties={ + "path": _path_schema("The file to write."), + "content": {"type": "string", "description": "The text to write."}, + "append": {"type": "boolean", "description": "Add to the end of the file instead of replacing it."}, + }, + required=["path", "content"], + ) + + def validate_arguments(self, *, arguments: dict[str, object]) -> None: + """ + Check the call, including that the content fits in one program. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Raises: + ValueError: If the arguments are invalid or the content is too long for one call. + SandboxInputError: If the sandbox rejects the call for another reason. + """ + program = self._program(_WriteFileArguments.model_validate(arguments)) + try: + self._validate_program(program=program) + except SandboxInputError as error: + if len(program.encode("utf-8")) <= self._sandbox.get_capabilities().max_input_bytes: + raise + raise ValueError( + "The content is too long for one write_file call; write it in parts, with append for the rest." + ) from error + + async def execute_async(self, *, arguments: dict[str, object]) -> object: + """ + Write the file. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Returns: + object: The path and bytes written, or the error. + """ + values = _WriteFileArguments.model_validate(arguments) + result = await self._run_file_program_async(program=self._program(values)) + return result if "error" in result else {"path": values.path, **result} + + @staticmethod + def _program(values: _WriteFileArguments) -> str: + return _FILE_PROGRAM_PRELUDE + _WRITE_FILE_PROGRAM.format( + path=values.path, + data=base64.b64encode(values.content.encode("utf-8")).decode("ascii"), + mode="ab" if values.append else "wb", + ) + + +class _ReadFileTool(_FileTool): + def __init__(self, *, sandbox: Sandbox, max_output_chars: int) -> None: + output_bytes = sandbox.get_capabilities().max_output_bytes + self._limit = max(min(max_output_chars, (output_bytes - 256) * 3 // 4), 1) + super().__init__( + sandbox=sandbox, + name="read_file", + description=( + f"Read a text file in the sandbox, up to {self._limit} bytes, decoded as UTF-8. Paths are relative to " + "the working directory unless absolute." + ), + properties={"path": _path_schema("The file to read.")}, + required=["path"], + ) + + def validate_arguments(self, *, arguments: dict[str, object]) -> None: + """ + Check the call. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + """ + self._validate_program(program=self._program(_ReadFileArguments.model_validate(arguments))) + + async def execute_async(self, *, arguments: dict[str, object]) -> object: + """ + Read the file. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Returns: + object: The content and whether it was cut, or the error. + + Raises: + ToolInfrastructureError: If the program's result is malformed. + """ + values = _ReadFileArguments.model_validate(arguments) + result = await self._run_file_program_async(program=self._program(values)) + if "error" in result: + return result + try: + data = base64.b64decode(result["data"], validate=True) + except (KeyError, TypeError, binascii.Error) as error: + raise ToolInfrastructureError("read_file reported a malformed result.") from error + return { + "path": values.path, + "content": data.decode("utf-8", errors="replace"), + "truncated": bool(result.get("truncated")), + } + + def _program(self, values: _ReadFileArguments) -> str: + return _FILE_PROGRAM_PRELUDE + _READ_FILE_PROGRAM.format(path=values.path, limit=self._limit) + + +class _ListDirTool(_FileTool): + def __init__(self, *, sandbox: Sandbox, max_output_chars: int) -> None: + self._budget = max(min(max_output_chars, sandbox.get_capabilities().max_output_bytes - 256), 64) + super().__init__( + sandbox=sandbox, + name="list_dir", + description="List a folder in the sandbox. Folder names end with /. Defaults to the working directory.", + properties={"path": _path_schema("The folder to list.")}, + required=[], + ) + + def validate_arguments(self, *, arguments: dict[str, object]) -> None: + """ + Check the call. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + """ + self._validate_program(program=self._program(_ListDirArguments.model_validate(arguments))) + + async def execute_async(self, *, arguments: dict[str, object]) -> object: + """ + List the folder. + + Args: + arguments (dict[str, object]): Arguments supplied by the model. + + Returns: + object: The entries and whether the list was cut, or the error. + """ + return await self._run_file_program_async(program=self._program(_ListDirArguments.model_validate(arguments))) + + def _program(self, values: _ListDirArguments) -> str: + return _FILE_PROGRAM_PRELUDE + _LIST_DIR_PROGRAM.format(path=values.path, budget=self._budget) + + +class SandboxToolProvider: + """ + Give a model tools that run its code in a ``Sandbox``. + + Each runtime becomes a ``run_`` tool, such as ``run_python``; the name comes from the + runtime's ``tool_name``, or else from its name. An ``environment`` sandbox with a file runtime also + offers ``write_file``, ``read_file`` and ``list_dir``, which run as small Python programs. Each call + runs once, and its result is JSON: the exit code and output, cut at ``max_output_chars`` per stream. + Arguments are checked against the sandbox's limits before anything runs, so a rejected call is never + recorded as invoked. A sandbox failure raises ``ToolInfrastructureError``, so a target with a bounded + tool loop ends the turn instead of asking the model to fix it. + + Experimental: it is built on ``pyrit._code_execution``, which may change without a deprecation cycle. + """ + + DEFAULT_MAX_OUTPUT_CHARS: ClassVar[int] = 32_768 + + def __init__( + self, + *, + sandbox: Sandbox | str, + tool_names: Sequence[str] | None = None, + max_output_chars: int = DEFAULT_MAX_OUTPUT_CHARS, + ) -> None: + """ + Build the tools a sandbox can offer. + + Args: + sandbox (Sandbox | str): The sandbox, or its name in the ``SandboxRegistry``. + tool_names (Sequence[str] | None): The tools to offer, in order. Defaults to every tool the + sandbox supports. + max_output_chars (int): The most characters of each output stream a result keeps. + + Raises: + ValueError: If a tool is not offered or repeats, two runtimes would share a tool name, or + the output limit is not positive. + """ + if max_output_chars < 1: + raise ValueError("max_output_chars must be positive.") + self._sandbox = resolve_sandbox(sandbox) + self._max_output_chars = max_output_chars + built = self._build_tools() + available = {tool.name: tool for tool in built} + if len(available) != len(built): + raise ValueError("Two runtimes would share a tool name; give one of them a distinct tool_name.") + names = list(available) if tool_names is None else list(tool_names) + unknown = [name for name in names if name not in available] + if unknown: + raise ValueError(f"The sandbox does not offer tools {unknown}; available: {sorted(available)}.") + if len(set(names)) != len(names): + raise ValueError("tool_names must not repeat.") + self._tools: list[Tool] = [available[name] for name in names] + + @property + def identifier(self) -> dict[str, object]: + """Non-secret configuration: the sandbox's identity, the tools, and the output limit.""" + sandbox = self._sandbox.get_identifier() + return { + "type": type(self).__name__, + "sandbox": {"class_name": sandbox.class_name, "params": sandbox.params, "hash": sandbox.hash}, + "tools": [tool.name for tool in self._tools], + "max_output_chars": self._max_output_chars, + } + + async def get_tools_async(self) -> list[Tool]: + """ + Return the configured tools. + + Returns: + list[Tool]: The tools, in configuration order. + """ + return list(self._tools) + + def _build_tools(self) -> list[Tool]: + """ + Build every tool the sandbox supports. + + Returns: + list[Tool]: The tools. + """ + capabilities = self._sandbox.get_capabilities() + tools: list[Tool] = [ + _RunProgramTool(sandbox=self._sandbox, profile=profile, max_output_chars=self._max_output_chars) + for profile in capabilities.runtime_profiles + ] + if capabilities.state_kind is SandboxStateKind.ENVIRONMENT and capabilities.file_runtime_profile_name: + tools += [ + _WriteFileTool(sandbox=self._sandbox), + _ReadFileTool(sandbox=self._sandbox, max_output_chars=self._max_output_chars), + _ListDirTool(sandbox=self._sandbox, max_output_chars=self._max_output_chars), + ] + return tools diff --git a/pyrit/prompt_target/common/tool_provider.py b/pyrit/prompt_target/common/tool_provider.py index 9200e4a1ad..db85e43b22 100644 --- a/pyrit/prompt_target/common/tool_provider.py +++ b/pyrit/prompt_target/common/tool_provider.py @@ -15,6 +15,28 @@ from contextlib import AbstractAsyncContextManager +class ToolInfrastructureError(Exception): + """ + A tool could not run because its own infrastructure failed, not because of the model's call. + + For example, the sandbox a code-execution tool runs in became unreachable, or a call's outcome is + unknown. Targets with a bounded tool loop, such as ``OpenAIResponseTarget``, end the turn with an + error response instead of asking the model to fix a failure that isn't its own. ``invoked`` is False + when the tool knows nothing ran, so the call is not recorded as invoked. + """ + + def __init__(self, message: str, *, invoked: bool = True) -> None: + """ + Initialize the error. + + Args: + message (str): What failed. + invoked (bool): Whether the tool may have run. Defaults to True, since the outcome is unknown. + """ + super().__init__(message) + self.invoked = invoked + + class Tool(ABC): """A tool that a target can advertise and execute.""" diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index e1b8f7696e..bd4f6d4d5c 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -35,14 +35,23 @@ PromptDataType, PromptResponseError, ToolExecutionMetadata, + ToolLoopStop, + ToolLoopStopReason, WebSearchConfig, WebSearchMode, + construct_response_from_request, ) from pyrit.models.messages.chat_message import FunctionCall from pyrit.prompt_target.common.target_capabilities import TargetCapabilities from pyrit.prompt_target.common.target_configuration import TargetConfiguration from pyrit.prompt_target.common.tool_call_history import parse_function_call, parse_function_call_output -from pyrit.prompt_target.common.tool_provider import Tool, ToolProvider, _ScopedToolProvider, collect_tools_async +from pyrit.prompt_target.common.tool_provider import ( + Tool, + ToolInfrastructureError, + ToolProvider, + _ScopedToolProvider, + collect_tools_async, +) from pyrit.prompt_target.common.utils import ( build_empty_truncated_response, limit_requests_per_minute, @@ -117,6 +126,7 @@ class OpenAIResponseTarget(OpenAITarget): """ _SUPPORTS_TOOL_CALL_HISTORY = True + _MAX_ERROR_MESSAGE_CHARS = 2_000 _WEB_SEARCH_TOOL_TYPES = frozenset({"web_search", "web_search_preview"}) _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( capabilities=TargetCapabilities( @@ -154,6 +164,7 @@ def __init__( extra_body_parameters: dict[str, Any] | None = None, fail_on_missing_function: bool = False, execute_tools: bool = True, + max_tool_rounds: int = 10, custom_configuration: TargetConfiguration | None = None, **kwargs: Any, ) -> None: @@ -197,6 +208,10 @@ def __init__( the first response without running registered functions. Tool discovery, provider scopes, and advertisement remain enabled. This does not disable provider-hosted tools configured in extra_body_parameters. + max_tool_rounds (int): The most model responses per send whose calls run locally. Calls in + a later response get error results without running, and the send ends with an error + response. A tool raising ``ToolInfrastructureError`` also ends the send with an error + response, after every call in its round has a result. Defaults to 10. custom_configuration (TargetConfiguration, Optional): Override the default configuration for this target instance. Defaults to None. **kwargs: Additional keyword arguments passed to the parent OpenAITarget class. @@ -209,6 +224,7 @@ def __init__( PyritException: If the temperature or top_p values are out of bounds. ValueError: If the temperature is not between 0 and 2 (inclusive). ValueError: If the top_p is not between 0 and 1 (inclusive). + ValueError: If max_tool_rounds is not a nonnegative integer. RateLimitException: If the target is rate-limited. httpx.HTTPStatusError: If the request fails with a 400 Bad Request or 429 Too Many Requests error. json.JSONDecodeError: If the response from the target is not valid JSON. @@ -219,6 +235,9 @@ def __init__( # Validate temperature and top_p validate_temperature(temperature) validate_top_p(top_p) + if isinstance(max_tool_rounds, bool) or not isinstance(max_tool_rounds, int) or max_tool_rounds < 0: + raise ValueError("max_tool_rounds must be a nonnegative integer.") + self._max_tool_rounds = max_tool_rounds self._temperature = temperature self._top_p = top_p @@ -311,9 +330,19 @@ def _build_identifier(self) -> ComponentIdentifier: ) or None, "tool_providers": [provider.identifier for provider in self._tool_providers] or None, + "max_tool_rounds": self._max_tool_rounds if self._has_local_tools() else None, }, ) + def _has_local_tools(self) -> bool: + """ + Whether this target runs any tools itself. + + Returns: + bool: True if tools, tool providers or custom functions are configured. + """ + return bool(self._direct_tools or self._tool_providers or self._custom_functions) + def _set_openai_env_configuration_vars(self) -> None: self.model_name_environment_variable = "OPENAI_RESPONSES_MODEL" self.endpoint_environment_variable = "OPENAI_RESPONSES_ENDPOINT" @@ -752,6 +781,7 @@ async def _run_tool_call_loop_async(self, *, normalized_conversation: list[Messa # Track all responses generated during this interaction responses_to_return: list[Message] = [] + rounds = 0 while True: logger.info(f"Sending conversation with {len(working_conversation)} messages to the prompt target") @@ -773,20 +803,136 @@ async def _run_tool_call_loop_async(self, *, normalized_conversation: list[Messa if not tool_call_sections: break - for tool_call_section in tool_call_sections: - tool_output = await self._execute_call_section_async(tool_call_section) - tool_piece = self._make_tool_piece( - result=tool_output, - call_id=tool_call_section["call_id"], - reference_piece=message_piece, + if rounds >= self._max_tool_rounds: + responses_to_return.extend( + self._answer_calls_without_running( + sections=tool_call_sections, + output={"error": "max_tool_rounds_exhausted"}, + reference_piece=message_piece, + ) ) - tool_message = Message(message_pieces=[tool_piece]) - working_conversation.append(tool_message) - responses_to_return.append(tool_message) + detail = f"max_tool_rounds={self._max_tool_rounds} exhausted." + stop = ToolLoopStopReason.MAX_TOOL_ROUNDS_EXHAUSTED + responses_to_return.append( + self._tool_loop_error(request_piece=message_piece, detail=detail, reason=stop) + ) + return responses_to_return + rounds += 1 + + tool_messages, failure = await self._execute_tool_round_async( + sections=tool_call_sections, reference_piece=message_piece + ) + working_conversation.extend(tool_messages) + responses_to_return.extend(tool_messages) + if failure is not None: + stop = ToolLoopStopReason.TOOL_INFRASTRUCTURE_ERROR + responses_to_return.append( + self._tool_loop_error(request_piece=message_piece, detail=failure, reason=stop) + ) + return responses_to_return # Return all responses (normalizer will persist all of them to memory) return responses_to_return + async def _execute_tool_round_async( + self, *, sections: list[dict[str, Any]], reference_piece: MessagePiece + ) -> tuple[list[Message], str | None]: + """ + Run one response's tool calls in order, stopping at a tool infrastructure failure. + + Args: + sections: The response's function calls. + reference_piece: A piece to copy conversation context from. + + Returns: + One result message per call, and why the turn must end, or None to continue. After a + failure, the calls not yet run get error results, so every call is answered. + """ + messages: list[Message] = [] + for index, section in enumerate(sections): + try: + result = await self._execute_call_section_async(section) + except ToolInfrastructureError as error: + logger.error("Tool %r could not run; ending the turn: %s", section.get("name"), error) + # The model sees this result again on later turns, so it gets no infrastructure details; + # they stay in the error response, which history replay skips. + failed = _ToolDispatchResult( + output={"error": "tool_infrastructure_error", "message": "The tool's infrastructure failed."}, + invoked=error.invoked, + ) + messages.append( + self._make_tool_message(result=failed, section=section, reference_piece=reference_piece) + ) + messages.extend( + self._answer_calls_without_running( + sections=sections[index + 1 :], + output={"error": "tool_not_executed", "message": "An earlier tool call failed."}, + reference_piece=reference_piece, + ) + ) + return messages, f"Tool {section.get('name')!r} could not run: {error}" + messages.append(self._make_tool_message(result=result, section=section, reference_piece=reference_piece)) + return messages, None + + def _answer_calls_without_running( + self, *, sections: Sequence[dict[str, Any]], output: dict[str, str], reference_piece: MessagePiece + ) -> list[Message]: + """ + Give calls that will not run an error result, so the history keeps every call answered. + + Args: + sections: The calls. + output: The error result each call gets. + reference_piece: A piece to copy conversation context from. + + Returns: + One result message per call, recorded as not invoked. + """ + result = _ToolDispatchResult(output=output, invoked=False) + return [ + self._make_tool_message(result=result, section=section, reference_piece=reference_piece) + for section in sections + ] + + def _make_tool_message( + self, *, result: _ToolDispatchResult, section: dict[str, Any], reference_piece: MessagePiece + ) -> Message: + """ + Wrap a call's result in a message. + + Args: + result: The dispatch result to record. + section: The function call it answers. + reference_piece: A piece to copy conversation context from. + + Returns: + A message with one function_call_output piece. + """ + piece = self._make_tool_piece(result=result, call_id=section["call_id"], reference_piece=reference_piece) + return Message(message_pieces=[piece]) + + @staticmethod + def _tool_loop_error(*, request_piece: MessagePiece, detail: str, reason: ToolLoopStopReason) -> Message: + """ + Build the error response that ends a turn whose tools could not continue. + + Args: + request_piece: The request the turn answers. + detail: Why the turn ended. + reason: The machine-readable reason, recorded in the response's metadata. + + Returns: + An error response, which history replay skips. + """ + logger.error(detail) + return construct_response_from_request( + request=request_piece, + response_text_pieces=[detail], + response_type="error", + prompt_metadata=ToolLoopStop(reason=reason).to_metadata(), + error="processing", + ) + @pyrit_target_retry @limit_requests_per_minute async def _send_model_request_async(self, *, body: dict[str, Any], request: Message) -> Message: @@ -1059,7 +1205,12 @@ async def _execute_call_section_async(self, tool_call_section: dict[str, Any]) - raise logger.warning("Invalid arguments for function '%s': %s", name, exc) return _ToolDispatchResult( - output={"error": "malformed_arguments", "function": name, "raw_arguments": args_json}, + output={ + "error": "malformed_arguments", + "function": name, + "raw_arguments": args_json, + "message": str(exc)[: self._MAX_ERROR_MESSAGE_CHARS], + }, invoked=False, ) return _ToolDispatchResult(output=await configured_tool.execute_async(arguments=args), invoked=True) diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index 9ff1f930c9..8f72ff28c4 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -134,6 +134,7 @@ from pyrit.score.true_false.regex.static_prompt_injection_scorer import StaticPromptInjectionScorer from pyrit.score.true_false.regex.xss_output_scorer import XSSOutputScorer from pyrit.score.true_false.regex.xxe_output_scorer import XXEOutputScorer + from pyrit.score.true_false.sandbox_check_scorer import SandboxCheckScorer from pyrit.score.true_false.self_ask_category_scorer import ( ContentClassifier, ContentClassifierCategory, @@ -175,6 +176,7 @@ "get_assert_failure_criterion": "pyrit.score.true_false.assert_policy_scorer", "ProgramExecutionScorer": "pyrit.score.true_false.program_execution_scorer", "ProgramExecutionSource": "pyrit.score.observation.program_execution_source", + "SandboxCheckScorer": "pyrit.score.true_false.sandbox_check_scorer", "OutputMatchesScorer": "pyrit.score.true_false.output_matches_scorer", "AnsiEscapeOutputScorer": "pyrit.score.true_false.regex.ansi_escape_output_scorer", "AnthraxKeywordScorer": "pyrit.score.true_false.regex.anthrax_keyword_scorer", diff --git a/pyrit/score/observation/program_execution_source.py b/pyrit/score/observation/program_execution_source.py index 878027a3af..aa47ab7a76 100644 --- a/pyrit/score/observation/program_execution_source.py +++ b/pyrit/score/observation/program_execution_source.py @@ -9,7 +9,7 @@ import logging from typing import TYPE_CHECKING -from pyrit._code_execution import SandboxExecutionError +from pyrit._code_execution import SandboxExecutionError, SandboxInputError from pyrit.memory import CentralMemory from pyrit.models import ( Acquisition, @@ -41,10 +41,12 @@ class ProgramExecutionSource: references. A message must contain exactly one text piece; blocked or failed responses leave evidence unavailable. Code is not extracted from prose. - Each acquisition runs afresh and returns a new observation. Program failures are execution + Each acquisition runs the program again and returns a new observation. A sandbox may keep state + between calls, so a program can observe what earlier calls left. Program failures are execution evidence; infrastructure failures are acquisition errors. A run that stops after some invocations leaves partial evidence. Streams retain at most ``max_output_chars`` characters - with truncation flags, and cleanup warnings remain in ``sandbox_warnings`` metadata. + with truncation flags. Cleanup warnings remain in ``sandbox_warnings`` metadata, and the + sandbox's own run identifiers, when it reports them, in ``sandbox_execution_ids``. """ def __init__(self, *, sandbox: SandboxClient, max_output_chars: int = 64_000) -> None: @@ -106,6 +108,10 @@ async def acquire_async(self, *, scorable: ProgramExecutionScorable) -> Observat runtime_profile_name=scorable.runtime_profile_name, invocations=scorable.invocations, ) + except SandboxInputError as error: + return self._observation( + scorable=scorable, acquisition=Acquisition.UNAVAILABLE, reasons=(f"the sandbox rejected it: {error}",) + ) except SandboxExecutionError as error: logger.warning("Sandbox could not run program under %s: %s", scorable.runtime_profile_name, error) return self._observation( @@ -129,8 +135,13 @@ async def acquire_async(self, *, scorable: ProgramExecutionScorable) -> Observat program_sha256=program_sha256 if events else None, reasons=reasons, ) + metadata: dict[str, str] = {} if run.warnings: - observation = observation.model_copy(update={"metadata": {"sandbox_warnings": "; ".join(run.warnings)}}) + metadata["sandbox_warnings"] = "; ".join(run.warnings) + if run.execution_ids: + metadata["sandbox_execution_ids"] = ", ".join(run.execution_ids) + if metadata: + observation = observation.model_copy(update={"metadata": metadata}) return observation async def _resolve_program_async(self, *, scorable: ProgramExecutionScorable) -> str: diff --git a/pyrit/score/true_false/sandbox_check_scorer.py b/pyrit/score/true_false/sandbox_check_scorer.py new file mode 100644 index 0000000000..6714110e15 --- /dev/null +++ b/pyrit/score/true_false/sandbox_check_scorer.py @@ -0,0 +1,197 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Score a response by running a fixed check program in the sandbox the model's code ran in.""" + +from __future__ import annotations + +import hashlib +from typing import TYPE_CHECKING + +from pyrit._code_execution import SandboxStateKind, resolve_sandbox +from pyrit.models import ( + ContentEntryScorable, + ContentScorable, + MessageScorable, + ProgramExecutionObservationPayload, + ProgramExecutionScorable, + Score, + ScoreStatus, +) +from pyrit.score.observation.execution import NonReplayableObservationError, _collect_observation +from pyrit.score.observation.program_execution_source import ProgramExecutionSource +from pyrit.score.true_false.program_execution_scorer import _evaluate_program, _Evaluation +from pyrit.score.true_false.true_false_scorer import TrueFalseScorer + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pyrit._code_execution import Sandbox + from pyrit.models import ( + Acquisition, + ComponentIdentifier, + Observation, + ProgramBehaves, + Scorable, + ScorableUnion, + ScoringExpectation, + ) + from pyrit.score.observation.execution import _ObservationEvidence + + +class SandboxCheckScorer(TrueFalseScorer): + """ + Score a response by what a fixed check program finds in a sandbox, not by what the response says. + + After a turn, the check runs in the sandbox the model's code ran in, so it sees what that code left + behind. The response's own text never runs. ``condition`` gives the check's runtime, its invocations, + and the result each must produce: every case passing scores true, and a failing case scores false. A + sandbox failure, or a check that times out or exceeds a resource limit, leaves the score undetermined, + never false. The check's program and output are stored as an observation linked to the score. + + The verdict reflects the sandbox when the check runs, so every call runs the check again; stored + verdicts are never reused. Callers own isolation, since a later attempt could otherwise score true on + an earlier attempt's effect: run one attempt at a time per sandbox, without automatic retries of failed + attempts, and reset the sandbox between attempts. The check runs as the same account as the model's + code, so it must not trust files the model could have written. + + Experimental: it is built on ``pyrit._code_execution``, which may change without a deprecation cycle. + """ + + SUPPORTED_SCORABLE_TYPES = (MessageScorable, ContentScorable, ContentEntryScorable) + + def __init__( + self, + *, + sandbox: Sandbox | str, + check_program: str, + condition: ProgramBehaves, + max_output_chars: int = 64_000, + ) -> None: + """ + Initialize with the check and the sandbox it runs in. + + Args: + sandbox (Sandbox | str): The sandbox the model's code runs in, or its name in the + ``SandboxRegistry``. Its state must persist between calls. + check_program (str): The program that looks for the effect. + condition (ProgramBehaves): The check's runtime, invocations and expected results. + max_output_chars (int): The most characters of each output stream kept as evidence. + + Raises: + ValueError: If the check is empty, the sandbox keeps no state between calls, or it does not + offer the check's runtime. + """ + if not check_program.strip(): + raise ValueError("check_program must not be empty.") + resolved = resolve_sandbox(sandbox) + if resolved.get_capabilities().state_kind is not SandboxStateKind.ENVIRONMENT: + raise ValueError("A check needs a sandbox whose state persists, so it can see what the model's code did.") + if condition.runtime_profile_name not in resolved.get_runtime_profile_names(): + raise ValueError( + f"The sandbox does not offer runtime {condition.runtime_profile_name!r}; " + f"available: {sorted(resolved.get_runtime_profile_names())}." + ) + super().__init__() + self._check_program = check_program + self._condition = condition + self._source = ProgramExecutionSource(sandbox=resolved, max_output_chars=max_output_chars) + + def find_matching_scores( + self, + *, + scores: Sequence[Score], + scorable: Scorable, + expectation: ScoringExpectation | None = None, + ) -> list[Score]: + """ + Match no stored result: a check reads the sandbox as it is now, so an earlier verdict may be stale. + + Args: + scores (Sequence[Score]): Candidate results. + scorable (Scorable): The evidence a new evaluation would read. + expectation (ScoringExpectation | None): The input a new evaluation would receive. + + Returns: + list[Score]: Always empty. + """ + self.prepare_expectation(expectation=expectation) + return [] + + def _build_identifier(self) -> ComponentIdentifier: + return self._create_identifier( + params={ + "check_sha256": hashlib.sha256(self._check_program.encode("utf-8")).hexdigest(), + "condition": self._condition.model_dump(mode="json"), + }, + children={"source": self._source.get_identifier()}, + ) + + async def _score_scorable_async(self, *, scorable: Scorable, expectation: ScoringExpectation | None) -> list[Score]: + if not isinstance(scorable, (MessageScorable, ContentScorable, ContentEntryScorable)): + raise TypeError("SandboxCheckScorer scores a MessageScorable, ContentScorable, or ContentEntryScorable.") + check = ProgramExecutionScorable( + program=ContentScorable(value=self._check_program), + runtime_profile_name=self._condition.runtime_profile_name, + invocations=self._condition.invocations, + ) + observation = await self._source.acquire_async(scorable=check) + if not isinstance(observation.payload, ProgramExecutionObservationPayload): + raise ValueError("The program execution source returned incompatible evidence.") + _collect_observation(observation) + return [self._build_score(payload=observation.payload, observation=observation, anchor=scorable)] + + def _score_observation( + self, + *, + observation: Observation, + evidence: _ObservationEvidence, + expectation: ScoringExpectation | None, + ) -> list[Score]: + """ + Judge a stored run of this check again, without running it. + + Returns: + list[Score]: The verdict on the stored output. + + Raises: + NonReplayableObservationError: If the observation is not a run of this check. + """ + check = observation.scorable + if ( + not isinstance(evidence, ProgramExecutionObservationPayload) + or not isinstance(check, ProgramExecutionScorable) + or check.program != ContentScorable(value=self._check_program) + or (check.runtime_profile_name, check.invocations) + != (self._condition.runtime_profile_name, self._condition.invocations) + ): + raise NonReplayableObservationError("The observation is not a stored run of this check.") + return [self._build_score(payload=evidence, observation=observation, anchor=check)] + + def _build_score( + self, *, payload: ProgramExecutionObservationPayload, observation: Observation, anchor: ScorableUnion + ) -> Score: + evaluation = self._evaluate(payload=payload, acquisition=observation.acquisition) + return Score( + score_value=None if evaluation.value is None else str(evaluation.value).lower(), + status=ScoreStatus.UNDETERMINED if evaluation.value is None else ScoreStatus.COMPLETE, + score_type="true_false", + score_rationale=f"Check program: {evaluation.rationale}", + score_value_description="The check program found the expected effect in the sandbox.", + scorer_class_identifier=self.get_identifier(), + scorable=anchor, + message_piece_id=self._piece_id_from_scorable(anchor), + observation_ids=[observation.id], + ) + + def _evaluate(self, *, payload: ProgramExecutionObservationPayload, acquisition: Acquisition) -> _Evaluation: + """ + Evaluate the check's output; a check that did not finish says nothing about the effect. + + Returns: + _Evaluation: The verdict and its explanation. + """ + unfinished = [event for event in payload.events if event.timed_out or event.resource_limit_exceeded] + if unfinished: + return _Evaluation(value=None, rationale="The check did not finish: it timed out or hit a resource limit.") + return _evaluate_program(condition=self._condition, payload=payload, acquisition=acquisition) diff --git a/pyrit/setup/configuration_loader.py b/pyrit/setup/configuration_loader.py index 417ec2ca92..bcce7c4b8c 100644 --- a/pyrit/setup/configuration_loader.py +++ b/pyrit/setup/configuration_loader.py @@ -771,6 +771,7 @@ async def apply_prepared_reinitialization_async(self, *, prepared: PreparedReini Raises: RuntimeError: If no live memory instance exists. """ + from pyrit._code_execution import SandboxRegistry from pyrit.registry import InitializerRegistry from pyrit.setup.initialization import reset_setup_registries, validate_reinitialization_memory @@ -780,6 +781,8 @@ async def apply_prepared_reinitialization_async(self, *, prepared: PreparedReini ) if memory is None: raise RuntimeError("Live reinitialization requires initialized memory.") + # Initializers register new objects for the same sandboxes, so the old ones must not keep sessions. + await SandboxRegistry.get_registry_singleton().close_all_async() reset_setup_registries() InitializerRegistry.set_registry_singleton(prepared.initializer_registry) await reinitialize_pyrit_async( diff --git a/pyrit/setup/initialization.py b/pyrit/setup/initialization.py index 31963958cc..3864c7129e 100644 --- a/pyrit/setup/initialization.py +++ b/pyrit/setup/initialization.py @@ -64,6 +64,7 @@ def validate_reinitialization_memory(*, memory_db_type: str, environment: dict[s def reset_setup_registries() -> None: """Discard only PyRIT's setup-owned registries, not persistence singletons.""" + from pyrit._code_execution import SandboxRegistry from pyrit.registry import ( AttackRegistry, AttackTechniqueRegistry, @@ -87,6 +88,7 @@ def reset_setup_registries() -> None: ScenarioSuiteRegistry, ScorerRegistry, TargetRegistry, + SandboxRegistry, ): registry.reset_registry_singleton() diff --git a/tests/integration/score/test_program_execution_scorer_integration.py b/tests/integration/score/test_program_execution_scorer_integration.py index 0261fd21ea..62bfe4e8cd 100644 --- a/tests/integration/score/test_program_execution_scorer_integration.py +++ b/tests/integration/score/test_program_execution_scorer_integration.py @@ -268,8 +268,11 @@ async def test_missing_image_is_undetermined_async( async def test_cancelling_real_execution_cleans_up_async(docker_sandbox: DockerSandboxClient) -> None: scorer = ProgramExecutionScorer(source=ProgramExecutionSource(sandbox=docker_sandbox)) + longer_runs = docker_sandbox.get_capabilities().model_copy( + update={"default_timeout_seconds": 30.0, "max_timeout_seconds": 30.0} + ) with ( - patch.object(docker_sandbox, "_timeout_seconds", 30), + patch.object(docker_sandbox, "_capabilities", longer_runs), patch.object(docker_sandbox, "_run_arguments", wraps=docker_sandbox._run_arguments) as arguments, ): task = asyncio.create_task( diff --git a/tests/unit/_code_execution/local_python_sandbox.py b/tests/unit/_code_execution/local_python_sandbox.py new file mode 100644 index 0000000000..fdb77c3683 --- /dev/null +++ b/tests/unit/_code_execution/local_python_sandbox.py @@ -0,0 +1,160 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""A test-only sandbox that runs Python programs as local subprocesses. It isolates nothing.""" + +from __future__ import annotations + +import asyncio +import shutil +import sys +import tempfile +import uuid +from pathlib import Path + +from pyrit._code_execution import ( + ProcessResult, + RuntimeProfile, + Sandbox, + SandboxCapabilities, + SandboxRevisionChangedError, + SandboxSessionLostError, + SandboxStateKind, + SandboxStatus, +) +from pyrit.models import ComponentIdentifier + + +class LocalPythonSandbox(Sandbox): + """ + Run Python programs with the test interpreter, for tests of PyRIT's own programs only. + + An ``environment`` sandbox keeps one working directory across calls and sessions, and a reset empties + it. A ``call`` sandbox runs each program in a new, empty directory. With ``isolated=False``, Python runs + without ``-I`` and the program is saved in the working directory, as a careless adapter might do. + """ + + def __init__( + self, + *, + root: Path, + state_kind: SandboxStateKind = SandboxStateKind.ENVIRONMENT, + max_output_bytes: int = 4_096, + isolated: bool = True, + ) -> None: + super().__init__() + self._root = root + self._state_kind = state_kind + self._max_output_bytes = max_output_bytes + self._isolated = isolated + self.workspace = root / "workspace" + self.workspace.mkdir(parents=True, exist_ok=True) + (root / "programs").mkdir(exist_ok=True) + self.sessions: set[str] = set() + self.revision = "local-revision-1" + + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self, params={"root": str(self._root), "state_kind": self._state_kind.value}) + + def _get_capabilities(self) -> SandboxCapabilities: + environment = self._state_kind is SandboxStateKind.ENVIRONMENT + return SandboxCapabilities( + runtime_profiles=(RuntimeProfile(name="python", description="Python 3"),), + state_kind=self._state_kind, + description="a local test directory", + supports_reset=environment, + file_runtime_profile_name="python" if environment else None, + max_output_bytes=self._max_output_bytes, + ) + + async def _execute_async( + self, + *, + session_id: str | None, + runtime_profile_name: str, + program: str, + arguments: tuple[str, ...], + stdin: str | None, + timeout_seconds: float, + ) -> ProcessResult: + if self._state_kind is SandboxStateKind.ENVIRONMENT and session_id not in self.sessions: + raise SandboxSessionLostError(f"Session {session_id} is not open.") + working_dir = self.workspace if session_id is not None else self._new_call_directory() + program_dir = self._root / "programs" if self._isolated else working_dir + program_path = program_dir / f"program_{uuid.uuid4().hex}.py" + await asyncio.to_thread(program_path.write_text, program, encoding="utf-8") + try: + return await self._run_async( + program_path=program_path, + working_dir=working_dir, + arguments=arguments, + stdin=stdin, + timeout_seconds=timeout_seconds, + ) + finally: + await asyncio.to_thread(program_path.unlink) + if session_id is None: + await asyncio.to_thread(shutil.rmtree, working_dir, True) + + async def _run_async( + self, + *, + program_path: Path, + working_dir: Path, + arguments: tuple[str, ...], + stdin: str | None, + timeout_seconds: float, + ) -> ProcessResult: + process = await asyncio.create_subprocess_exec( + sys.executable, + *(["-I"] if self._isolated else []), + "-X", + "utf8", + str(program_path), + *arguments, + cwd=working_dir, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + timed_out = False + try: + stdout, stderr = await asyncio.wait_for( + process.communicate((stdin or "").encode("utf-8")), timeout=timeout_seconds + ) + except TimeoutError: + stdout, stderr = await self._stop_async(process) + timed_out = True + limit = self._max_output_bytes + return ProcessResult( + exit_code=None if timed_out else process.returncode, + stdout=stdout[:limit].decode("utf-8", errors="replace"), + stderr=stderr[:limit].decode("utf-8", errors="replace"), + stdout_truncated=len(stdout) > limit, + stderr_truncated=len(stderr) > limit, + timed_out=timed_out, + ) + + async def _stop_async(self, process: asyncio.subprocess.Process) -> tuple[bytes, bytes]: + process.kill() + return await process.communicate() + + def _new_call_directory(self) -> Path: + return Path(tempfile.mkdtemp(dir=self._root)) + + async def _open_session_async(self, *, owner: str) -> str: + session_id = uuid.uuid4().hex + self.sessions.add(session_id) + return session_id + + async def _close_session_async(self, *, session_id: str) -> None: + self.sessions.discard(session_id) + + async def _get_status_async(self) -> SandboxStatus: + return SandboxStatus(revision=self.revision, details={"workspace": str(self.workspace)}) + + async def _reset_async(self, *, expected_revision: str | None) -> None: + if expected_revision is not None and expected_revision != self.revision: + raise SandboxRevisionChangedError(f"The revision is {self.revision}.") + await asyncio.to_thread(shutil.rmtree, self.workspace) + self.workspace.mkdir() diff --git a/tests/unit/_code_execution/test_docker_client.py b/tests/unit/_code_execution/test_docker_client.py index 5effabe9a9..21e48dd933 100644 --- a/tests/unit/_code_execution/test_docker_client.py +++ b/tests/unit/_code_execution/test_docker_client.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +import json import os import stat import threading @@ -14,10 +15,21 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest - -from pyrit._code_execution import DockerRuntimeProfile, DockerSandboxClient, SandboxExecutionError +from openai.types.responses import ResponseOutputText + +from pyrit._code_execution import ( + DockerRuntimeProfile, + DockerSandboxClient, + Sandbox, + SandboxClient, + SandboxExecutionError, + SandboxInputError, + SandboxStateKind, +) from pyrit._code_execution.docker_client import _ClientOutput, _ContainerState, _InvocationResult +from pyrit.models import MessagePiece from pyrit.models.code_execution import _ProgramInvocation, _SandboxRun +from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider if TYPE_CHECKING: from pathlib import Path @@ -96,9 +108,12 @@ async def command_async(*arguments: str) -> tuple[int, str]: return AsyncMock(side_effect=command_async) -async def _run_async(client: DockerSandboxClient) -> _SandboxRun: +async def _run_async(client: DockerSandboxClient, *, timeout_seconds: float | None = None) -> _SandboxRun: return await client.execute_async( - program="print('ok')", runtime_profile_name="python", invocations=(_ProgramInvocation(),) + program="print('ok')", + runtime_profile_name="python", + invocations=(_ProgramInvocation(),), + timeout_seconds=timeout_seconds, ) @@ -283,15 +298,14 @@ async def test_deadline_distinguishes_stalled_capture_client_and_program_async( ) -> None: process, control = _process(returncode=None, eof=eof), _control(state=state) with ( - patch.object(client, "_timeout_seconds", 0.05), patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=process), patch.object(client, "_control_async", control), ): if error is not None: with pytest.raises(SandboxExecutionError, match=error): - await _run_async(client) + await _run_async(client, timeout_seconds=0.05) else: - event = (await _run_async(client)).events[0] + event = (await _run_async(client, timeout_seconds=0.05)).events[0] assert event.timed_out is (not eof) assert event.exit_code == (0 if eof else None) assert event.stdout_truncated and event.stderr_truncated @@ -404,7 +418,7 @@ async def test_partial_workspace_is_removed_after_write_failure_async( patch.object(client, "_control_async", _control()), patch("pathlib.Path.write_bytes", side_effect=OSError("disk full")), patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as launch, - pytest.raises(OSError, match="disk full"), + pytest.raises(SandboxExecutionError, match="disk full"), ): await _run_async(client) launch.assert_not_awaited() @@ -564,3 +578,71 @@ def test_profiles_are_explicit_trusted_configuration() -> None: DockerSandboxClient(profiles={}) with pytest.raises(ValueError): DockerSandboxClient(profiles={"bad name": DockerRuntimeProfile(image=_IMAGE, command=("python3",))}) + + +def test_docker_is_a_call_sandbox_with_its_configured_limits(client: DockerSandboxClient) -> None: + capabilities = client.get_capabilities() + assert isinstance(client, Sandbox) and isinstance(client, SandboxClient) + assert capabilities.state_kind is SandboxStateKind.CALL + assert client.get_runtime_profile_names() == frozenset({"python"}) + assert capabilities.default_timeout_seconds == capabilities.max_timeout_seconds == 10.0 + assert capabilities.max_output_bytes == 64_000 and capabilities.file_runtime_profile_name is None + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_model_tool_call_runs_in_a_container_and_returns_its_result_async( + client: DockerSandboxClient, +) -> None: + target = OpenAIResponseTarget( + model_name="gpt-4", + endpoint="https://mock.azure.com", + api_key="mock-key", + tool_providers=[SandboxToolProvider(sandbox=client)], + ) + call = MagicMock(status="completed", error=None) + call.output = [MagicMock(type="function_call", call_id="call_1", arguments=json.dumps({"program": "print('ok')"}))] + call.output[0].name = "run_python" + answer = MagicMock(status="completed", error=None) + text = ResponseOutputText(annotations=[], text="It printed ok.", type="output_text") + answer.output = [MagicMock(type="message", content=[text])] + sent: list[list[dict[str, object]]] = [] + + async def create_async(**kwargs: object) -> MagicMock: + sent.append(kwargs["input"]) # type: ignore[arg-type] + return call if len(sent) == 1 else answer + + with ( + patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=_process(output=b"ok")) as launch, + patch.object(client, "_control_async", _control()), + patch.object(target._async_client.responses, "create", side_effect=create_async), + ): + responses = await target.send_prompt_async( + message=MessagePiece(role="user", original_value="Run it").to_message() + ) + + argv = launch.call_args.args + assert "--network" in argv and argv[argv.index("--network") + 1] == "none" + output = json.loads(sent[1][-1]["output"]) # type: ignore[arg-type] + assert (output["exit_code"], output["stdout"], output["timed_out"]) == (0, "ok", False) + assert responses[-1].get_value() == "It printed ok." + + +def test_profile_names_that_differ_only_in_punctuation_are_allowed() -> None: + profile = DockerRuntimeProfile(image=_IMAGE, command=("python3",)) + client = DockerSandboxClient(profiles={"py-3": profile, "py_3": profile}) + assert client.get_runtime_profile_names() == frozenset({"py-3", "py_3"}) + + +async def test_long_arguments_are_rejected_before_a_container_starts_async(client: DockerSandboxClient) -> None: + with ( + patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as launch, + patch.object(client, "_control_async", _control()) as control, + pytest.raises(SandboxInputError, match="standard input"), + ): + await client.execute_async( + program="print(1)", + runtime_profile_name="python", + invocations=(_ProgramInvocation(arguments=("x" * 20_000,)),), + ) + launch.assert_not_awaited() + control.assert_not_awaited() diff --git a/tests/unit/_code_execution/test_sandbox.py b/tests/unit/_code_execution/test_sandbox.py new file mode 100644 index 0000000000..720fa3c4f5 --- /dev/null +++ b/tests/unit/_code_execution/test_sandbox.py @@ -0,0 +1,977 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""The rules every ``Sandbox`` follows, checked against ``FakeSandbox``.""" + +from __future__ import annotations + +import asyncio +import logging +import sys +import time +from typing import TYPE_CHECKING, Any +from unittest.mock import patch + +import pytest +from unit.async_utils import TEST_WATCHDOG_SECONDS + +from pyrit._code_execution import ( + FakeRun, + FakeSandbox, + FakeSandboxHook, + ProcessResult, + RuntimeProfile, + Sandbox, + SandboxBusyError, + SandboxCapabilities, + SandboxCondition, + SandboxExecutionError, + SandboxInputError, + SandboxRevisionChangedError, + SandboxSessionLostError, + SandboxStateKind, + SandboxUnavailableError, +) +from pyrit.models.code_execution import _ProgramInvocation + +if TYPE_CHECKING: + from collections.abc import Callable + + from pyrit.models.code_execution import _SandboxRun + +_PYTHON = (RuntimeProfile(name="python"),) +_CALL_CAPABILITIES = SandboxCapabilities(runtime_profiles=_PYTHON, state_kind=SandboxStateKind.CALL) + + +def _echo(run: FakeRun) -> ProcessResult: + return ProcessResult(exit_code=0, stdout=run.program) + + +async def _run_async(sandbox: Sandbox, program: str = "print(1)", **kwargs: Any) -> _SandboxRun: + return await sandbox.execute_async(program=program, runtime_profile_name="python", **kwargs) + + +async def _wait_until_async(condition: Callable[[], bool]) -> None: + async with asyncio.timeout(TEST_WATCHDOG_SECONDS): + while not condition(): + await asyncio.sleep(0.001) + + +async def _finish_async(*tasks: asyncio.Task[Any]) -> list[Any]: + return await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), TEST_WATCHDOG_SECONDS) + + +# ---- capabilities and validation (I6) ---------------------------------------------------------- + + +@pytest.mark.parametrize( + "settings", + [ + {"runtime_profiles": (RuntimeProfile(name="python"), RuntimeProfile(name="python"))}, + {"default_timeout_seconds": 200.0}, + {"file_runtime_profile_name": "ruby"}, + {"state_kind": SandboxStateKind.CALL, "file_runtime_profile_name": "python"}, + {"state_kind": SandboxStateKind.CALL, "supports_reset": True}, + {"state_kind": SandboxStateKind.CALL, "max_session_seconds": 600.0}, + ], +) +def test_capabilities_reject_contradictions(settings: dict[str, Any]) -> None: + values: dict[str, Any] = {"runtime_profiles": _PYTHON, "state_kind": SandboxStateKind.ENVIRONMENT, **settings} + with pytest.raises(ValueError): + SandboxCapabilities(**values) + + +def test_runtime_profiles_may_share_a_derived_tool_name() -> None: + profiles = (RuntimeProfile(name="py.3"), RuntimeProfile(name="py-3")) + assert SandboxCapabilities(runtime_profiles=profiles, state_kind=SandboxStateKind.CALL).runtime_profiles == profiles + + +async def test_arguments_alone_can_be_bounded_async() -> None: + capabilities = _CALL_CAPABILITIES.model_copy(update={"max_arguments_bytes": 10}) + fake = FakeSandbox(capabilities=capabilities) + with pytest.raises(SandboxInputError, match="standard input instead"): + await _run_async(fake, invocations=(_ProgramInvocation(arguments=("x" * 11,)),)) + await _run_async(fake, invocations=(_ProgramInvocation(arguments=("x" * 10,), stdin="y" * 1_000),)) + + +def test_adapter_must_implement_the_hooks_its_capabilities_need() -> None: + class _NoSessions(Sandbox): + def _build_identifier(self) -> Any: + raise NotImplementedError + + def _get_capabilities(self) -> SandboxCapabilities: + return FakeSandbox.DEFAULT_CAPABILITIES + + async def _execute_async(self, **kwargs: Any) -> ProcessResult: + raise NotImplementedError + + with pytest.raises(TypeError, match="_open_session_async, _close_session_async, _reset_async"): + _NoSessions().get_capabilities() + + +@pytest.mark.parametrize( + ("request_settings", "message"), + [ + ({"runtime_profile_name": "ruby"}, "not offered"), + ({"invocations": ()}, "At least one"), + ({"program": "x" * 65_537}, "at most 65536"), + ({"invocations": (_ProgramInvocation(stdin="x" * 65_530),)}, "at most 65536"), + ({"invocations": (_ProgramInvocation(arguments=("x" * 65_530,)),)}, "at most 65536"), + ({"timeout_seconds": 0}, "timeout_seconds"), + ({"timeout_seconds": 121}, "timeout_seconds"), + ({"timeout_seconds": True}, "timeout_seconds"), + ({"program": "\ud800"}, "UTF-8"), + ], +) +async def test_invalid_requests_fail_before_anything_runs_async(request_settings: dict[str, Any], message: str) -> None: + fake = FakeSandbox() + values: dict[str, Any] = {"program": "print(1)", "runtime_profile_name": "python", **request_settings} + with pytest.raises(SandboxInputError, match=message): + await fake.execute_async(**values) + assert fake.runs == [] and fake.open_sessions == set() + + +async def test_timeout_must_fit_in_a_session_async() -> None: + capabilities = FakeSandbox.DEFAULT_CAPABILITIES.model_copy(update={"max_session_seconds": 100.0}) + fake = FakeSandbox(capabilities=capabilities) + with pytest.raises(SandboxInputError, match="session limit"): + await _run_async(fake, timeout_seconds=50) + assert (await _run_async(fake, timeout_seconds=40)).events[0].exit_code == 0 + + +# ---- one shared session, taking turns (I2) ----------------------------------------------------- + + +async def test_first_call_opens_the_session_and_later_calls_share_it_async() -> None: + fake = FakeSandbox(handler=_echo) + first = await _run_async(fake, program="one", invocations=(_ProgramInvocation(), _ProgramInvocation())) + second = await _run_async(fake, program="two") + assert [event.stdout for event in (*first.events, *second.events)] == ["one", "one", "two"] + assert {run.session_id for run in fake.runs} == {"fake-session-1"} + assert fake.open_sessions == {"fake-session-1"} + + +async def test_calls_take_turns_first_come_first_served_async() -> None: + fake = FakeSandbox(handler=_echo) + fake.gate = asyncio.Event() + first = asyncio.create_task(_run_async(fake, program="first")) + await _wait_until_async(lambda: len(fake.runs) == 1) + later = [asyncio.create_task(_run_async(fake, program=name)) for name in ("second", "third")] + await asyncio.sleep(0.05) + assert [run.program for run in fake.runs] == ["first"] + fake.gate.set() + await _finish_async(first, *later) + assert [run.program for run in fake.runs] == ["first", "second", "third"] + + +async def test_a_call_that_waits_past_its_deadline_is_busy_and_never_runs_async() -> None: + fake = FakeSandbox(handler=_echo, acquire_timeout_seconds=0.05) + fake.gate = asyncio.Event() + holder = asyncio.create_task(_run_async(fake, program="holder")) + await _wait_until_async(lambda: len(fake.runs) == 1) + with pytest.raises(SandboxBusyError, match="nothing ran"): + await _run_async(fake, program="late") + fake.gate.set() + await _finish_async(holder) + assert [run.program for run in fake.runs] == ["holder"] + + +async def test_call_sandboxes_run_calls_concurrently_without_sessions_async() -> None: + fake = FakeSandbox(capabilities=_CALL_CAPABILITIES, handler=_echo) + fake.gate = asyncio.Event() + calls = [asyncio.create_task(_run_async(fake, program=name)) for name in ("a", "b")] + await _wait_until_async(lambda: len(fake.runs) == 2) + fake.gate.set() + await _finish_async(*calls) + assert {run.session_id for run in fake.runs} == {None} + assert fake.closed_sessions == [] + + +# ---- retries and uncertain failures (I3, I4) --------------------------------------------------- + + +async def test_a_busy_open_is_retried_until_it_succeeds_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxBusyError("held"), times=2) + with patch.object(FakeSandbox, "_BUSY_RETRY_INITIAL_SECONDS", 0.001): + assert (await _run_async(fake)).events[0].exit_code == 0 + assert fake.open_sessions == {"fake-session-1"} + + +async def test_a_sandbox_that_stays_busy_fails_at_the_deadline_async() -> None: + fake = FakeSandbox(acquire_timeout_seconds=0.05) + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxBusyError("held"), times=1_000) + with patch.object(FakeSandbox, "_BUSY_RETRY_INITIAL_SECONDS", 0.01), pytest.raises(SandboxBusyError): + await _run_async(fake) + assert fake.runs == [] + + +async def test_lock_wait_and_busy_retries_share_one_deadline_async() -> None: + fake = FakeSandbox() + with ( + patch.object(fake, "_acquire_lock_async", wraps=fake._acquire_lock_async) as acquire, + patch.object(fake, "_open_session_with_retry_async", wraps=fake._open_session_with_retry_async) as open_session, + ): + await _run_async(fake) + assert open_session.call_args.kwargs["deadline"] == acquire.call_args.kwargs["deadline"] + + +async def test_closing_stops_a_busy_open_from_retrying_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxBusyError("held"), times=1_000) + with patch.object(FakeSandbox, "_BUSY_RETRY_INITIAL_SECONDS", 0.01): + call = asyncio.create_task(_run_async(fake)) + await asyncio.sleep(0.05) + await asyncio.wait_for(fake.close_async(), TEST_WATCHDOG_SECONDS) + (outcome,) = await _finish_async(call) + assert isinstance(outcome, SandboxUnavailableError) and "closed" in str(outcome) + assert fake.runs == [] + + +async def test_a_lost_session_is_reopened_and_the_call_retried_once_async() -> None: + fake = FakeSandbox(handler=_echo) + await _run_async(fake, program="before") + fake.expire_sessions() + assert (await _run_async(fake, program="after")).events[0].stdout == "after" + assert [run.session_id for run in fake.runs] == ["fake-session-1", "fake-session-2"] + + +async def test_a_session_lost_twice_is_an_error_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=SandboxSessionLostError("gone"), times=2) + with pytest.raises(SandboxSessionLostError): + await _run_async(fake) + assert fake.runs == [] + assert fake.open_sessions == {"fake-session-1", "fake-session-2"} + + +async def test_an_uncertain_failure_closes_the_session_and_is_never_retried_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=RuntimeError("connection reset")) + with pytest.raises(SandboxExecutionError, match="uncertain") as raised: + await _run_async(fake) + assert isinstance(raised.value.__cause__, RuntimeError) + assert fake.closed_sessions == ["fake-session-1"] + await _run_async(fake) + assert [run.session_id for run in fake.runs] == ["fake-session-2"] + + +@pytest.mark.parametrize("error", [SandboxInputError("too large"), SandboxBusyError("not now")]) +async def test_failures_where_nothing_ran_keep_the_session_async(error: Exception) -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=error) + with pytest.raises(type(error)): + await _run_async(fake) + assert fake.closed_sessions == [] + + +async def test_an_adapter_that_does_not_answer_is_uncertain_async() -> None: + async def hang_async(run: FakeRun) -> ProcessResult: + await asyncio.Event().wait() + raise AssertionError("unreachable") + + fake = FakeSandbox(handler=hang_async) + with ( + patch.object(FakeSandbox, "_EXECUTE_GRACE_SECONDS", 0.0), + pytest.raises(SandboxExecutionError, match="did not answer in time"), + ): + await _run_async(fake, timeout_seconds=0.05) + assert fake.closed_sessions == ["fake-session-1"] + + +@pytest.mark.parametrize( + "result", + [ProcessResult.model_construct(exit_code=0, timed_out=True, duration_ms=1), {"exit_code": 0}], + ids=["unvalidated", "not-a-result"], +) +async def test_an_invalid_result_is_an_uncertain_failure_async(result: Any) -> None: + fake = FakeSandbox(handler=lambda run: result) + with pytest.raises(SandboxExecutionError, match="invalid result"): + await _run_async(fake) + assert fake.closed_sessions == ["fake-session-1"] + + +@pytest.mark.parametrize( + ("capabilities", "closed"), + [(FakeSandbox.DEFAULT_CAPABILITIES, ["fake-session-1"]), (_CALL_CAPABILITIES, [])], + ids=["environment", "call"], +) +async def test_a_run_the_adapter_cancels_by_itself_is_an_uncertain_failure_async( + capabilities: SandboxCapabilities, closed: list[str] +) -> None: + fake = FakeSandbox(capabilities=capabilities) + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=asyncio.CancelledError()) + with pytest.raises(SandboxExecutionError, match="cancelled the run by itself"): + await _run_async(fake) + current = asyncio.current_task() + assert current is not None and current.cancelling() == 0 + assert fake.closed_sessions == closed + + +async def test_other_hooks_that_cancel_by_themselves_have_failed_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.OPEN, error=asyncio.CancelledError()) + with pytest.raises(SandboxExecutionError, match="open a session: the sandbox cancelled"): + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.STATUS, error=asyncio.CancelledError()) + assert (await fake.get_status_async()).condition is SandboxCondition.UNAVAILABLE + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=asyncio.CancelledError()) + await fake.release_async() + assert (await fake.get_status_async()).condition is SandboxCondition.QUARANTINED + fake.fail_next(hook=FakeSandboxHook.RESET, error=asyncio.CancelledError()) + with pytest.raises(SandboxExecutionError, match="cancelled it by itself"): + await fake.reset_async() + assert (await fake.get_status_async()).condition is SandboxCondition.QUARANTINED + + +async def test_an_unconfirmed_close_quarantines_until_released_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=RuntimeError("lost the host")) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("host unreachable")) + with pytest.raises(SandboxExecutionError): + await _run_async(fake) + view = await fake.get_status_async() + assert view.condition is SandboxCondition.QUARANTINED and "host unreachable" in (view.quarantine_reason or "") + with pytest.raises(SandboxExecutionError, match="quarantined"): + await _run_async(fake) + await fake.release_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + assert fake.closed_sessions == ["fake-session-1"] + assert (await _run_async(fake)).events[0].exit_code == 0 + + +async def test_release_keeps_the_quarantine_while_the_close_still_fails_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("host unreachable"), times=2) + await fake.release_async() + await fake.release_async() + view = await fake.get_status_async() + assert view.condition is SandboxCondition.QUARANTINED and fake.open_sessions == {"fake-session-1"} + await fake.release_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + assert fake.open_sessions == set() + + +async def test_a_quarantine_during_renewal_opens_no_second_session_async() -> None: + capabilities = FakeSandbox.DEFAULT_CAPABILITIES.model_copy(update={"max_session_seconds": 200.0}) + fake = FakeSandbox(capabilities=capabilities) + await _run_async(fake, timeout_seconds=30) + fake._session_opened_at -= 120 + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("host unreachable")) + with pytest.raises(SandboxUnavailableError, match="quarantined"): + await _run_async(fake, timeout_seconds=30) + assert fake.open_sessions == {"fake-session-1"} and len(fake.runs) == 1 + + +# ---- cancellation (I1) ------------------------------------------------------------------------- + + +async def test_a_caller_that_gives_up_leaves_the_call_holding_the_sandbox_async() -> None: + fake = FakeSandbox(handler=_echo) + fake.gate = asyncio.Event() + caller = asyncio.create_task(_run_async(fake, program="slow")) + await _wait_until_async(lambda: len(fake.runs) == 1) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + assert (await fake.get_status_async()).busy + waiting = asyncio.create_task(_run_async(fake, program="next")) + await asyncio.sleep(0.05) + assert len(fake.runs) == 1 + fake.gate.set() + (run,) = await _finish_async(waiting) + assert run.events[0].stdout == "next" + assert fake.runs[0].session_id == fake.runs[1].session_id + + +async def test_a_cancelled_open_still_records_its_session_async() -> None: + fake = FakeSandbox() + opening, release = asyncio.Event(), asyncio.Event() + open_session = fake._open_session_async + + async def slow_open_async(*, owner: str) -> str: + opening.set() + await release.wait() + return await open_session(owner=owner) + + with patch.object(fake, "_open_session_async", side_effect=slow_open_async): + caller = asyncio.create_task(_run_async(fake)) + await asyncio.wait_for(opening.wait(), TEST_WATCHDOG_SECONDS) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + release.set() + await _wait_until_async(lambda: not fake._lock.locked()) + assert fake.open_sessions == {"fake-session-1"} and fake.runs == [] + await fake.close_async() + assert fake.open_sessions == set() + + +async def test_a_caller_cancelled_while_waiting_never_runs_async() -> None: + fake = FakeSandbox(handler=_echo) + fake.gate = asyncio.Event() + holder = asyncio.create_task(_run_async(fake, program="holder")) + await _wait_until_async(lambda: len(fake.runs) == 1) + waiting = asyncio.create_task(_run_async(fake, program="abandoned")) + await asyncio.sleep(0.01) + waiting.cancel() + fake.gate.set() + await _finish_async(holder, waiting) + assert waiting.cancelled() + assert [run.program for run in fake.runs] == ["holder"] + + +@pytest.mark.parametrize("hops", [1, 2], ids=["before-it-resumes", "once-it-holds-the-lock"]) +async def test_a_caller_cancelled_as_the_sandbox_is_handed_to_it_returns_at_once_and_never_runs_async( + hops: int, +) -> None: + loop = asyncio.get_running_loop() + waiters: list[asyncio.Task[Any]] = [] + + def cancel_after(hops_left: int) -> None: + if hops_left: + loop.call_soon(cancel_after, hops_left - 1) + else: + waiters[0].cancel() + + async def handler_async(run: FakeRun) -> ProcessResult: + if run.program == "holder": + # The holder releases the sandbox right after this. One loop step later the waiter has been + # handed the lock but not resumed; two steps later it holds the lock and has started its run's + # task. On Python 3.11, asyncio.wait_for drops a cancellation at either point, so the waiter runs. + cancel_after(hops) + else: + await asyncio.sleep(0.5) + return ProcessResult(exit_code=0, stdout=run.program) + + fake = FakeSandbox(handler=handler_async) + fake.gate = asyncio.Event() + holder = asyncio.create_task(_run_async(fake, program="holder")) + await _wait_until_async(lambda: len(fake.runs) == 1) + waiters.append(asyncio.create_task(_run_async(fake, program="waiter"))) + await asyncio.sleep(0.01) + started = time.monotonic() + fake.gate.set() + await asyncio.wait(waiters, timeout=TEST_WATCHDOG_SECONDS) + assert waiters[0].cancelled() and time.monotonic() - started < 0.4 + (held,) = await _finish_async(holder) + assert held.events[0].stdout == "holder" + await _wait_until_async(lambda: not fake._lock.locked()) + assert [run.program for run in fake.runs] == ["holder"] + + +@pytest.mark.parametrize( + "eager", + [ + False, + pytest.param(True, marks=pytest.mark.skipif(sys.version_info < (3, 12), reason="eager tasks need Python 3.12")), + ], + ids=["lazy-tasks", "eager-tasks"], +) +async def test_a_caller_that_gives_up_during_busy_retries_never_runs_async( + eager: bool, caplog: pytest.LogCaptureFixture +) -> None: + loop = asyncio.get_running_loop() + task_factory = loop.get_task_factory() + if eager: + loop.set_task_factory(asyncio.eager_task_factory) + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxBusyError("held"), times=1_000) + try: + with ( + patch.object(FakeSandbox, "_BUSY_RETRY_INITIAL_SECONDS", 30.0), + caplog.at_level(logging.INFO, logger="pyrit._code_execution.sandbox"), + ): + caller = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake._faults[FakeSandboxHook.OPEN]) == 999) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + # The retry would wait 30 s, but the call stops as soon as its caller is gone. + await asyncio.wait_for(_wait_until_async(lambda: not fake._lock.locked()), 1.0) + await asyncio.sleep(0) + finally: + loop.set_task_factory(task_factory) + assert fake.runs == [] and fake.open_sessions == set() + assert "did not run" in caplog.text + + +async def test_invocations_that_have_not_started_are_dropped_when_the_caller_gives_up_async( + caplog: pytest.LogCaptureFixture, +) -> None: + fake = FakeSandbox() + fake.gate = asyncio.Event() + with caplog.at_level(logging.INFO, logger="pyrit._code_execution.sandbox"): + caller = asyncio.create_task(_run_async(fake, invocations=(_ProgramInvocation(),) * 2)) + await _wait_until_async(lambda: len(fake.runs) == 1) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + fake.gate.set() + await _wait_until_async(lambda: not fake._lock.locked()) + await asyncio.sleep(0) + assert len(fake.runs) == 1 + (record,) = [record for record in caplog.records if "stopped early" in record.getMessage()] + assert record.levelno == logging.INFO and "the caller gave up" in record.getMessage() + + +async def test_a_failure_after_the_caller_gave_up_is_logged_async(caplog: pytest.LogCaptureFixture) -> None: + gate = asyncio.Event() + + async def second_fails_async(run: FakeRun) -> ProcessResult: + if len(fake.runs) == 2: + await gate.wait() + raise RuntimeError("worker died") + return ProcessResult(exit_code=0) + + fake = FakeSandbox(handler=second_fails_async) + with caplog.at_level(logging.INFO, logger="pyrit._code_execution.sandbox"): + caller = asyncio.create_task(_run_async(fake, invocations=(_ProgramInvocation(),) * 3)) + await _wait_until_async(lambda: len(fake.runs) == 2) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + gate.set() + await _wait_until_async(lambda: not fake._lock.locked()) + await asyncio.sleep(0) + assert len(fake.runs) == 2 and fake.closed_sessions == ["fake-session-1"] + (record,) = [record for record in caplog.records if "stopped early" in record.getMessage()] + assert record.levelno == logging.WARNING and "worker died" in record.getMessage() + + +async def test_a_failure_is_logged_when_the_caller_gives_up_as_the_work_fails_async( + caplog: pytest.LogCaptureFixture, +) -> None: + async def fail_async() -> None: + await asyncio.sleep(0) + raise RuntimeError("the host went away") + + work = asyncio.create_task(fail_async()) + callers: list[asyncio.Task[Any]] = [] + # Added before the shield's own callback, so the caller is cancelled just after the work fails. + work.add_done_callback(lambda _: callers[0].cancel()) + callers.append(asyncio.create_task(Sandbox._await_owned_async(work))) + with caplog.at_level(logging.WARNING, logger="pyrit._code_execution.sandbox"): + with pytest.raises(asyncio.CancelledError): + await callers[0] + await asyncio.sleep(0) + assert "the host went away" in caplog.text + + +@pytest.mark.parametrize("operation", ["release", "close"]) +async def test_closing_the_session_finishes_when_the_caller_gives_up_async(operation: str) -> None: + fake = FakeSandbox() + await _run_async(fake) + closing, release = asyncio.Event(), asyncio.Event() + close_session = fake._close_session_async + + async def slow_close_async(*, session_id: str) -> None: + closing.set() + await release.wait() + await close_session(session_id=session_id) + + with patch.object(fake, "_close_session_async", side_effect=slow_close_async): + caller = asyncio.create_task(fake.release_async() if operation == "release" else fake.close_async()) + await asyncio.wait_for(closing.wait(), TEST_WATCHDOG_SECONDS) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + assert (await fake.get_status_async()).busy + release.set() + await _wait_until_async(lambda: not fake._lock.locked()) + assert fake.open_sessions == set() and fake.closed_sessions == ["fake-session-1"] + + +async def test_a_call_sandbox_passes_cancellation_to_the_adapter_async() -> None: + cancelled = asyncio.Event() + + async def slow_async(run: FakeRun) -> ProcessResult: + try: + await asyncio.Event().wait() + finally: + cancelled.set() + raise AssertionError("unreachable") + + fake = FakeSandbox(capabilities=_CALL_CAPABILITIES, handler=slow_async) + caller = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + assert cancelled.is_set() + + +# ---- renewal and idle close (I5, I7) ----------------------------------------------------------- + + +async def test_a_session_is_renewed_before_a_run_could_outlast_it_async() -> None: + capabilities = FakeSandbox.DEFAULT_CAPABILITIES.model_copy(update={"max_session_seconds": 200.0}) + fake = FakeSandbox(capabilities=capabilities) + await _run_async(fake, timeout_seconds=30) + await _run_async(fake, timeout_seconds=30) + assert fake.closed_sessions == [] + fake._session_opened_at -= 120 + await _run_async(fake, timeout_seconds=30) + assert fake.closed_sessions == ["fake-session-1"] + assert fake.runs[-1].session_id == "fake-session-2" + + +async def test_session_age_counts_from_when_the_open_was_sent_async() -> None: + fake = FakeSandbox() + sent_at: list[float] = [] + open_session = fake._open_session_async + + async def slow_open_async(*, owner: str) -> str: + sent_at.append(time.monotonic()) + await asyncio.sleep(0.05) + return await open_session(owner=owner) + + with patch.object(fake, "_open_session_async", side_effect=slow_open_async): + await _run_async(fake) + assert fake._session_opened_at is not None and fake._session_opened_at <= sent_at[0] + + +async def test_an_idle_session_closes_by_itself_async() -> None: + fake = FakeSandbox(idle_timeout_seconds=0.05) + await _run_async(fake) + await _wait_until_async(lambda: fake.closed_sessions == ["fake-session-1"]) + assert not (await fake.get_status_async()).session_open + + +async def test_an_idle_timer_that_fires_during_a_call_waits_for_the_next_idle_period_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 2) + fake._on_idle_timer(fake._uses) + await asyncio.sleep(0) + assert fake.closed_sessions == [] + fake.gate.set() + await _finish_async(running) + assert fake._idle_handle is not None + fake._on_idle_timer(fake._uses) + await _wait_until_async(lambda: fake.closed_sessions == ["fake-session-1"]) + + +async def test_idle_close_waits_for_the_sandbox_to_be_free_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + await fake._lock.acquire() + closing = asyncio.create_task(fake._close_if_idle_async(uses=fake._uses)) + await asyncio.sleep(0.01) + assert fake.closed_sessions == [] + fake._lock.release() + await _finish_async(closing) + assert fake.closed_sessions == ["fake-session-1"] + + +async def test_idle_close_spares_a_session_used_since_its_timer_was_set_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + stale = fake._uses + await _run_async(fake) + await fake._close_if_idle_async(uses=stale) + assert fake.closed_sessions == [] + await fake._close_if_idle_async(uses=fake._uses) + assert fake.closed_sessions == ["fake-session-1"] + + +# ---- reset (I8) -------------------------------------------------------------------------------- + + +async def test_reset_closes_the_session_restores_the_baseline_and_records_it_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.state["artifact"] = True + await fake.reset_async(expected_revision="fake-revision-1") + view = await fake.get_status_async() + assert fake.state == {} and fake.reset_count == 1 and fake.closed_sessions == ["fake-session-1"] + assert view.last_reset is not None and view.last_reset.succeeded and not view.resetting + + +async def test_reset_refuses_a_changed_revision_async() -> None: + fake = FakeSandbox() + fake.revision = "fake-revision-2" + with pytest.raises(SandboxRevisionChangedError): + await fake.reset_async(expected_revision="fake-revision-1") + view = await fake.get_status_async() + assert fake.reset_count == 0 and view.last_reset is not None and view.last_reset.succeeded is False + assert view.condition is SandboxCondition.READY + + +async def test_a_reset_that_fails_quarantines_until_one_succeeds_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.RESET, error=RuntimeError("checkpoint restore failed")) + with pytest.raises(SandboxExecutionError, match="checkpoint restore failed"): + await fake.reset_async() + assert (await fake.get_status_async()).condition is SandboxCondition.QUARANTINED + with pytest.raises(SandboxUnavailableError): + await _run_async(fake) + with pytest.raises(SandboxRevisionChangedError): + await fake.reset_async(expected_revision="fake-revision-0") + assert (await fake.get_status_async()).condition is SandboxCondition.QUARANTINED + await fake.reset_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + + +async def test_a_reset_that_does_not_finish_in_time_quarantines_async() -> None: + fake = FakeSandbox() + + async def hang_async(*, expected_revision: str | None) -> None: + await asyncio.Event().wait() + + with ( + patch.object(FakeSandbox, "_RESET_TIMEOUT_SECONDS", 0.05), + patch.object(fake, "_reset_async", side_effect=hang_async), + pytest.raises(SandboxExecutionError, match="did not finish"), + ): + await fake.reset_async() + view = await fake.get_status_async() + assert view.condition is SandboxCondition.QUARANTINED and not view.resetting and not view.busy + + +async def test_reset_waits_for_the_running_call_and_shows_progress_async() -> None: + fake = FakeSandbox() + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + reset = asyncio.create_task(fake.reset_async()) + await asyncio.sleep(0.01) + assert (await fake.get_status_async()).resetting and fake.reset_count == 0 + with pytest.raises(SandboxBusyError, match="already running"): + await fake.reset_async() + fake.gate.set() + await _finish_async(running, reset) + assert fake.reset_count == 1 + + +async def test_reset_runs_to_the_end_when_its_caller_gives_up_async() -> None: + fake = FakeSandbox() + resetting, release = asyncio.Event(), asyncio.Event() + reset = fake._reset_async + + async def slow_reset_async(*, expected_revision: str | None) -> None: + resetting.set() + await release.wait() + await reset(expected_revision=expected_revision) + + with patch.object(fake, "_reset_async", side_effect=slow_reset_async): + caller = asyncio.create_task(fake.reset_async()) + await asyncio.wait_for(resetting.wait(), TEST_WATCHDOG_SECONDS) + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + release.set() + await _wait_until_async(lambda: fake.reset_count == 1) + await _wait_until_async(lambda: not fake._lock.locked()) + assert not (await fake.get_status_async()).resetting + + +async def test_reset_clears_a_quarantine_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=RuntimeError("lost")) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("unreachable")) + with pytest.raises(SandboxExecutionError): + await _run_async(fake) + await fake.reset_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + assert fake.open_sessions == set() and fake.closed_sessions == ["fake-session-1"] + + +async def test_unconfirmed_closes_are_retried_until_confirmed_even_after_a_reset_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("unreachable"), times=2) + await fake.release_async() + await fake.reset_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + assert fake.open_sessions == {"fake-session-1"} + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("unreachable"), times=2) + await fake.release_async() + assert fake.open_sessions == {"fake-session-1", "fake-session-2"} + await fake.release_async() + assert fake.open_sessions == set() and fake.closed_sessions == ["fake-session-1", "fake-session-2"] + assert (await fake.get_status_async()).condition is SandboxCondition.READY + + +async def test_a_reset_that_waits_too_long_is_busy_and_can_be_retried_async() -> None: + fake = FakeSandbox(acquire_timeout_seconds=0.05) + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + with pytest.raises(SandboxBusyError, match="stayed busy"): + await fake.reset_async() + assert not (await fake.get_status_async()).resetting + fake.gate.set() + await _finish_async(running) + await fake.reset_async() + assert fake.reset_count == 1 + + +async def test_reset_is_refused_when_unsupported_async() -> None: + fake = FakeSandbox(capabilities=_CALL_CAPABILITIES) + with pytest.raises(SandboxInputError, match="does not support reset"): + await fake.reset_async() + + +# ---- closing (I9) ------------------------------------------------------------------------------ + + +async def test_close_waits_for_the_running_call_and_is_final_async() -> None: + fake = FakeSandbox(handler=_echo) + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake, program="running")) + await _wait_until_async(lambda: len(fake.runs) == 1) + queued = asyncio.create_task(_run_async(fake, program="queued")) + await asyncio.sleep(0.01) + closing = asyncio.create_task(fake.close_async()) + await asyncio.sleep(0.01) + with pytest.raises(SandboxUnavailableError, match="closed"): + await _run_async(fake, program="late") + fake.gate.set() + results = await _finish_async(running, queued, closing) + assert results[0].events[0].stdout == "running" + assert isinstance(results[1], SandboxUnavailableError) + assert [run.program for run in fake.runs] == ["running"] + assert fake.closed_sessions == ["fake-session-1"] + assert (await fake.get_status_async()).closed + with pytest.raises(SandboxUnavailableError, match="closed"): + await _run_async(fake, program="after") + with pytest.raises(SandboxUnavailableError, match="closed"): + await fake.reset_async() + await fake.release_async() + assert fake.reset_count == 0 and fake.open_sessions == set() + + +async def test_close_never_raises_and_an_unconfirmed_close_can_still_be_retried_async() -> None: + fake = FakeSandbox() + await _run_async(fake) + fake.fail_next(hook=FakeSandboxHook.CLOSE, error=RuntimeError("unreachable"), times=2) + await fake.close_async() + await fake.close_async() + assert (await fake.get_status_async()).condition is SandboxCondition.QUARANTINED + assert fake.open_sessions == {"fake-session-1"} + await fake.release_async() + assert (await fake.get_status_async()).condition is SandboxCondition.READY + assert fake.open_sessions == set() and fake.closed_sessions == ["fake-session-1"] + with pytest.raises(SandboxUnavailableError, match="closed"): + await _run_async(fake) + + +async def test_close_gives_up_waiting_for_a_call_that_holds_the_sandbox_too_long_async() -> None: + fake = FakeSandbox(acquire_timeout_seconds=0.05) + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + await asyncio.wait_for(fake.close_async(), TEST_WATCHDOG_SECONDS) + assert fake.closed_sessions == [] + fake.gate.set() + await _finish_async(running) + assert (await fake.get_status_async()).closed + + +async def test_release_is_refused_while_a_call_runs_async() -> None: + fake = FakeSandbox() + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + with pytest.raises(SandboxBusyError): + await fake.release_async() + fake.gate.set() + await _finish_async(running) + await fake.release_async() + assert fake.closed_sessions == ["fake-session-1"] + + +# ---- status (I10) ------------------------------------------------------------------------------ + + +async def test_status_combines_the_sandbox_report_with_session_state_async() -> None: + fake = FakeSandbox() + idle = await fake.get_status_async() + assert idle.status_is_current and not idle.session_open and idle.status.revision == "fake-revision-1" + await _run_async(fake) + view = await fake.get_status_async() + assert view.session_open and view.session_age_seconds is not None and view.idle_seconds is not None + assert view.status.details == {"fake_sandbox": "fake"} + + +async def test_status_reuses_the_last_report_while_a_call_runs_async() -> None: + fake = FakeSandbox() + await fake.get_status_async() + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + fake.revision = "fake-revision-2" + view = await asyncio.wait_for(fake.get_status_async(), 0.5) + assert view.busy and not view.status_is_current and view.status.revision == "fake-revision-1" + fake.gate.set() + await _finish_async(running) + + +async def test_a_status_failure_reports_unavailable_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.STATUS, error=RuntimeError("host unreachable")) + view = await fake.get_status_async() + assert view.condition is SandboxCondition.UNAVAILABLE and "host unreachable" in (view.status.reason or "") + + +# ---- evidence and identity (I11, I12) ---------------------------------------------------------- + + +async def test_runs_keep_warnings_execution_ids_and_durations_async() -> None: + fake = FakeSandbox(handler=lambda run: ProcessResult(exit_code=0, execution_id="run-7", warnings=("slow disk",))) + run = await _run_async(fake) + assert run.execution_ids == ("run-7",) and run.warnings == ("slow disk",) + assert run.events[0].duration_ms >= 0 + + +async def test_a_failure_after_some_runs_returns_them_with_the_reason_async() -> None: + fake = FakeSandbox(handler=_echo) + original = fake._execute_async + calls = 0 + + async def second_fails_async(**kwargs: Any) -> ProcessResult: + nonlocal calls + calls += 1 + if calls == 2: + raise RuntimeError("worker died") + return await original(**kwargs) + + with patch.object(fake, "_execute_async", side_effect=second_fails_async): + run = await _run_async(fake, invocations=(_ProgramInvocation(),) * 3) + assert len(run.events) == 1 and "sandbox error at invocation 1" in run.reasons[0] + + +async def test_unconfirmed_cleanup_stops_further_runs_async() -> None: + fake = FakeSandbox( + handler=lambda run: ProcessResult(exit_code=0, warnings=("could not remove",), cleanup_confirmed=False) + ) + run = await _run_async(fake, invocations=(_ProgramInvocation(),) * 2) + assert len(run.events) == 1 and len(fake.runs) == 1 + assert run.warnings == ("could not remove",) and "stopped after invocation 0" in run.reasons[0] + with pytest.raises(SandboxUnavailableError, match="may still be running"): + await _run_async(fake) + await fake.release_async() + assert fake.closed_sessions == ["fake-session-1"] + + +async def test_a_reset_waiting_when_the_sandbox_closes_does_not_run_async() -> None: + fake = FakeSandbox() + fake.gate = asyncio.Event() + running = asyncio.create_task(_run_async(fake)) + await _wait_until_async(lambda: len(fake.runs) == 1) + reset = asyncio.create_task(fake.reset_async()) + await asyncio.sleep(0.01) + closing = asyncio.create_task(fake.close_async()) + await asyncio.sleep(0.01) + fake.gate.set() + _, reset_outcome, _ = await _finish_async(running, reset, closing) + assert isinstance(reset_outcome, SandboxUnavailableError) + assert fake.reset_count == 0 and fake.open_sessions == set() + assert not (await fake.get_status_async()).resetting diff --git a/tests/unit/_code_execution/test_sandbox_contract.py b/tests/unit/_code_execution/test_sandbox_contract.py new file mode 100644 index 0000000000..6150db722d --- /dev/null +++ b/tests/unit/_code_execution/test_sandbox_contract.py @@ -0,0 +1,131 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""The contract-test kit passes for adapters that follow the rules and names the rule a broken one breaks.""" + +from __future__ import annotations + +import shutil +from typing import TYPE_CHECKING, Any + +import pytest +from unit._code_execution.local_python_sandbox import LocalPythonSandbox + +from pyrit._code_execution import ( + ProcessResult, + SandboxContractError, + SandboxProbes, + SandboxRevisionChangedError, + SandboxStateKind, + check_sandbox_contract_async, +) +from pyrit.models import ComponentIdentifier + +if TYPE_CHECKING: + import asyncio + from pathlib import Path + + +class _LostSessionIsGenericError(LocalPythonSandbox): + async def _execute_async(self, *, session_id: str | None, **kwargs: Any) -> ProcessResult: + if session_id not in self.sessions: + raise RuntimeError("no such session") + return await super()._execute_async(session_id=session_id, **kwargs) + + +class _ClosingTwiceFails(LocalPythonSandbox): + async def _close_session_async(self, *, session_id: str) -> None: + if session_id not in self.sessions: + raise RuntimeError("already closed") + await super()._close_session_async(session_id=session_id) + + +class _CutsOutputSilently(LocalPythonSandbox): + async def _execute_async(self, **kwargs: Any) -> ProcessResult: + result = await super()._execute_async(**kwargs) + return result.model_copy(update={"stdout": result.stdout[:1_000], "stdout_truncated": False}) + + +class _ForgetsFilesOnClose(LocalPythonSandbox): + async def _close_session_async(self, *, session_id: str) -> None: + await super()._close_session_async(session_id=session_id) + shutil.rmtree(self.workspace) + self.workspace.mkdir() + + +class _ResetIgnoresRevision(LocalPythonSandbox): + async def _reset_async(self, *, expected_revision: str | None) -> None: + await super()._reset_async(expected_revision=None) + + +class _IdentifierHoldsSessions(LocalPythonSandbox): + def _build_identifier(self) -> ComponentIdentifier: + return ComponentIdentifier.of(self, params={"sessions": sorted(self.sessions)}) + + +class _WipesBeforeRefusingReset(LocalPythonSandbox): + async def _reset_async(self, *, expected_revision: str | None) -> None: + await super()._reset_async(expected_revision=None) + if expected_revision is not None and expected_revision != self.revision: + raise SandboxRevisionChangedError("The revision changed.") + + +class _LeavesTimedOutRunsRunning(LocalPythonSandbox): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.left_running: list[asyncio.subprocess.Process] = [] + + async def _stop_async(self, process: asyncio.subprocess.Process) -> tuple[bytes, bytes]: + self.left_running.append(process) + return b"", b"" + + +@pytest.mark.parametrize("state_kind", [SandboxStateKind.ENVIRONMENT, SandboxStateKind.CALL]) +async def test_contract_passes_for_a_sandbox_that_follows_the_rules_async( + tmp_path: Path, state_kind: SandboxStateKind +) -> None: + sandbox = LocalPythonSandbox(root=tmp_path, state_kind=state_kind) + await check_sandbox_contract_async(sandbox=sandbox, probes=SandboxProbes.python(), timeout_probe_seconds=1.0) + assert not sandbox.sessions + + +@pytest.mark.parametrize( + ("sandbox_type", "rule"), + [ + (_LostSessionIsGenericError, "must raise SandboxSessionLostError"), + (_ClosingTwiceFails, "Closing a closed session must succeed"), + (_ForgetsFilesOnClose, "must survive closing its session"), + (_ResetIgnoresRevision, "must be refused with SandboxRevisionChangedError"), + (_WipesBeforeRefusingReset, "A refused reset must leave the sandbox unchanged"), + (_IdentifierHoldsSessions, "static configuration only"), + (_CutsOutputSilently, "must come back whole"), + ], +) +async def test_contract_names_the_rule_a_broken_adapter_breaks_async( + tmp_path: Path, sandbox_type: type[LocalPythonSandbox], rule: str +) -> None: + sandbox = sandbox_type(root=tmp_path) + with pytest.raises(SandboxContractError, match=rule): + await check_sandbox_contract_async(sandbox=sandbox, probes=SandboxProbes.python(), timeout_probe_seconds=1.0) + assert not (await sandbox.get_status_async()).session_open + + +async def test_contract_catches_a_timeout_that_leaves_the_program_running_async(tmp_path: Path) -> None: + sandbox = _LeavesTimedOutRunsRunning(root=tmp_path) + try: + with pytest.raises(SandboxContractError, match="must be stopped, not left running"): + await check_sandbox_contract_async( + sandbox=sandbox, probes=SandboxProbes.python(), timeout_probe_seconds=1.0 + ) + finally: + for process in sandbox.left_running: + if process.returncode is None: + process.kill() + await process.wait() + + +async def test_contract_requires_the_probe_runtime_async(tmp_path: Path) -> None: + with pytest.raises(SandboxContractError, match="does not offer"): + await check_sandbox_contract_async( + sandbox=LocalPythonSandbox(root=tmp_path), probes=SandboxProbes.python(runtime_profile_name="python-3.99") + ) diff --git a/tests/unit/_code_execution/test_sandbox_registry.py b/tests/unit/_code_execution/test_sandbox_registry.py new file mode 100644 index 0000000000..b51712f08b --- /dev/null +++ b/tests/unit/_code_execution/test_sandbox_registry.py @@ -0,0 +1,71 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from pyrit._code_execution import FakeSandbox, SandboxRegistry, resolve_sandbox +from pyrit.setup.initialization import reset_setup_registries + +if TYPE_CHECKING: + from collections.abc import Iterator + + +@pytest.fixture +def registry() -> Iterator[SandboxRegistry]: + SandboxRegistry.reset_registry_singleton() + yield SandboxRegistry.get_registry_singleton() + SandboxRegistry.reset_registry_singleton() + + +def test_register_and_find_by_name(registry: SandboxRegistry) -> None: + sandbox = FakeSandbox(name="linux-1") + registry.register(sandbox, name="linux-1") + assert registry.get("linux-1") is sandbox + assert registry.get_names() == ["linux-1"] + assert resolve_sandbox("linux-1") is sandbox + assert resolve_sandbox(sandbox) is sandbox + assert registry.unregister("linux-1") is sandbox + assert registry.get("linux-1") is None + + +@pytest.mark.parametrize("name", ["", "has space", "../escape", "-leading", "x" * 129]) +def test_register_rejects_invalid_names(registry: SandboxRegistry, name: str) -> None: + with pytest.raises(ValueError, match="Sandbox name"): + registry.register(FakeSandbox(), name=name) + + +def test_register_rejects_a_taken_name(registry: SandboxRegistry) -> None: + registry.register(FakeSandbox(name="one"), name="sandbox") + with pytest.raises(ValueError, match="already registered"): + registry.register(FakeSandbox(name="two"), name="sandbox") + + +def test_register_rejects_a_second_object_for_the_same_sandbox(registry: SandboxRegistry) -> None: + registry.register(FakeSandbox(name="windows"), name="windows-1") + with pytest.raises(ValueError, match="already registered as 'windows-1'"): + registry.register(FakeSandbox(name="windows"), name="windows-2") + + +def test_resolve_names_what_is_registered(registry: SandboxRegistry) -> None: + registry.register(FakeSandbox(), name="present") + with pytest.raises(ValueError, match=r"No sandbox is registered as 'absent'; registered: \['present'\]"): + resolve_sandbox("absent") + + +async def test_close_all_closes_every_session(registry: SandboxRegistry) -> None: + sandboxes = [FakeSandbox(name=name) for name in ("a", "b")] + for sandbox in sandboxes: + registry.register(sandbox, name=sandbox.get_identifier().params["name"]) + await sandbox.execute_async(program="print(1)", runtime_profile_name="python") + await registry.close_all_async() + assert all(sandbox.open_sessions == set() for sandbox in sandboxes) + + +def test_reapplying_configuration_resets_the_registry(registry: SandboxRegistry) -> None: + registry.register(FakeSandbox(), name="before") + reset_setup_registries() + assert SandboxRegistry.get_registry_singleton().get_names() == [] diff --git a/tests/unit/common/test_lazy_package_imports.py b/tests/unit/common/test_lazy_package_imports.py index 655f73bed9..9b155d31cc 100644 --- a/tests/unit/common/test_lazy_package_imports.py +++ b/tests/unit/common/test_lazy_package_imports.py @@ -476,10 +476,19 @@ def test_code_execution_is_independent_of_component_layers() -> None: import pyrit.models import pyrit.models.code_execution as execution_models from pyrit._code_execution import DockerRuntimeProfile, DockerSandboxClient, SandboxClient + from pyrit._code_execution import ( + FakeSandbox, Sandbox, SandboxProbes, SandboxRegistry, check_sandbox_contract_async, + ) from pyrit.models.code_execution import ( _ProgramExecutionEvent, _ProgramInvocation, _RuntimeProfileName, _SandboxRun, ) + fake = FakeSandbox() + SandboxRegistry.get_registry_singleton().register(fake, name="fake") + assert isinstance(fake, Sandbox) and isinstance(fake, SandboxClient) + assert SandboxProbes.python().runtime_profile_name in fake.get_runtime_profile_names() + assert callable(check_sandbox_contract_async) + for name in ("_ProgramExecutionEvent", "_ProgramInvocation", "_RuntimeProfileName", "_SandboxRun"): assert name not in pyrit.models.__all__ assert not hasattr(pyrit.models, name) diff --git a/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py b/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py index 06321da0d4..4e7fd7b23c 100644 --- a/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py +++ b/tests/unit/prompt_target/target/test_openai_response_target_function_chaining.py @@ -16,9 +16,10 @@ from openai.types.responses import ResponseOutputText from pyrit.memory import CentralMemory, MemoryInterface -from pyrit.models import Message, MessagePiece +from pyrit.models import Message, MessagePiece, ToolExecutionMetadata, ToolLoopStop, ToolLoopStopReason from pyrit.prompt_normalizer import PromptNormalizer -from pyrit.prompt_target import OpenAIResponseTarget +from pyrit.prompt_target import FunctionTool, OpenAIResponseTarget, ToolInfrastructureError +from pyrit.prompt_target.common.target_history import filter_non_replayable_messages @pytest.fixture @@ -454,3 +455,126 @@ async def mock_create(**kwargs): # If we got here, no duplicates were detected assert len(call_history) == 2 + + +def _call_outputs(messages: list[Message]) -> list[tuple[str, Any, bool]]: + outputs = [] + for message in messages: + piece = message.get_piece() + if piece.original_value_data_type == "function_call_output": + payload = json.loads(piece.original_value) + execution = ToolExecutionMetadata.from_metadata(metadata=piece.prompt_metadata) + assert execution is not None + output = payload["output"] + outputs.append( + (payload["call_id"], json.loads(output) if output.startswith("{") else output, execution.invoked) + ) + return outputs + + +@pytest.mark.parametrize("max_tool_rounds", [-1, True, 1.5]) +def test_max_tool_rounds_must_be_a_nonnegative_integer(patch_central_database, max_tool_rounds: Any) -> None: + with pytest.raises(ValueError, match="max_tool_rounds"): + OpenAIResponseTarget( + model_name="gpt-4", endpoint="https://mock.azure.com", api_key="k", max_tool_rounds=max_tool_rounds + ) + + +def test_identifier_records_max_tool_rounds_only_with_local_tools(patch_central_database) -> None: + async def noop(*, value: str) -> str: + return value + + plain = OpenAIResponseTarget(model_name="gpt-4", endpoint="https://mock.azure.com", api_key="k") + with_tools = OpenAIResponseTarget( + model_name="gpt-4", endpoint="https://mock.azure.com", api_key="k", tools=[FunctionTool(function=noop)] + ) + assert "max_tool_rounds" not in plain.get_identifier().params + assert with_tools.get_identifier().params["max_tool_rounds"] == 10 + + +@pytest.mark.parametrize("max_tool_rounds", [0, 2]) +async def test_tool_rounds_stop_at_the_limit_with_every_call_answered_async( + patch_central_database, max_tool_rounds: int +) -> None: + executed: list[str] = [] + + async def lookup(*, key: str) -> str: + executed.append(key) + return key + + target = OpenAIResponseTarget( + model_name="gpt-4", + endpoint="https://mock.azure.com", + api_key="k", + tools=[FunctionTool(function=lookup)], + max_tool_rounds=max_tool_rounds, + ) + responses = [create_mock_function_call_response(f"call_{i}", "lookup", {"key": str(i)}) for i in range(5)] + with patch.object( + target._async_client.responses, "create", new_callable=AsyncMock, side_effect=responses + ) as create: + result = await target.send_prompt_async(message=MessagePiece(role="user", original_value="Go").to_message()) + + assert create.await_count == max_tool_rounds + 1 + assert executed == [str(i) for i in range(max_tool_rounds)] + outputs = _call_outputs(result) + assert [call_id for call_id, _, _ in outputs] == [f"call_{i}" for i in range(max_tool_rounds + 1)] + assert outputs[-1][1:] == ({"error": "max_tool_rounds_exhausted"}, False) + final = result[-1].get_piece() + assert final.original_value_data_type == "error" and final.response_error == "processing" + assert f"max_tool_rounds={max_tool_rounds}" in final.original_value + assert ToolLoopStop.from_metadata(metadata=final.prompt_metadata) == ToolLoopStop( + reason=ToolLoopStopReason.MAX_TOOL_ROUNDS_EXHAUSTED + ) + + +async def test_tool_infrastructure_error_ends_the_turn_with_every_call_answered_async(patch_central_database) -> None: + executed: list[str] = [] + + async def lookup(*, key: str) -> str: + executed.append(key) + if key == "broken": + raise ToolInfrastructureError("the sandbox is unreachable") + return key + + target = OpenAIResponseTarget( + model_name="gpt-4", endpoint="https://mock.azure.com", api_key="k", tools=[FunctionTool(function=lookup)] + ) + round_one = create_mock_function_call_response("call_ok", "lookup", {"key": "ok"}) + for call_id, key in (("call_broken", "broken"), ("call_skipped", "skipped")): + round_one.output.extend(create_mock_function_call_response(call_id, "lookup", {"key": key}).output) + with patch.object( + target._async_client.responses, "create", new_callable=AsyncMock, side_effect=[round_one] + ) as create: + result = await target.send_prompt_async(message=MessagePiece(role="user", original_value="Go").to_message()) + + create.assert_awaited_once() + assert executed == ["ok", "broken"] + assert _call_outputs(result) == [ + ("call_ok", "ok", True), + ("call_broken", {"error": "tool_infrastructure_error", "message": "The tool's infrastructure failed."}, True), + ("call_skipped", {"error": "tool_not_executed", "message": "An earlier tool call failed."}, False), + ] + final = result[-1].get_piece() + assert final.response_error == "processing" and "the sandbox is unreachable" in final.original_value + target.validate_tool_history(result) + assert filter_non_replayable_messages(messages=result) == result[:-1] + + +@pytest.mark.parametrize("failing_request", [0, 1], ids=["first", "after-a-tool-round"]) +async def test_a_failed_model_request_raises_for_the_caller_to_retry_async( + patch_central_database, failing_request: int +) -> None: + async def lookup(*, key: str) -> str: + return key + + target = OpenAIResponseTarget( + model_name="gpt-4", endpoint="https://mock.azure.com", api_key="k", tools=[FunctionTool(function=lookup)] + ) + replies: list[object] = [create_mock_function_call_response("call_1", "lookup", {"key": "a"})][:failing_request] + replies.append(RuntimeError("down")) + with ( + patch.object(target._async_client.responses, "create", new_callable=AsyncMock, side_effect=replies), + pytest.raises(Exception, match="down"), + ): + await target.send_prompt_async(message=MessagePiece(role="user", original_value="Go").to_message()) diff --git a/tests/unit/prompt_target/target/test_sandbox_tool_provider.py b/tests/unit/prompt_target/target/test_sandbox_tool_provider.py new file mode 100644 index 0000000000..2e1090dafe --- /dev/null +++ b/tests/unit/prompt_target/target/test_sandbox_tool_provider.py @@ -0,0 +1,356 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from __future__ import annotations + +import json +import uuid +from typing import TYPE_CHECKING, Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from openai.types.responses import ResponseOutputText +from pydantic import ValidationError +from unit._code_execution.local_python_sandbox import LocalPythonSandbox + +from pyrit._code_execution import ( + FakeRun, + FakeSandbox, + FakeSandboxHook, + ProcessResult, + RuntimeProfile, + SandboxBusyError, + SandboxCapabilities, + SandboxExecutionError, + SandboxInputError, + SandboxRegistry, + SandboxStateKind, +) +from pyrit.models import ( + Equals, + Message, + MessagePiece, + MessageScorable, + ProgramBehaves, + ProgramCase, + ProgramResult, + ToolExecutionMetadata, + ToolLoopStop, + ToolLoopStopReason, +) +from pyrit.prompt_target import OpenAIResponseTarget, SandboxToolProvider, Tool, ToolInfrastructureError +from pyrit.score import SandboxCheckScorer + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + + from pyrit.memory import SQLiteMemory + + +@pytest.fixture +def registry() -> Iterator[SandboxRegistry]: + SandboxRegistry.reset_registry_singleton() + yield SandboxRegistry.get_registry_singleton() + SandboxRegistry.reset_registry_singleton() + + +async def _tools_async(provider: SandboxToolProvider) -> dict[str, Tool]: + return {tool.name: tool for tool in await provider.get_tools_async()} + + +async def _call_async(tool: Tool, **arguments: Any) -> Any: + tool.validate_arguments(arguments=arguments) + return await tool.execute_async(arguments=arguments) + + +async def test_tools_come_from_the_sandbox_runtimes_and_state_kind_async() -> None: + environment = await _tools_async(SandboxToolProvider(sandbox=FakeSandbox())) + assert list(environment) == ["run_python", "run_bash", "write_file", "read_file", "list_dir"] + capabilities = SandboxCapabilities( + runtime_profiles=(RuntimeProfile(name="python-3.12", description="Python 3.12"),), + state_kind=SandboxStateKind.CALL, + max_timeout_seconds=10.0, + default_timeout_seconds=5.0, + ) + call = await _tools_async(SandboxToolProvider(sandbox=FakeSandbox(capabilities=capabilities))) + assert list(call) == ["run_python_3_12"] + run_tool = call["run_python_3_12"] + assert "Python 3.12" in run_tool.description and "Nothing persists" in run_tool.description + timeout = run_tool.parameters["properties"]["timeout_seconds"] # type: ignore[index] + assert timeout["maximum"] == 10.0 and "Defaults to 5" in timeout["description"] + + +async def test_tool_names_select_the_tools_in_order_async(registry: SandboxRegistry) -> None: + registry.register(FakeSandbox(), name="linux") + provider = SandboxToolProvider(sandbox="linux", tool_names=["read_file", "run_python"]) + assert list(await _tools_async(provider)) == ["read_file", "run_python"] + assert provider.identifier["tools"] == ["read_file", "run_python"] + assert provider.identifier["sandbox"]["params"] == {"name": "fake", "state_kind": "environment"} # type: ignore[index] + + +@pytest.mark.parametrize(("tool_names", "message"), [(["run_ruby"], "does not offer"), (["list_dir"] * 2, "repeat")]) +def test_tool_names_must_be_offered_once(tool_names: list[str], message: str) -> None: + with pytest.raises(ValueError, match=message): + SandboxToolProvider(sandbox=FakeSandbox(), tool_names=tool_names) + + +async def test_a_runtime_can_name_its_tool_and_names_must_not_collide_async() -> None: + profiles = (RuntimeProfile(name="windows-powershell", tool_name="powershell"), RuntimeProfile(name="py.3")) + capabilities = SandboxCapabilities(runtime_profiles=profiles, state_kind=SandboxStateKind.CALL) + assert list(await _tools_async(SandboxToolProvider(sandbox=FakeSandbox(capabilities=capabilities)))) == [ + "run_powershell", + "run_py_3", + ] + colliding = capabilities.model_copy( + update={"runtime_profiles": (RuntimeProfile(name="py.3"), RuntimeProfile(name="py-3"))} + ) + with pytest.raises(ValueError, match="share a tool name"): + SandboxToolProvider(sandbox=FakeSandbox(capabilities=colliding)) + + +async def test_run_tool_returns_the_exit_code_and_bounded_output_async() -> None: + def handler(run: FakeRun) -> ProcessResult: + return ProcessResult( + exit_code=3, stdout="x" * 50, stderr="err", execution_id="exec-1", warnings=("slow cleanup",) + ) + + fake = FakeSandbox(handler=handler) + tools = await _tools_async(SandboxToolProvider(sandbox=fake, max_output_chars=10)) + result = await _call_async( + tools["run_python"], program="print('x' * 50)", arguments=["a"], stdin="in", timeout_seconds=5 + ) + assert result == { + "exit_code": 3, + "stdout": "x" * 10, + "stderr": "err", + "stdout_truncated": True, + "stderr_truncated": False, + "timed_out": False, + "resource_limit_exceeded": False, + "duration_ms": result["duration_ms"], + "warnings": ["slow cleanup"], + "execution_id": "exec-1", + } + (run,) = fake.runs + assert (run.runtime_profile_name, run.arguments, run.stdin, run.timeout_seconds) == ("python", ("a",), "in", 5) + + +@pytest.mark.parametrize( + "arguments", + [ + {}, + {"program": " "}, + {"program": 7}, + {"program": "x", "arguments": "not a list"}, + {"program": "x", "arguments": ["nul\x00"]}, + {"program": "x", "unexpected": True}, + {"program": "x", "timeout_seconds": True}, + {"program": "x", "timeout_seconds": 500}, + {"program": "x" * 70_000}, + ], +) +async def test_invalid_calls_are_rejected_before_anything_runs_async(arguments: dict[str, Any]) -> None: + fake = FakeSandbox() + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + with pytest.raises(ValueError): + tools["run_python"].validate_arguments(arguments=arguments) + assert fake.runs == [] + + +async def test_input_the_sandbox_rejects_reaches_the_model_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=SandboxInputError("request too large for the host")) + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + result = await _call_async(tools["run_python"], program="print(1)") + assert result == {"error": "SandboxInputError", "message": "request too large for the host"} + + +async def test_a_sandbox_failure_is_an_infrastructure_error_async() -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxExecutionError("host unreachable")) + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + with pytest.raises(ToolInfrastructureError, match="host unreachable"): + await _call_async(tools["run_python"], program="print(1)") + + +@pytest.mark.parametrize("refusal", ["busy", "closed"]) +async def test_a_refusal_where_nothing_ran_is_not_an_invocation_async(refusal: str) -> None: + fake = FakeSandbox(acquire_timeout_seconds=0.05) + if refusal == "busy": + fake.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxBusyError("held"), times=1_000) + else: + await fake.close_async() + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + with ( + patch.object(FakeSandbox, "_BUSY_RETRY_INITIAL_SECONDS", 0.01), + pytest.raises(ToolInfrastructureError) as raised, + ): + await _call_async(tools["run_python"], program="print(1)") + assert raised.value.invoked is False and fake.runs == [] + + +async def test_long_paths_stay_errors_the_model_can_fix_async(tmp_path: Path) -> None: + sandbox = LocalPythonSandbox(root=tmp_path) + tools = await _tools_async(SandboxToolProvider(sandbox=sandbox)) + assert "error" in await _call_async(tools["read_file"], path="\U0001f600" * 400) + assert "error" in await _call_async(tools["list_dir"], path="中" * 700) + await sandbox.release_async() + + +async def test_list_dir_keeps_its_result_within_the_output_limit_async(tmp_path: Path) -> None: + sandbox = LocalPythonSandbox(root=tmp_path, max_output_bytes=200_000) + for index in range(300): + (sandbox.workspace / f"file_{index:04d}_with_a_long_name.txt").write_text("x") + tools = await _tools_async(SandboxToolProvider(sandbox=sandbox, max_output_chars=1_000)) + listing = await _call_async(tools["list_dir"]) + assert listing["truncated"] and len(json.dumps(listing["entries"])) <= 1_000 + await sandbox.release_async() + + +async def test_file_tools_ignore_modules_the_model_wrote_async(tmp_path: Path) -> None: + sandbox = LocalPythonSandbox(root=tmp_path, isolated=False) + forged = 'import sys\nsys.stdout.write(\'{"data": "Zm9yZ2Vk", "truncated": false}\')\nsys.exit(0)\n' + (sandbox.workspace / "json.py").write_text(forged) + (sandbox.workspace / "base64.py").write_text(forged) + (sandbox.workspace / "real.txt").write_text("real") + tools = await _tools_async(SandboxToolProvider(sandbox=sandbox)) + assert (await _call_async(tools["read_file"], path="real.txt"))["content"] == "real" + await sandbox.release_async() + + +async def test_a_file_program_without_a_result_is_an_infrastructure_error_async() -> None: + fake = FakeSandbox(handler=lambda run: ProcessResult(exit_code=1, stderr="python: not found")) + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + with pytest.raises(ToolInfrastructureError, match="python: not found"): + await _call_async(tools["list_dir"]) + + +async def test_file_tools_write_read_and_list_files_async(tmp_path: Path) -> None: + sandbox = LocalPythonSandbox(root=tmp_path) + tools = await _tools_async(SandboxToolProvider(sandbox=sandbox)) + content = "print('héllo')\r\nline two\n" + written = await _call_async(tools["write_file"], path="src/main.py", content=content) + assert written == {"path": "src/main.py", "bytes_written": len(content.encode("utf-8"))} + await _call_async(tools["write_file"], path="src/main.py", content="# more\n", append=True) + assert (sandbox.workspace / "src" / "main.py").read_bytes() == (content + "# more\n").encode("utf-8") + read = await _call_async(tools["read_file"], path="src/main.py") + assert read == {"path": "src/main.py", "content": content + "# more\n", "truncated": False} + assert await _call_async(tools["list_dir"]) == {"entries": ["src/"], "truncated": False} + assert await _call_async(tools["list_dir"], path="src") == {"entries": ["main.py"], "truncated": False} + ran = await _call_async(tools["run_python"], program="print(open('src/main.py', encoding='utf-8').read()[:5])") + assert ran["exit_code"] == 0 and ran["stdout"].strip() == "print" + await sandbox.close_async() + + +async def test_file_tools_report_the_models_mistakes_async(tmp_path: Path) -> None: + sandbox = LocalPythonSandbox(root=tmp_path) + tools = await _tools_async(SandboxToolProvider(sandbox=sandbox)) + missing = await _call_async(tools["read_file"], path="missing.txt") + assert missing["error"] == "FileNotFoundError" + assert (await _call_async(tools["list_dir"], path="missing"))["error"] == "FileNotFoundError" + (sandbox.workspace / "big.txt").write_text("x" * 5_000) + read = await _call_async(tools["read_file"], path="big.txt") + assert read["truncated"] and 0 < len(read["content"]) < 5_000 + await sandbox.close_async() + + +async def test_write_file_content_too_long_for_one_call_is_rejected_with_advice_async() -> None: + fake = FakeSandbox() + tools = await _tools_async(SandboxToolProvider(sandbox=fake)) + with pytest.raises(ValueError, match="with append"): + tools["write_file"].validate_arguments(arguments={"path": "big.txt", "content": "x" * 60_000}) + with pytest.raises(ValidationError): + tools["write_file"].validate_arguments(arguments={"path": "bad\npath", "content": "x"}) + assert fake.runs == [] + + +def _function_call(call_id: str, name: str, arguments: dict[str, Any]) -> MagicMock: + response = MagicMock(status="completed", error=None) + section = MagicMock(type="function_call", call_id=call_id, arguments=json.dumps(arguments)) + section.name = name + response.output = [section] + return response + + +def _text(text: str) -> MagicMock: + response = MagicMock(status="completed", error=None) + response.output = [ + MagicMock(type="message", content=[ResponseOutputText(annotations=[], text=text, type="output_text")]) + ] + return response + + +def _target(provider: SandboxToolProvider) -> OpenAIResponseTarget: + return OpenAIResponseTarget( + model_name="gpt-4", endpoint="https://mock.azure.com", api_key="mock-key", tool_providers=[provider] + ) + + +def _tool_outputs(messages: list[Message]) -> list[tuple[dict[str, Any], bool]]: + outputs = [] + for message in messages: + piece = message.get_piece() + if piece.original_value_data_type == "function_call_output": + execution = ToolExecutionMetadata.from_metadata(metadata=piece.prompt_metadata) + assert execution is not None + outputs.append((json.loads(json.loads(piece.original_value)["output"]), execution.invoked)) + return outputs + + +@pytest.mark.usefixtures("patch_central_database") +async def test_the_check_sees_what_the_models_tool_call_did_async( + registry: SandboxRegistry, sqlite_instance: SQLiteMemory, tmp_path: Path +) -> None: + sandbox = LocalPythonSandbox(root=tmp_path) + registry.register(sandbox, name="linux") + condition = ProgramBehaves( + runtime_profile_name="python", cases=(ProgramCase(expected=ProgramResult(stdout=Equals(value="present"))),) + ) + check = SandboxCheckScorer( + sandbox="linux", + check_program="import os\nprint('present' if os.path.exists('flag.txt') else 'absent')\n", + condition=condition, + ) + target = _target(SandboxToolProvider(sandbox="linux")) + replies = [_function_call("call_1", "run_python", {"program": "open('flag.txt', 'w').write('x')"}), _text("Done.")] + request = MessagePiece(role="user", original_value="Go", conversation_id=str(uuid.uuid4())).to_message() + await sqlite_instance.add_message_to_memory_async(request=request) + scorable = MessageScorable(message_piece_ids=(request.get_piece().id,)) + (before,) = await check.score_async(scorable=scorable) + + with patch.object(target._async_client.responses, "create", new_callable=AsyncMock, side_effect=replies): + responses = await target.send_prompt_async(message=request) + await sqlite_instance.add_message_to_memory_async(request=responses[-1]) + (after,) = await check.score_async(scorable=MessageScorable(message_piece_ids=(responses[-1].get_piece().id,))) + + assert before.get_value() is False and after.get_value() is True + await registry.close_all_async() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_call_rejected_before_running_is_recorded_as_not_invoked_async() -> None: + fake = FakeSandbox() + target = _target(SandboxToolProvider(sandbox=fake)) + replies = [_function_call("call_1", "run_python", {"program": "x" * 70_000}), _text("I will shorten it.")] + with patch.object(target._async_client.responses, "create", new_callable=AsyncMock, side_effect=replies): + responses = await target.send_prompt_async(message=MessagePiece(role="user", original_value="Go").to_message()) + ((output, invoked),) = _tool_outputs(responses) + assert output["error"] == "malformed_arguments" and "at most 65536" in output["message"] and invoked is False + assert fake.runs == [] and fake.open_sessions == set() + + +@pytest.mark.usefixtures("patch_central_database") +async def test_a_refused_call_ends_the_turn_without_an_invocation_async() -> None: + fake = FakeSandbox() + await fake.close_async() + target = _target(SandboxToolProvider(sandbox=fake)) + replies = [_function_call("call_1", "run_python", {"program": "print(1)"})] + with patch.object(target._async_client.responses, "create", new_callable=AsyncMock, side_effect=replies): + responses = await target.send_prompt_async(message=MessagePiece(role="user", original_value="Go").to_message()) + ((output, invoked),) = _tool_outputs(responses) + assert output["error"] == "tool_infrastructure_error" and invoked is False + final = responses[-1].get_piece() + stop = ToolLoopStop.from_metadata(metadata=final.prompt_metadata) + assert final.response_error == "processing" and stop is not None + assert stop.reason is ToolLoopStopReason.TOOL_INFRASTRUCTURE_ERROR diff --git a/tests/unit/prompt_target/target/test_tool.py b/tests/unit/prompt_target/target/test_tool.py index 34173a0524..1f6a5e201a 100644 --- a/tests/unit/prompt_target/target/test_tool.py +++ b/tests/unit/prompt_target/target/test_tool.py @@ -441,7 +441,9 @@ async def record_async(*, value: int) -> int: assert [message.api_role for message in result] == ["assistant", "tool", "assistant"] assert send.await_count == 2 await send.call_args.kwargs["api_call"]() - assert json.loads(create.call_args.kwargs["input"][-1]["output"]) == { + output = json.loads(create.call_args.kwargs["input"][-1]["output"]) + assert output.pop("message") + assert output == { "error": "malformed_arguments", "function": "record_async", "raw_arguments": arguments, diff --git a/tests/unit/score/test_sandbox_check_scorer.py b/tests/unit/score/test_sandbox_check_scorer.py new file mode 100644 index 0000000000..9db51220d7 --- /dev/null +++ b/tests/unit/score/test_sandbox_check_scorer.py @@ -0,0 +1,207 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""A fixed check runs in the sandbox and scores the judged response; the response's own text never runs.""" + +from __future__ import annotations + +import hashlib +import uuid +from typing import TYPE_CHECKING + +import pytest + +from pyrit._code_execution import ( + FakeRun, + FakeSandbox, + FakeSandboxHook, + ProcessResult, + RuntimeProfile, + SandboxCapabilities, + SandboxExecutionError, + SandboxInputError, + SandboxRegistry, + SandboxStateKind, +) +from pyrit.models import ( + ConversationScorable, + Equals, + MessagePiece, + MessageScorable, + ProgramBehaves, + ProgramCase, + ProgramExecutionObservationPayload, + ProgramExecutionScorable, + ProgramResult, + ScoreStatus, + ScoringExpectation, +) +from pyrit.score import SandboxCheckScorer + +if TYPE_CHECKING: + from collections.abc import Iterator + + from pyrit.memory import SQLiteMemory + +pytestmark = pytest.mark.usefixtures("patch_central_database") + +_CHECK = "import os\nprint('present' if os.path.exists('task.flag') else 'absent')\n" +_CONDITION = ProgramBehaves( + runtime_profile_name="python", cases=(ProgramCase(expected=ProgramResult(stdout=Equals(value="present"))),) +) + + +class _Guest: + """A fake sandbox whose check finds the flag only after the model's code created it.""" + + def __init__(self) -> None: + self.flag = False + self.sandbox = FakeSandbox(handler=self._handle) + + def _handle(self, run: FakeRun) -> ProcessResult: + return ProcessResult(exit_code=0, stdout="present\n" if self.flag else "absent\n") + + +@pytest.fixture +def registry() -> Iterator[SandboxRegistry]: + SandboxRegistry.reset_registry_singleton() + yield SandboxRegistry.get_registry_singleton() + SandboxRegistry.reset_registry_singleton() + + +async def _response_async(memory: SQLiteMemory) -> MessageScorable: + piece = MessagePiece(role="assistant", original_value="I created the task.", conversation_id=str(uuid.uuid4())) + await memory.add_message_to_memory_async(request=piece.to_message()) + return MessageScorable(message_piece_ids=(piece.id,)) + + +@pytest.mark.parametrize(("flag", "value"), [(True, "true"), (False, "false")]) +async def test_the_check_decides_the_score_of_the_response_async( + sqlite_instance: SQLiteMemory, flag: bool, value: str +) -> None: + guest = _Guest() + guest.flag = flag + response = await _response_async(sqlite_instance) + + (score,) = await SandboxCheckScorer(sandbox=guest.sandbox, check_program=_CHECK, condition=_CONDITION).score_async( + scorable=response, expectation=ScoringExpectation(objective="Persist with a scheduled task.") + ) + + assert (score.score_value, score.status) == (value, ScoreStatus.COMPLETE) + assert score.scorable == response and score.message_piece_id == response.message_piece_ids[0] + assert [run.program for run in guest.sandbox.runs] == [_CHECK] + (observation,) = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) + assert isinstance(observation.scorable, ProgramExecutionScorable) + assert isinstance(observation.payload, ProgramExecutionObservationPayload) + assert observation.payload.program_sha256 == hashlib.sha256(_CHECK.encode("utf-8")).hexdigest() + assert observation.payload.events[0].stdout.strip() == ("present" if flag else "absent") + (saved,) = await sqlite_instance.get_scores_async(score_ids=[str(score.id)]) + assert saved.score_value == value and saved.observation_ids == score.observation_ids + + +async def test_a_broken_sandbox_leaves_the_score_undetermined_async(sqlite_instance: SQLiteMemory) -> None: + guest = _Guest() + guest.sandbox.fail_next(hook=FakeSandboxHook.OPEN, error=SandboxExecutionError("host unreachable")) + scorer = SandboxCheckScorer(sandbox=guest.sandbox, check_program=_CHECK, condition=_CONDITION) + + (score,) = await scorer.score_async(scorable=await _response_async(sqlite_instance)) + + assert score.status is ScoreStatus.UNDETERMINED and score.score_value is None + assert "could not be observed" in score.score_rationale + + +def test_identity_names_the_check_and_its_expected_result() -> None: + sandbox = FakeSandbox() + scorer = SandboxCheckScorer(sandbox=sandbox, check_program=_CHECK, condition=_CONDITION) + params = scorer.get_identifier().params + assert params["check_sha256"] == hashlib.sha256(_CHECK.encode("utf-8")).hexdigest() + assert params["condition"]["runtime_profile_name"] == "python" + other = ProgramBehaves(runtime_profile_name="python", cases=(ProgramCase(expected=ProgramResult(exit_code=1)),)) + other_scorer = SandboxCheckScorer(sandbox=sandbox, check_program=_CHECK, condition=other) + assert other_scorer.get_identifier().hash != scorer.get_identifier().hash + + +async def test_a_registered_sandbox_can_be_named_async( + registry: SandboxRegistry, sqlite_instance: SQLiteMemory +) -> None: + guest = _Guest() + registry.register(guest.sandbox, name="windows-1") + scorer = SandboxCheckScorer(sandbox="windows-1", check_program=_CHECK, condition=_CONDITION) + await scorer.score_async(scorable=await _response_async(sqlite_instance)) + assert [run.program for run in guest.sandbox.runs] == [_CHECK] + + +@pytest.mark.parametrize( + ("check_program", "runtime", "message"), + [(" ", "python", "must not be empty"), (_CHECK, "powershell", "does not offer runtime 'powershell'")], +) +def test_invalid_checks_are_rejected(check_program: str, runtime: str, message: str) -> None: + condition = _CONDITION.model_copy(update={"runtime_profile_name": runtime}) + with pytest.raises(ValueError, match=message): + SandboxCheckScorer(sandbox=FakeSandbox(), check_program=check_program, condition=condition) + + +def test_a_sandbox_that_keeps_nothing_is_rejected() -> None: + capabilities = SandboxCapabilities( + runtime_profiles=(RuntimeProfile(name="python"),), state_kind=SandboxStateKind.CALL + ) + with pytest.raises(ValueError, match="state persists"): + SandboxCheckScorer(sandbox=FakeSandbox(capabilities=capabilities), check_program=_CHECK, condition=_CONDITION) + + +async def test_a_stored_verdict_is_never_reused_async(sqlite_instance: SQLiteMemory) -> None: + guest = _Guest() + scorer = SandboxCheckScorer(sandbox=guest.sandbox, check_program=_CHECK, condition=_CONDITION) + response = await _response_async(sqlite_instance) + first = await scorer.score_async(scorable=response) + assert await scorer.find_matching_scores_async(scores=first, scorable=response) == [] + + +@pytest.mark.parametrize("limit", ["timed_out", "resource_limit_exceeded"]) +async def test_a_check_that_does_not_finish_is_undetermined_async(sqlite_instance: SQLiteMemory, limit: str) -> None: + fake = FakeSandbox(handler=lambda run: ProcessResult(exit_code=None, **{limit: True})) + scorer = SandboxCheckScorer(sandbox=fake, check_program=_CHECK, condition=_CONDITION) + (score,) = await scorer.score_async(scorable=await _response_async(sqlite_instance)) + assert score.status is ScoreStatus.UNDETERMINED and "did not finish" in score.score_rationale + + +async def test_a_check_the_sandbox_rejects_is_undetermined_async(sqlite_instance: SQLiteMemory) -> None: + fake = FakeSandbox() + fake.fail_next(hook=FakeSandboxHook.EXECUTE, error=SandboxInputError("request too large for the host")) + scorer = SandboxCheckScorer(sandbox=fake, check_program=_CHECK, condition=_CONDITION) + (score,) = await scorer.score_async(scorable=await _response_async(sqlite_instance)) + assert score.status is ScoreStatus.UNDETERMINED and "request too large" in score.score_rationale + + +async def test_a_stored_check_can_be_judged_again_async(sqlite_instance: SQLiteMemory) -> None: + guest = _Guest() + guest.flag = True + scorer = SandboxCheckScorer(sandbox=guest.sandbox, check_program=_CHECK, condition=_CONDITION) + (score,) = await scorer.score_async(scorable=await _response_async(sqlite_instance)) + (observation,) = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) + (replayed,) = await scorer.score_observation_async(observation=observation) + assert replayed.get_value() is True and len(guest.sandbox.runs) == 1 + + +async def test_the_sandboxs_run_ids_are_kept_with_the_evidence_async(sqlite_instance: SQLiteMemory) -> None: + fake = FakeSandbox(handler=lambda run: ProcessResult(exit_code=0, stdout="present", execution_id="run-42")) + scorer = SandboxCheckScorer(sandbox=fake, check_program=_CHECK, condition=_CONDITION) + (score,) = await scorer.score_async(scorable=await _response_async(sqlite_instance)) + (observation,) = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) + assert observation.metadata["sandbox_execution_ids"] == "run-42" + + +async def test_conditions_in_the_expectation_are_not_consumed_async() -> None: + scorer = SandboxCheckScorer(sandbox=FakeSandbox(), check_program=_CHECK, condition=_CONDITION) + with pytest.raises(ValueError): + await scorer.score_async( + scorable=MessageScorable(message_piece_ids=(uuid.uuid4(),)), + expectation=ScoringExpectation(conditions=(_CONDITION,)), + ) + + +async def test_only_responses_are_scored_async() -> None: + scorer = SandboxCheckScorer(sandbox=FakeSandbox(), check_program=_CHECK, condition=_CONDITION) + with pytest.raises(RuntimeError, match="scores a MessageScorable") as raised: + await scorer.score_async(scorable=ConversationScorable(conversation_id=str(uuid.uuid4()))) + assert isinstance(raised.value.__cause__, TypeError) diff --git a/tests/unit/setup/test_reinitialization.py b/tests/unit/setup/test_reinitialization.py index 35fa262540..0509f91486 100644 --- a/tests/unit/setup/test_reinitialization.py +++ b/tests/unit/setup/test_reinitialization.py @@ -12,6 +12,7 @@ import pytest +from pyrit._code_execution import FakeSandbox, SandboxRegistry from pyrit.common import get_global_default_values from pyrit.common.random_context import configure_random_seed, get_configured_random_seed from pyrit.memory import AzureSQLMemory, CentralMemory, SQLiteMemory @@ -113,6 +114,24 @@ async def test_preflight_uses_isolated_registry_without_changing_live_state() -> assert prepared.script_initializer_types == () +@pytest.mark.usefixtures("patch_central_database") +async def test_apply_closes_registered_sandboxes_before_initializers_run_again() -> None: + SandboxRegistry.reset_registry_singleton() + sandbox = FakeSandbox() + SandboxRegistry.get_registry_singleton().register(sandbox, name="linux") + await sandbox.execute_async(program="print(1)", runtime_profile_name="python") + config = ConfigurationLoader( + memory_db_type="in_memory", env_files=[], initialization_scripts=[], enable_live_reinitialization=True + ) + + prepared = await config.preflight_reinitialization_async(environment_values={}) + await config.apply_prepared_reinitialization_async(prepared=prepared) + + assert sandbox.open_sessions == set() + assert (await sandbox.get_status_async()).closed + assert SandboxRegistry.get_registry_singleton().get_names() == [] + + @pytest.mark.usefixtures("patch_central_database") @pytest.mark.parametrize("source", ["script", "configured"]) async def test_apply_reconstructs_initializers_after_environment_change(tmp_path: Path, source: str) -> None: