Files
nanobot/tests/tools/test_tool_validation.py
T

983 lines
34 KiB
Python

import shlex
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock
import pytest
from pydantic import ValidationError
from nanobot.agent.tools import (
ArraySchema,
IntegerSchema,
ObjectSchema,
Schema,
StringSchema,
tool_parameters,
tool_parameters_schema,
)
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.shell import ExecTool, ExecToolConfig
from nanobot.execution import processes
from nanobot.security.network import configure_ssrf_whitelist
class SampleTool(Tool):
@property
def name(self) -> str:
return "sample"
@property
def description(self) -> str:
return "sample tool"
@property
def parameters(self) -> dict[str, Any]:
return {
"type": "object",
"properties": {
"query": {"type": "string", "minLength": 2},
"count": {"type": "integer", "minimum": 1, "maximum": 10},
"mode": {"type": "string", "enum": ["fast", "full"]},
"meta": {
"type": "object",
"properties": {
"tag": {"type": "string"},
"flags": {
"type": "array",
"items": {"type": "string"},
},
},
"required": ["tag"],
},
},
"required": ["query", "count"],
}
async def execute(self, **kwargs: Any) -> str:
return "ok"
@tool_parameters(
tool_parameters_schema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
required=["query", "count"],
)
)
class DecoratedSampleTool(Tool):
@property
def name(self) -> str:
return "decorated_sample"
@property
def description(self) -> str:
return "decorated sample tool"
async def execute(self, **kwargs: Any) -> str:
return f"ok:{kwargs['count']}"
def test_schema_validate_value_matches_tool_validate_params() -> None:
root = tool_parameters_schema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
required=["query", "count"],
)
obj = ObjectSchema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
required=["query", "count"],
)
params = {"query": "h", "count": 2}
class _Mini(Tool):
@property
def name(self) -> str:
return "m"
@property
def description(self) -> str:
return ""
@property
def parameters(self) -> dict[str, Any]:
return root
async def execute(self, **kwargs: Any) -> str:
return ""
expected = _Mini().validate_params(params)
assert Schema.validate_json_schema_value(params, root, "") == expected
assert obj.validate_value(params, "") == expected
assert IntegerSchema(minimum=1).validate_value(0, "n") == ["n: 0 is less than the minimum of 1"]
def test_schema_classes_equivalent_to_sample_tool_parameters() -> None:
built = tool_parameters_schema(
query=StringSchema(min_length=2),
count=IntegerSchema(minimum=1, maximum=10),
mode=StringSchema("", enum=["fast", "full"]),
meta=ObjectSchema(
tag=StringSchema(""),
flags=ArraySchema(StringSchema("")),
required=["tag"],
),
required=["query", "count"],
additional_properties=None,
)
assert built == SampleTool().parameters
def test_tool_parameters_returns_fresh_copy_per_access() -> None:
tool = DecoratedSampleTool()
first = tool.parameters
second = tool.parameters
assert first == second
assert first is not second
assert first["properties"] is not second["properties"]
first["properties"]["query"]["minLength"] = 99
assert tool.parameters["properties"]["query"]["minLength"] == 2
async def test_registry_executes_decorated_tool_end_to_end() -> None:
reg = ToolRegistry()
reg.register(DecoratedSampleTool())
ok = await reg.execute("decorated_sample", {"query": "hello", "count": 3})
assert ok == "ok:3"
err = await reg.execute("decorated_sample", {"query": "h", "count": 3})
assert "Invalid parameters" in err
@pytest.mark.parametrize("schema_type", ["integer", ["integer", "null"], ["integer", "string"]])
def test_integer_schema_accepts_integral_json_numbers(schema_type) -> None:
assert Schema.validate_json_schema_value(3.0, {"type": schema_type}) == []
async def test_registry_preserves_integral_json_number() -> None:
reg = ToolRegistry()
reg.register(DecoratedSampleTool())
result = await reg.execute("decorated_sample", {"query": "hello", "count": 3.0})
assert result == "ok:3.0"
def test_validate_params_missing_required() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "hi"})
assert "'count' is a required property" in "; ".join(errors)
def test_validate_params_type_and_range() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "hi", "count": 0})
assert any("count: 0 is less than the minimum of 1" in e for e in errors)
errors = tool.validate_params({"query": "hi", "count": "2"})
assert any("count: '2' is not of type 'integer'" in e for e in errors)
def test_validate_params_enum_and_min_length() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "h", "count": 2, "mode": "slow"})
assert any("query: 'h' is too short" in e for e in errors)
assert any("mode: 'slow' is not one of" in e for e in errors)
@pytest.mark.parametrize(
"value, allowed, valid",
[
(True, 1, False),
(False, 0, False),
(1, True, False),
(0, False, False),
([True], [1], False),
({"enabled": True}, {"enabled": 1}, False),
(1.0, 1, True),
(True, True, True),
("x", "x", True),
({"a": 1, "b": 2}, {"b": 2.0, "a": 1.0}, True),
],
)
@pytest.mark.asyncio
async def test_registry_enforces_json_enum_equality(value, allowed, valid) -> None:
calls = []
class EnumTool(SampleTool):
@property
def parameters(self) -> dict[str, Any]:
return {
"type": "object",
"properties": {"value": {"enum": [allowed]}},
"required": ["value"],
}
async def execute(self, **kwargs: Any) -> str:
calls.append(kwargs["value"])
return "ok"
registry = ToolRegistry()
registry.register(EnumTool())
result = await registry.execute("sample", {"value": value})
if valid:
assert result == "ok"
assert calls == [value]
else:
assert f"value: {value!r} is not one of" in result
assert calls == []
def test_validate_params_nested_object_and_array() -> None:
tool = SampleTool()
errors = tool.validate_params(
{
"query": "hi",
"count": 2,
"meta": {"flags": [1, "ok"]},
}
)
assert any("meta: 'tag' is a required property" in e for e in errors)
assert any("meta.flags[0]: 1 is not of type 'string'" in e for e in errors)
def test_validate_params_ignores_unknown_fields() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "hi", "count": 2, "extra": "x"})
assert errors == []
def test_tool_parameters_schema_rejects_unknown_fields_by_default() -> None:
tool = DecoratedSampleTool()
errors = tool.validate_params({"query": "hi", "count": 2, "extra": "x"})
assert errors == ["parameters: Additional properties are not allowed ('extra' was unexpected)"]
def test_validate_params_validates_typed_additional_properties() -> None:
schema = {
"type": "object",
"properties": {},
"additionalProperties": {"type": "integer"},
}
tool = SchemaTestTool(schema)
errors = tool.validate_params({"extra": "2"})
assert errors == ["extra: '2' is not of type 'integer'"]
async def test_registry_returns_validation_error() -> None:
reg = ToolRegistry()
reg.register(SampleTool())
result = await reg.execute("sample", {"query": "hi"})
assert "Invalid parameters" in result
def test_exec_extract_absolute_paths_keeps_full_windows_path() -> None:
cmd = r"type C:\user\workspace\txt"
paths = ExecTool._extract_absolute_paths(cmd)
assert paths == [r"C:\user\workspace\txt"]
def test_exec_extract_absolute_paths_captures_windows_drive_root_path() -> None:
# Note: raw strings cannot end with a single backslash.
cmd = "dir E:\\"
paths = ExecTool._extract_absolute_paths(cmd)
assert paths == ["E:\\"]
def test_exec_extract_absolute_paths_ignores_relative_posix_segments() -> None:
cmd = ".venv/bin/python script.py"
paths = ExecTool._extract_absolute_paths(cmd)
assert "/bin/python" not in paths
def test_exec_extract_absolute_paths_ignores_urls() -> None:
cmd = 'curl -s -o /dev/null -w "%{http_code}" https://www.google.com'
paths = ExecTool._extract_absolute_paths(cmd)
assert paths == ["/dev/null"]
@pytest.mark.parametrize(
"command",
[
'curl -s -o /dev/null -w "%{http_code}" https://www.google.com',
'wget -q -O - http://example.com 2>&1 | head -c 100',
'python3 -c "import urllib.request; print(urllib.request.urlopen(\'http://example.com\').read()[:100])"',
],
)
def test_exec_guard_allows_public_urls(tmp_path, command: str) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command(command, str(tmp_path))
assert error is None
def test_exec_guard_allows_whitelisted_internal_urls(tmp_path) -> None:
configure_ssrf_whitelist(["10.10.10.0/24"])
try:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command(
'curl -s -H "Authorization: Bearer ..." http://10.10.10.3:8123/api/',
str(tmp_path),
)
assert error is None
finally:
configure_ssrf_whitelist([])
def test_exec_extract_absolute_paths_captures_posix_absolute_paths() -> None:
cmd = "cat /tmp/data.txt > /tmp/out.txt"
paths = ExecTool._extract_absolute_paths(cmd)
assert "/tmp/data.txt" in paths
assert "/tmp/out.txt" in paths
def test_exec_extract_absolute_paths_captures_home_paths() -> None:
cmd = "cat ~/.nanobot/config.json > ~/out.txt"
paths = ExecTool._extract_absolute_paths(cmd)
assert "~/.nanobot/config.json" in paths
assert "~/out.txt" in paths
def test_exec_extract_absolute_paths_captures_paths_after_equals() -> None:
cmd = "curl --output=/etc/passwd --config=~/.nanobot/config.json --user-home=~root"
paths = ExecTool._extract_absolute_paths(cmd)
assert "/etc/passwd" in paths
assert "~/.nanobot/config.json" in paths
assert "~root" in paths
def test_exec_extract_absolute_paths_does_not_capture_query_tilde() -> None:
cmd = 'python query.py --query \'{job=~"app"}\''
paths = ExecTool._extract_absolute_paths(cmd)
assert not any(p.startswith("~") for p in paths)
def test_exec_extract_absolute_paths_captures_bare_and_named_user_home_paths() -> None:
paths = ExecTool._extract_absolute_paths("cd ~ && cat ~root/.bashrc")
assert "~" in paths
assert "~root/.bashrc" in paths
def test_exec_extract_absolute_paths_captures_tilde_after_shell_operators() -> None:
paths = ExecTool._extract_absolute_paths(
"cat <~root/.bashrc;~root/bin/tool|~daemon/bin/tool"
)
assert "~root/.bashrc" in paths
assert paths.count("~root/bin/tool") == 1
assert "~daemon/bin/tool" in paths
def test_exec_extract_absolute_paths_captures_tilde_assignment_components() -> None:
paths = ExecTool._extract_absolute_paths(
"HOME=~ PATH=bin:~root/bin curl --config=~"
)
assert "~" in paths
assert "~root/bin" in paths
def test_exec_extract_absolute_paths_captures_quoted_paths() -> None:
cmd = 'cat "/tmp/data.txt" "~/.nanobot/config.json"'
paths = ExecTool._extract_absolute_paths(cmd)
assert "/tmp/data.txt" in paths
assert "~/.nanobot/config.json" in paths
def test_exec_guard_blocks_home_path_outside_workspace(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat ~/.nanobot/config.json", str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
assert "hard policy boundary" in error
@pytest.mark.skipif(sys.platform == "win32", reason="Unix resolves named homes through passwd")
@pytest.mark.parametrize(
"command",
["cat ~unknown/file.txt", "cat --config=~unknown/file.txt", "cat <~unknown/file.txt"],
)
async def test_exec_rejects_unknown_user_home(tmp_path, monkeypatch, command) -> None:
home_path = f"~nanobot-missing-{tmp_path.name}/file.txt"
command = command.replace("~unknown/file.txt", home_path)
with pytest.raises(RuntimeError):
Path(home_path).expanduser()
spawn = AsyncMock(side_effect=AssertionError("Blocked commands must not start a process"))
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
result = await ExecTool(
working_dir=str(tmp_path), restrict_to_workspace=True,
).execute(command=command)
assert result.startswith("Error: Command blocked by safety guard (path outside working dir)")
assert "hard policy boundary" in result
spawn.assert_not_called()
async def test_exec_rejects_home_path_without_home_directory(tmp_path, monkeypatch) -> None:
for key in ("HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"):
monkeypatch.delenv(key, raising=False)
if sys.platform != "win32":
import pwd
def missing_passwd_entry(uid):
# A container UID may have no passwd entry when HOME is unset.
raise KeyError(uid)
monkeypatch.setattr(pwd, "getpwuid", missing_passwd_entry)
with pytest.raises(RuntimeError):
Path("~/file.txt").expanduser()
spawn = AsyncMock(side_effect=AssertionError("Blocked commands must not start a process"))
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
result = await ExecTool(
working_dir=str(tmp_path), restrict_to_workspace=True,
).execute(command="cat ~/file.txt")
assert result.startswith("Error: Command blocked by safety guard (path outside working dir)")
assert "hard policy boundary" in result
spawn.assert_not_called()
async def test_exec_allows_resolved_home_inside_workspace(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("USERPROFILE" if sys.platform == "win32" else "HOME", str(tmp_path))
(tmp_path / "file.txt").write_text("allowed home content", encoding="utf-8")
result = await ExecTool(
working_dir=str(tmp_path), restrict_to_workspace=True,
).execute(command="cat ~/file.txt", login=False, yield_time_ms=10000)
assert "allowed home content" in result
assert "Exit code: 0" in result
@pytest.mark.parametrize(
"command",
[
pytest.param("cd ~ && cat secret.txt", id="bare_tilde_cwd_escape"),
pytest.param("cat ~root/.bashrc", id="named_user_home_path"),
pytest.param("cat --config=~/.nanobot/config.json", id="equals_home_path_outside_workspace"),
pytest.param("cat --config=~root/.bashrc", id="equals_named_user_home_path"),
],
)
def test_exec_guard_blocks_home_paths_outside_workspace(tmp_path, command) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command(command, str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
@pytest.mark.parametrize(
"command",
[
"cat <~root/.bashrc",
"cat ~-/.bashrc",
"cat ~+1/.bashrc",
"cat ~-1/.bashrc",
],
)
def test_exec_guard_blocks_home_paths_with_special_shell_contexts(
tmp_path, command: str
) -> None:
error = ExecTool(restrict_to_workspace=True)._guard_command(command, str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
def test_exec_guard_allows_current_directory_tilde(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
assert tool._guard_command("cat ~+/file.txt", str(tmp_path)) is None
def test_exec_guard_blocks_quoted_home_path_outside_workspace(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command('cat "~/.nanobot/config.json"', str(tmp_path))
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
assert "hard policy boundary" in error
def test_exec_guard_allows_media_path_outside_workspace(tmp_path, monkeypatch) -> None:
media_dir = tmp_path / "media"
media_dir.mkdir()
media_file = media_dir / "photo.jpg"
media_file.write_text("ok", encoding="utf-8")
monkeypatch.setattr("nanobot.agent.tools.shell.get_media_dir", lambda: media_dir)
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command(f'cat "{media_file}"', str(tmp_path / "workspace"))
assert error is None
def test_exec_guard_blocks_windows_drive_root_outside_workspace(monkeypatch) -> None:
import nanobot.agent.tools.shell as shell_mod
class FakeWindowsPath:
def __init__(self, raw: str) -> None:
self.raw = raw.rstrip("\\") + ("\\" if raw.endswith("\\") else "")
def resolve(self) -> "FakeWindowsPath":
return self
def expanduser(self) -> "FakeWindowsPath":
return self
def is_absolute(self) -> bool:
return len(self.raw) >= 3 and self.raw[1:3] == ":\\"
@property
def parents(self) -> list["FakeWindowsPath"]:
if not self.is_absolute():
return []
trimmed = self.raw.rstrip("\\")
if len(trimmed) <= 2:
return []
idx = trimmed.rfind("\\")
if idx <= 2:
return [FakeWindowsPath(trimmed[:2] + "\\")]
parent = FakeWindowsPath(trimmed[:idx])
return [parent, *parent.parents]
def __eq__(self, other: object) -> bool:
return isinstance(other, FakeWindowsPath) and self.raw.lower() == other.raw.lower()
monkeypatch.setattr(shell_mod, "Path", FakeWindowsPath)
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("dir E:\\", "E:\\workspace")
assert error is not None
assert error.startswith(
"Error: Command blocked by safety guard (path outside working dir)"
)
assert "hard policy boundary" in error
def test_exec_guard_allows_dev_null_redirect(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
ws = tmp_path / "workspace"
ws.mkdir()
(ws / "file.txt").write_text("ok", encoding="utf-8")
error = tool._guard_command(f'rm "{ws / "file.txt"}" 2>/dev/null', str(ws))
assert error is None
def test_exec_guard_allows_dev_urandom(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat /dev/urandom | head -c 16 > random.bin", str(tmp_path))
assert error is None
def test_exec_guard_blocks_non_benign_dev_path(tmp_path) -> None:
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command("cat /dev/sda", str(tmp_path))
assert error is not None
assert "path outside working dir" in error
def test_exec_extract_absolute_paths_ignores_pipe_tilde() -> None:
cmd = "python query.py --query '{job=\"app\"} |~ \"error\"'"
paths = ExecTool._extract_absolute_paths(cmd)
assert not any(p.startswith("~") for p in paths)
class SchemaTestTool(Tool):
"""Minimal tool with a supplied parameter schema."""
def __init__(self, schema: dict[str, Any]) -> None:
self._schema = schema
@property
def name(self) -> str:
return "schema_test"
@property
def description(self) -> str:
return "test tool for schema validation"
@property
def parameters(self) -> dict[str, Any]:
return self._schema
async def execute(self, **kwargs: Any) -> str:
return "ok"
@pytest.mark.parametrize("schema, value, valid", [
({"type": "integer"}, "42", 42),
({"type": "number"}, "3.14", 3.14),
({"type": "boolean"}, "false", False),
({"type": "string"}, 123, "123"),
({"type": "array", "items": {"type": "integer"}}, ["1", "2"], [1, 2]),
({"type": "object", "properties": {"port": {"type": "integer"}}}, {"port": "8080"}, {"port": 8080}),
])
def test_registry_rejects_wrong_types_and_accepts_corrected_arguments(schema, value, valid):
tool = SchemaTestTool({"type": "object", "properties": {"value": schema}})
registry = ToolRegistry()
registry.register(tool)
_, arguments, error = registry.prepare_call(tool.name, {"value": value})
assert arguments == {"value": value}
assert error is not None
assert "value" in error
assert "is not of type" in error
assert registry.prepare_call(tool.name, {"value": valid})[2] is None
@pytest.mark.parametrize("types", [["array", "object"], ["object", "array"]])
@pytest.mark.parametrize("value", [[2], {"count": 2}])
def test_type_union_validates_matching_container(types, value) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {
"type": types,
"properties": {"count": {"type": "integer", "minimum": 1}},
"items": {"type": "integer", "minimum": 1},
}},
})
assert tool.validate_params({"value": value}) == []
invalid = {"count": 0} if isinstance(value, dict) else [0]
assert "is less than the minimum of 1" in "; ".join(tool.validate_params({"value": invalid}))
@pytest.mark.parametrize("types", [["integer", "string"], ["string", "integer"]])
@pytest.mark.parametrize(
"value, error", [(0, "is less than the minimum of 1"), ("ab", "is too short")],
)
def test_type_union_enforces_matching_type_constraints(types, value, error) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": types, "minimum": 1, "minLength": 3}},
})
assert error in "; ".join(tool.validate_params({"value": value}))
@pytest.mark.parametrize("types", [["integer", "string"], ["string", "integer"]])
@pytest.mark.parametrize("value", [True, 1.5, None])
def test_type_union_rejects_undeclared_types_without_coercion(types, value) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": types}},
})
assert tool.validate_params({"value": value})
@pytest.mark.parametrize(
"types, value, error",
[
(["number", "boolean", "null"], True, None),
(["number", "boolean", "null"], 1.5, None),
(["number", "boolean", "null"], None, None),
(["string", "number"], float("inf"), "value: inf is not of type 'string', 'number'"),
(["string", "number"], float("nan"), "value: nan is not of type 'string', 'number'"),
],
)
def test_type_union_preserves_numeric_boolean_and_null_values(types, value, error) -> None:
for order in (types, types[::-1]):
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": order}},
})
errors = tool.validate_params({"value": value})
expected = f"value: {value!r} is not of type {', '.join(repr(t) for t in order)}"
assert errors == ([expected] if error else [])
@pytest.mark.parametrize("value", [42, None])
def test_nullable_integer_accepts_integer_and_null(value) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": ["integer", "null"]}},
})
assert tool.validate_params({"value": value}) == []
def test_validate_params_rejects_boolean_as_integer() -> None:
tool = SchemaTestTool({"type": "object", "properties": {"count": {"type": "integer"}}})
assert tool.validate_params({"count": True}) == ["count: True is not of type 'integer'"]
@pytest.mark.parametrize(
"value",
[float("nan"), float("inf"), float("-inf"), "NaN", "Infinity", "-Infinity"],
)
def test_validate_params_rejects_non_finite_numbers(value: float | str) -> None:
tool = SchemaTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
assert tool.validate_params({"rate": value}) == [f"rate: {value!r} is not of type 'number'"]
def test_validate_params_bool_not_accepted_as_number() -> None:
tool = SchemaTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
errors = tool.validate_params({"rate": False})
assert errors == ["rate: False is not of type 'number'"]
@pytest.mark.parametrize("schema_type", ["string", "integer", "array", "object"])
def test_validate_params_rejects_undeclared_null(schema_type) -> None:
tool = SchemaTestTool({"type": "object", "properties": {"value": {"type": schema_type}}})
assert tool.validate_params({"value": None}) == [f"value: None is not of type '{schema_type}'"]
@pytest.mark.parametrize("value", [5, "text"])
def test_validate_params_rejects_scalar_for_array(value) -> None:
tool = SchemaTestTool({"type": "object", "properties": {"items": {"type": "array"}}})
assert tool.validate_params({"items": value}) == [f"items: {value!r} is not of type 'array'"]
async def test_completed_exec_returns_exit_code() -> None:
tool = ExecTool()
result = await tool.execute(command="echo hello", yield_time_ms=10000)
assert "Exit code: 0" in result
assert "hello" in result
async def test_exec_head_tail_truncation(tmp_path) -> None:
tool = ExecTool()
# Generate output that exceeds _MAX_OUTPUT (10_000 chars).
# Use a temp script file so the output-generating logic lives in a file
# (Windows cmd.exe has finicky rules for quoting `-c` payloads with
# embedded newlines). ExecTool runs via create_subprocess_shell, so we
# must quote *both* the interpreter path and the script path — tmp_path
# on some CI runners and on many local Windows installs contains spaces
# (e.g. C:\Users\John Doe\AppData\...) which would otherwise break the
# shell's argv split.
script_file = tmp_path / "gen_output.py"
script_file.write_text("print('A' * 6000 + chr(10) + 'B' * 6000)", encoding="utf-8")
if sys.platform == "win32":
command = subprocess.list2cmdline([sys.executable, str(script_file)])
else:
command = f"{shlex.quote(sys.executable)} {shlex.quote(str(script_file))}"
result = await tool.execute(command=command, yield_time_ms=10000)
assert "chars truncated" in result
assert result.startswith("A")
assert "Exit code:" in result
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
async def test_exec_timeout_parameter(runtime_parameter) -> None:
tool = ExecTool(timeout=60)
started_at = time.monotonic()
result = await tool.execute(
command=[sys.executable, "-c", "import time; time.sleep(10)"],
yield_time_ms=5000,
**{runtime_parameter: 1},
)
assert "timed out" in result
assert time.monotonic() - started_at < 8
assert "Exit code: 0" not in result
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
@pytest.mark.parametrize("runtime", [0, -1, 301])
async def test_exec_runtime_rejects_out_of_range(
monkeypatch, runtime_parameter, runtime,
) -> None:
spawn = AsyncMock(side_effect=AssertionError("Invalid runtime must not start a process"))
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
tool = ExecTool(max_runtime=301, max_runtime_limit=300)
result = await tool.execute(command="echo ok", **{runtime_parameter: runtime})
assert result.startswith("Error:")
assert "runtime" in result or "timeout" in result
spawn.assert_not_called()
async def test_exec_runtime_aliases_are_mutually_exclusive(monkeypatch) -> None:
spawn = AsyncMock(side_effect=AssertionError("Conflicting runtime arguments must not spawn"))
monkeypatch.setattr(processes, "spawn_process_tree", spawn)
tool = ExecTool()
params = {"command": "echo ok", "max_runtime": 5, "timeout": 5}
result = await tool.execute(**params)
assert result.startswith("Error:")
assert "max_runtime" in result
assert "timeout" in result
spawn.assert_not_called()
def test_exec_config_runtime_defaults_and_timeout_alias() -> None:
cfg = ExecToolConfig()
assert cfg.max_runtime == 3600
assert cfg.max_runtime_limit == 86400
assert cfg.idle_timeout == 300
assert cfg.idle_action == "report"
assert ExecToolConfig(timeout=5).max_runtime == 5
assert ExecToolConfig(timeout=3600).max_runtime == 3600
assert ExecToolConfig(timeout=0).max_runtime == 0
with pytest.raises(ValidationError):
ExecToolConfig(timeout=-1)
def test_exec_config_accepts_bwrap_bind_aliases() -> None:
cfg = ExecToolConfig.model_validate(
{
"sandboxRoBinds": ["/home/user/.local/bin"],
"sandboxRwBinds": ["/home/user/.cache/uv"],
}
)
dumped = cfg.model_dump(by_alias=True)
assert cfg.sandbox_ro_binds == ["/home/user/.local/bin"]
assert cfg.sandbox_rw_binds == ["/home/user/.cache/uv"]
assert dumped["sandboxRoBinds"] == ["/home/user/.local/bin"]
assert dumped["sandboxRwBinds"] == ["/home/user/.cache/uv"]
def test_resolve_timeout_uses_configured_hard_budget() -> None:
assert ExecTool()._resolve_timeout(None) == 3600
assert ExecTool(timeout=5)._resolve_timeout(None) == 5
assert ExecTool(max_runtime=172800, max_runtime_limit=60)._resolve_timeout(None) == 172800
def test_resolve_timeout_respects_configured_limit_without_clamping() -> None:
assert ExecTool()._resolve_timeout(9999) == 9999
tool = ExecTool(max_runtime=60, max_runtime_limit=1200)
assert tool._resolve_timeout(1) == 1
assert tool._resolve_timeout(1200) == 1200
for runtime in (0, -1, 1201):
with pytest.raises(ValueError):
tool._resolve_timeout(runtime)
@pytest.mark.parametrize("limit", [60, 1200, 86400])
@pytest.mark.parametrize("runtime_parameter", ["timeout", "max_runtime"])
def test_exec_runtime_schema_matches_configured_limit(limit, runtime_parameter) -> None:
tool = ExecTool(max_runtime=limit + 1, max_runtime_limit=limit)
runtime_schema = tool.parameters["properties"][runtime_parameter]
assert runtime_schema["minimum"] == 1
assert runtime_schema["maximum"] == limit
assert tool.validate_params({"command": "echo ok"}) == []
for runtime in (1, limit):
assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime}) == []
for runtime in (0, -1, limit + 1):
assert tool.validate_params({"command": "echo ok", runtime_parameter: runtime})
runtime_schema["maximum"] = 1
assert tool.parameters["properties"][runtime_parameter]["maximum"] == limit
assert ExecTool().parameters["properties"][runtime_parameter]["maximum"] == 86400
@pytest.mark.parametrize("raw_type", ["null", ["null"]])
@pytest.mark.parametrize("value", ["", 0, False, [], {}])
def test_null_only_schema_rejects_non_null_values(raw_type, value) -> None:
schema = {"type": raw_type}
assert Schema.validate_json_schema_value(value, schema, "value") == [
f"value: {value!r} is not of type 'null'"
]
assert Schema.validate_json_schema_value(None, schema) == []
@pytest.mark.parametrize(
"schema",
[
{"type": ["string", "null"], "enum": ["fast"]},
{"type": ["integer", "null"], "enum": [1]},
{"type": ["string", "integer", "null"], "enum": ["fast", 1]},
],
)
def test_nullable_schema_still_enforces_enum(schema) -> None:
assert Schema.validate_json_schema_value(None, schema, "mode") == [
f"mode: None is not one of {schema['enum']}"
]
assert Schema.validate_json_schema_value(None, {**schema, "enum": [None]}) == []
for value in schema["enum"]:
assert Schema.validate_json_schema_value(value, schema) == []
def test_nullable_string_schema_enforces_enum() -> None:
assert StringSchema(nullable=True, enum=["fast"]).validate_value(None)
assert StringSchema(nullable=True, enum=["fast", None]).validate_value(None) == []
def test_validate_nullable_param_accepts_string() -> None:
tool = SchemaTestTool(
{
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
}
)
errors = tool.validate_params({"name": "hello"})
assert errors == []
def test_validate_nullable_param_accepts_none() -> None:
tool = SchemaTestTool(
{
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
}
)
errors = tool.validate_params({"name": None})
assert errors == []
@pytest.mark.parametrize("command", [
"cat ~unknown/file.txt",
"cat --config=~unknown/file.txt",
"cat <~unknown/file.txt",
"cat ~/file.txt",
])
def test_exec_guard_rejects_unresolvable_home_path(tmp_path, monkeypatch, command) -> None:
original = Path.expanduser
def expanduser(path):
if str(path).startswith("~"):
raise RuntimeError("Could not determine home directory.")
return original(path)
monkeypatch.setattr(Path, "expanduser", expanduser)
tool = ExecTool(restrict_to_workspace=True)
error = tool._guard_command(command, str(tmp_path))
assert error is not None
assert error.startswith("Error: Command blocked by safety guard (path outside working dir)")
def test_exec_guard_allows_resolved_home_inside_workspace(tmp_path, monkeypatch) -> None:
original = Path.expanduser
def expanduser(path):
if str(path).startswith("~"):
return tmp_path / "file.txt"
return original(path)
monkeypatch.setattr(Path, "expanduser", expanduser)
tool = ExecTool(restrict_to_workspace=True)
assert tool._guard_command("cat ~/file.txt", str(tmp_path)) is None