|
| 1 | +"""Approval predicates see the same schema-parsed arguments `execute` gets, |
| 2 | +and schema-invalid arguments fail closed. Subset of upstream |
| 3 | +`tests/unit/approval-gate-regressions.test.ts`. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import dataclasses |
| 9 | +from typing import Any, Dict, List, Tuple |
| 10 | + |
| 11 | +import pytest |
| 12 | +from pydantic import BaseModel, field_validator |
| 13 | + |
| 14 | +from openrouter_agent import tool |
| 15 | +from openrouter_agent.conversation_state import tool_requires_approval |
| 16 | +from openrouter_agent.tool_executor import execute_regular_tool |
| 17 | +from openrouter_agent.tool_types import ParsedToolCall, Tool |
| 18 | + |
| 19 | +CONTEXT: Dict[str, Any] = {"number_of_turns": 1} |
| 20 | + |
| 21 | + |
| 22 | +class Recorder: |
| 23 | + """Counts invocations and records arguments; returns a fixed value. |
| 24 | +
|
| 25 | + A class (not `lambda: calls.append(...) or value`) so the return value is |
| 26 | + explicit and mypy-clean -- see tests/unit/test_tool_execution_once.py. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, value: Any = None) -> None: |
| 30 | + self.value = value |
| 31 | + self.calls: List[Tuple[Any, ...]] = [] |
| 32 | + |
| 33 | + def __call__(self, *args: Any) -> Any: |
| 34 | + self.calls.append(args) |
| 35 | + return self.value |
| 36 | + |
| 37 | + @property |
| 38 | + def count(self) -> int: |
| 39 | + return len(self.calls) |
| 40 | + |
| 41 | + |
| 42 | +def _dumped_first_args(recorder: Recorder) -> List[Any]: |
| 43 | + return [call[0].model_dump() if isinstance(call[0], BaseModel) else call[0] for call in recorder.calls] |
| 44 | + |
| 45 | + |
| 46 | +# --------------------------------------------------------------------------- |
| 47 | +# Bug 1: the approval predicate must see the SAME arguments `execute` gets. |
| 48 | +# --------------------------------------------------------------------------- |
| 49 | + |
| 50 | + |
| 51 | +class DangerousDefaultArgs(BaseModel): |
| 52 | + dangerous: bool = True |
| 53 | + |
| 54 | + |
| 55 | +class AmountArgs(BaseModel): |
| 56 | + amount: int |
| 57 | + |
| 58 | + |
| 59 | +class DestructiveDefaultArgs(BaseModel): |
| 60 | + destructive: bool = True |
| 61 | + |
| 62 | + |
| 63 | +class TargetArgs(BaseModel): |
| 64 | + target: str |
| 65 | + |
| 66 | + |
| 67 | +class OkOutput(BaseModel): |
| 68 | + ok: bool |
| 69 | + |
| 70 | + |
| 71 | +async def test_applies_input_schema_defaults_before_function_require_approval() -> None: |
| 72 | + predicate = Recorder() |
| 73 | + |
| 74 | + def require(params: Any, ctx: Any) -> bool: |
| 75 | + predicate(params, ctx) |
| 76 | + return params["dangerous"] is True |
| 77 | + |
| 78 | + conditional = tool( |
| 79 | + name="conditional_action", |
| 80 | + input_schema=DangerousDefaultArgs, |
| 81 | + require_approval=require, |
| 82 | + execute=lambda params, ctx: {}, |
| 83 | + ) |
| 84 | + |
| 85 | + # The model emitted `{}`; the schema default makes `dangerous` True by the |
| 86 | + # time execute runs, so the predicate must see it True too. |
| 87 | + requires = await tool_requires_approval( |
| 88 | + ParsedToolCall(id="1", name="conditional_action", arguments={}), [conditional], CONTEXT |
| 89 | + ) |
| 90 | + |
| 91 | + # Pydantic models are model_dump()'d for the predicate (conversation_state.py |
| 92 | + # _parse_tool_arguments): the predicate contract is a mapping, as upstream. |
| 93 | + assert [call[0] for call in predicate.calls] == [{"dangerous": True}] |
| 94 | + assert requires is True |
| 95 | + |
| 96 | + |
| 97 | +async def test_applies_input_schema_coercions_before_function_require_approval() -> None: |
| 98 | + predicate = Recorder() |
| 99 | + |
| 100 | + def require(params: Any, ctx: Any) -> bool: |
| 101 | + predicate(params, ctx) |
| 102 | + return bool(params["amount"] > 100) |
| 103 | + |
| 104 | + transfer = tool( |
| 105 | + name="transfer", |
| 106 | + input_schema=AmountArgs, |
| 107 | + require_approval=require, |
| 108 | + execute=lambda params, ctx: {}, |
| 109 | + ) |
| 110 | + |
| 111 | + # String amount is coerced (Pydantic lax mode stands in for z.coerce), so |
| 112 | + # the comparison is numeric, not lexicographic. |
| 113 | + requires = await tool_requires_approval( |
| 114 | + ParsedToolCall(id="2", name="transfer", arguments={"amount": "500"}), [transfer], CONTEXT |
| 115 | + ) |
| 116 | + |
| 117 | + assert [call[0] for call in predicate.calls] == [{"amount": 500}] |
| 118 | + assert requires is True |
| 119 | + |
| 120 | + |
| 121 | +async def test_applies_schema_defaults_for_call_level_checks_without_mutating_call() -> None: |
| 122 | + defaulted = tool( |
| 123 | + name="call_level_defaulted_action", |
| 124 | + input_schema=DestructiveDefaultArgs, |
| 125 | + execute=lambda params, ctx: {}, |
| 126 | + ) |
| 127 | + tool_call = ParsedToolCall(id="call-level-default", name="call_level_defaulted_action", arguments={}) |
| 128 | + call_level_check = Recorder(True) |
| 129 | + |
| 130 | + requires = await tool_requires_approval(tool_call, [defaulted], CONTEXT, call_level_check) |
| 131 | + |
| 132 | + assert call_level_check.calls == [(dataclasses.replace(tool_call, arguments={"destructive": True}), CONTEXT)] |
| 133 | + assert tool_call.arguments == {} |
| 134 | + assert requires is True |
| 135 | + |
| 136 | + |
| 137 | +@pytest.mark.parametrize("decision", [False, True]) |
| 138 | +async def test_honors_call_level_check_when_arguments_fail_schema_validation(decision: bool) -> None: |
| 139 | + strict = tool(name="call_level_invalid_action", input_schema=TargetArgs, execute=lambda params, ctx: {}) |
| 140 | + invalid_call = ParsedToolCall(id=f"call-level-invalid-{decision}", name="call_level_invalid_action", arguments={}) |
| 141 | + call_level_check = Recorder(decision) |
| 142 | + |
| 143 | + assert await tool_requires_approval(invalid_call, [strict], CONTEXT, call_level_check) is decision |
| 144 | + # Parsing failed, so the call-level check receives the raw call. |
| 145 | + assert call_level_check.calls == [(invalid_call, CONTEXT)] |
| 146 | + |
| 147 | + |
| 148 | +async def test_parses_original_wire_arguments_once_for_predicate_and_once_for_execution() -> None: |
| 149 | + transform_calls = {"n": 0} |
| 150 | + |
| 151 | + class TransformedArgs(BaseModel): |
| 152 | + value: str |
| 153 | + |
| 154 | + @field_validator("value") |
| 155 | + @classmethod |
| 156 | + def _suffix(cls, value: str) -> str: |
| 157 | + transform_calls["n"] += 1 |
| 158 | + return f"{value}:{transform_calls['n']}" |
| 159 | + |
| 160 | + predicate = Recorder(False) |
| 161 | + execute = Recorder({}) |
| 162 | + transformed = tool( |
| 163 | + name="transformed_action", |
| 164 | + input_schema=TransformedArgs, |
| 165 | + require_approval=predicate, |
| 166 | + execute=execute, |
| 167 | + ) |
| 168 | + tool_call = ParsedToolCall(id="non-idempotent-transform", name="transformed_action", arguments={"value": "wire"}) |
| 169 | + |
| 170 | + assert await tool_requires_approval(tool_call, [transformed], CONTEXT) is False |
| 171 | + await execute_regular_tool(transformed, tool_call, CONTEXT) |
| 172 | + |
| 173 | + assert predicate.calls == [({"value": "wire:1"}, CONTEXT)] |
| 174 | + assert _dumped_first_args(execute) == [{"value": "wire:2"}] |
| 175 | + assert transform_calls["n"] == 2 |
| 176 | + assert tool_call.arguments == {"value": "wire"} |
| 177 | + |
| 178 | + |
| 179 | +async def test_fails_closed_when_arguments_fail_schema_validation() -> None: |
| 180 | + predicate = Recorder(False) |
| 181 | + strict = tool(name="strict_action", input_schema=TargetArgs, require_approval=predicate, execute=lambda p, c: {}) |
| 182 | + |
| 183 | + requires = await tool_requires_approval( |
| 184 | + ParsedToolCall(id="3", name="strict_action", arguments={}), [strict], CONTEXT |
| 185 | + ) |
| 186 | + |
| 187 | + assert requires is True |
| 188 | + assert predicate.count == 0 |
| 189 | + |
| 190 | + |
| 191 | +async def test_still_fails_closed_when_schema_parses_to_non_object_value() -> None: |
| 192 | + predicate = Recorder(False) |
| 193 | + weird = tool(name="weird_action", input_schema=TargetArgs, require_approval=predicate, execute=lambda p, c: {}) |
| 194 | + # Mirrors upstream swapping in a schema whose parse succeeds with a |
| 195 | + # non-record payload: a callable schema is honored by validate_schema. |
| 196 | + weird["function"]["input_schema"] = lambda value: ["not", "a", "record"] |
| 197 | + |
| 198 | + requires = await tool_requires_approval( |
| 199 | + ParsedToolCall(id="4", name="weird_action", arguments={"target": "x"}), [weird], CONTEXT |
| 200 | + ) |
| 201 | + |
| 202 | + assert requires is True |
| 203 | + assert predicate.count == 0 |
| 204 | + |
| 205 | + |
| 206 | +async def test_still_fails_closed_on_schema_invalid_arguments_for_manual_tools() -> None: |
| 207 | + predicate = Recorder(False) |
| 208 | + # A manual tool: no execute / on_tool_called. The host runs it as-is, so a |
| 209 | + # malformed call must not be waved past the gate. |
| 210 | + manual_tool: Tool = { |
| 211 | + "type": "function", |
| 212 | + "function": {"name": "manual_action", "input_schema": TargetArgs, "require_approval": predicate}, |
| 213 | + } |
| 214 | + |
| 215 | + requires = await tool_requires_approval( |
| 216 | + ParsedToolCall(id="5", name="manual_action", arguments={}), [manual_tool], CONTEXT |
| 217 | + ) |
| 218 | + |
| 219 | + assert requires is True |
| 220 | + assert predicate.count == 0 |
| 221 | + |
| 222 | + |
| 223 | +# --------------------------------------------------------------------------- |
| 224 | +# Approval vs. PreToolUse-mutated arguments. |
| 225 | +# --------------------------------------------------------------------------- |
0 commit comments