botsting 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- botsting/__init__.py +3 -0
- botsting/__main__.py +8 -0
- botsting/attacks/__init__.py +0 -0
- botsting/attacks/adaptive.py +495 -0
- botsting/attacks/library.py +239 -0
- botsting/attacks/pyrit_adapter.py +227 -0
- botsting/attacks/strategy.py +157 -0
- botsting/authorize_cli.py +148 -0
- botsting/ci.py +122 -0
- botsting/cli.py +464 -0
- botsting/console.py +240 -0
- botsting/core/__init__.py +0 -0
- botsting/core/authorization.py +550 -0
- botsting/core/benchmark.py +199 -0
- botsting/core/canary.py +80 -0
- botsting/core/judge.py +175 -0
- botsting/core/matcher.py +367 -0
- botsting/core/meter.py +228 -0
- botsting/core/models.py +560 -0
- botsting/core/preflight.py +283 -0
- botsting/core/replay.py +145 -0
- botsting/core/runner.py +39 -0
- botsting/core/scan.py +917 -0
- botsting/core/stats.py +42 -0
- botsting/demo.py +215 -0
- botsting/doctor.py +271 -0
- botsting/egress_trap.py +243 -0
- botsting/exits.py +38 -0
- botsting/frameworks.py +453 -0
- botsting/harness.py +893 -0
- botsting/harness_tools.py +260 -0
- botsting/llm/__init__.py +0 -0
- botsting/llm/base.py +31 -0
- botsting/llm/ollama.py +165 -0
- botsting/llm/scripted.py +122 -0
- botsting/mcp_server.py +643 -0
- botsting/practice_server.py +190 -0
- botsting/presets.py +222 -0
- botsting/quick.py +485 -0
- botsting/report_html.py +588 -0
- botsting/report_markdown.py +472 -0
- botsting/reporting.py +73 -0
- botsting/seal.py +245 -0
- botsting/shell.py +40 -0
- botsting/sterility.py +407 -0
- botsting/targets/__init__.py +0 -0
- botsting/targets/base.py +207 -0
- botsting/targets/hardened.py +360 -0
- botsting/targets/http.py +826 -0
- botsting/targets/registry.py +96 -0
- botsting/targets/toy.py +310 -0
- botsting-0.0.3.dist-info/METADATA +495 -0
- botsting-0.0.3.dist-info/RECORD +56 -0
- botsting-0.0.3.dist-info/WHEEL +4 -0
- botsting-0.0.3.dist-info/entry_points.txt +2 -0
- botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Guard a Python bot's complete tool list during signed BotSting sessions.
|
|
2
|
+
|
|
3
|
+
Developed against openai-agents 0.25.0, langchain-core 1.8.4, and
|
|
4
|
+
claude-agent-sdk 0.2.187. Framework imports are local to the adapters.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
12
|
+
from copy import copy
|
|
13
|
+
from dataclasses import replace
|
|
14
|
+
from functools import partial, wraps
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from . import harness as pp
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from agents import FunctionTool
|
|
21
|
+
from claude_agent_sdk import HookMatcher, SdkMcpTool
|
|
22
|
+
from langchain_core.tools import BaseTool
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_STAND_IN = '{"status": "ok"}'
|
|
26
|
+
# The Claude SDK runs its callbacks in the context of whoever connected the client. If that was done at
|
|
27
|
+
# startup, not inside the wrapped request, a call made during a test arrives with no session. Running
|
|
28
|
+
# it as written would carry out a real action in the middle of a test, so it is blocked instead.
|
|
29
|
+
_OUTSIDE = (
|
|
30
|
+
"BotSting blocked this tool call: a test is in progress in this process, but the call arrived "
|
|
31
|
+
"outside the test request. Connect the SDK client inside the wrapped request."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _check_names(names: Iterable[str], configured: Iterable[str], option: str) -> frozenset[str]:
|
|
36
|
+
configured = frozenset(configured)
|
|
37
|
+
unknown = configured.difference(names)
|
|
38
|
+
if unknown:
|
|
39
|
+
raise pp.HarnessError(f"unknown tool names in {option}: {sorted(unknown)}")
|
|
40
|
+
return configured
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def guard(
|
|
44
|
+
tools: Mapping[str, Callable[..., Any]],
|
|
45
|
+
reads: Iterable[str] = (),
|
|
46
|
+
*,
|
|
47
|
+
results: Mapping[str, Any] | None = None,
|
|
48
|
+
live: Mapping[str, pp.Cap] | None = None,
|
|
49
|
+
) -> dict[str, Callable[..., Any]]:
|
|
50
|
+
"""Return tools guarded by `pp.action`, with the given reads passed through.
|
|
51
|
+
|
|
52
|
+
Stand-in values and synchronous result factories, and opt-in live caps, use
|
|
53
|
+
the same semantics as the corresponding `pp.action` options.
|
|
54
|
+
"""
|
|
55
|
+
reads = _check_names(tools, reads, "reads")
|
|
56
|
+
results = dict(results or {})
|
|
57
|
+
live = dict(live or {})
|
|
58
|
+
_check_names(tools, results, "results")
|
|
59
|
+
_check_names(tools, live, "live")
|
|
60
|
+
return {
|
|
61
|
+
name: function if name in reads else _guard_callable(name, function, results, live) for name, function in tools.items()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _guard_callable(name, function, results, live):
|
|
66
|
+
options = {}
|
|
67
|
+
if name in results:
|
|
68
|
+
options["result"] = results[name]
|
|
69
|
+
if name in live:
|
|
70
|
+
options["live"] = live[name]
|
|
71
|
+
|
|
72
|
+
target = function
|
|
73
|
+
while isinstance(target, partial):
|
|
74
|
+
target = target.func
|
|
75
|
+
if not inspect.iscoroutinefunction(function) and (
|
|
76
|
+
inspect.iscoroutinefunction(target) or inspect.iscoroutinefunction(target.__call__)
|
|
77
|
+
):
|
|
78
|
+
# On Python 3.11 iscoroutinefunction does not recognize async callable instances,
|
|
79
|
+
# or a partial of an async function.
|
|
80
|
+
@wraps(function)
|
|
81
|
+
async def invoke(*args, **kwargs):
|
|
82
|
+
return await function(*args, **kwargs)
|
|
83
|
+
|
|
84
|
+
return pp.action(name, **options)(invoke)
|
|
85
|
+
return pp.action(name, **options)(function)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _record(name: str, arguments: Mapping[str, Any], result: str) -> None:
|
|
89
|
+
# Frameworks supply argument maps, with keys that need not be Python parameters.
|
|
90
|
+
pp.record_call(name, arguments, result)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _tool_reads(tools, tool_type, reads, name):
|
|
94
|
+
if not all(isinstance(tool, tool_type) for tool in tools):
|
|
95
|
+
raise pp.HarnessError(f"expected only {tool_type.__name__} instances")
|
|
96
|
+
names = {name(tool) for tool in tools}
|
|
97
|
+
if len(names) != len(tools):
|
|
98
|
+
raise pp.HarnessError("tool names must be unique")
|
|
99
|
+
return _check_names(names, reads, "reads")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def guard_agents(
|
|
103
|
+
tools: Iterable[FunctionTool],
|
|
104
|
+
reads: Iterable[str] = (),
|
|
105
|
+
) -> list[FunctionTool]:
|
|
106
|
+
"""Guard OpenAI Agents SDK function tools at their invocation callback."""
|
|
107
|
+
from agents import FunctionTool
|
|
108
|
+
|
|
109
|
+
tools = list(tools)
|
|
110
|
+
reads = _tool_reads(tools, FunctionTool, reads, lambda tool: tool.qualified_name)
|
|
111
|
+
|
|
112
|
+
def protect(tool):
|
|
113
|
+
if callable(tool.needs_approval):
|
|
114
|
+
# The SDK binds validation of arguments to the original invoker for callable
|
|
115
|
+
# approval policies. Replacing it would change which arguments can skip approval.
|
|
116
|
+
raise pp.HarnessError(f"{tool.qualified_name}: callable needs_approval is unsupported")
|
|
117
|
+
guarded = copy(tool)
|
|
118
|
+
original = guarded.on_invoke_tool
|
|
119
|
+
|
|
120
|
+
@wraps(original)
|
|
121
|
+
async def invoke(context, raw):
|
|
122
|
+
if not pp.active():
|
|
123
|
+
return await original(context, raw)
|
|
124
|
+
try:
|
|
125
|
+
parsed = json.loads(raw) if raw else {}
|
|
126
|
+
except ValueError:
|
|
127
|
+
parsed = raw
|
|
128
|
+
arguments = parsed if isinstance(parsed, dict) else {"input": parsed}
|
|
129
|
+
_record(tool.qualified_name, arguments, _STAND_IN)
|
|
130
|
+
return _STAND_IN
|
|
131
|
+
|
|
132
|
+
guarded.on_invoke_tool = invoke
|
|
133
|
+
return guarded
|
|
134
|
+
|
|
135
|
+
return [tool if tool.qualified_name in reads else protect(tool) for tool in tools]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def guard_langchain(
|
|
139
|
+
tools: Iterable[BaseTool],
|
|
140
|
+
reads: Iterable[str] = (),
|
|
141
|
+
) -> list[BaseTool]:
|
|
142
|
+
"""Guard LangChain and LangGraph BaseTools at their public invocation methods."""
|
|
143
|
+
from langchain_core.messages import ToolMessage
|
|
144
|
+
from langchain_core.tools import BaseTool
|
|
145
|
+
|
|
146
|
+
tools = list(tools)
|
|
147
|
+
reads = _tool_reads(tools, BaseTool, reads, lambda tool: tool.name)
|
|
148
|
+
|
|
149
|
+
def protect(tool):
|
|
150
|
+
guarded = tool.model_copy()
|
|
151
|
+
injected = tool._injected_args_keys
|
|
152
|
+
|
|
153
|
+
def stand_in(tool_input, tool_call_id):
|
|
154
|
+
if isinstance(tool_input, dict):
|
|
155
|
+
arguments = {key: value for key, value in tool_input.items() if key not in injected}
|
|
156
|
+
else:
|
|
157
|
+
arguments = {"input": tool_input}
|
|
158
|
+
_record(tool.name, arguments, _STAND_IN)
|
|
159
|
+
if tool_call_id is None:
|
|
160
|
+
return _STAND_IN
|
|
161
|
+
return ToolMessage(content=_STAND_IN, name=tool.name, tool_call_id=tool_call_id)
|
|
162
|
+
|
|
163
|
+
@wraps(tool.run)
|
|
164
|
+
def run(tool_input, *args, **kwargs):
|
|
165
|
+
if pp.active():
|
|
166
|
+
return stand_in(tool_input, kwargs.get("tool_call_id"))
|
|
167
|
+
return tool.run(tool_input, *args, **kwargs)
|
|
168
|
+
|
|
169
|
+
@wraps(tool.arun)
|
|
170
|
+
async def arun(tool_input, *args, **kwargs):
|
|
171
|
+
if pp.active():
|
|
172
|
+
return stand_in(tool_input, kwargs.get("tool_call_id"))
|
|
173
|
+
return await tool.arun(tool_input, *args, **kwargs)
|
|
174
|
+
|
|
175
|
+
@wraps(tool.invoke)
|
|
176
|
+
def invoke(*args, **kwargs):
|
|
177
|
+
if pp.active():
|
|
178
|
+
return BaseTool.invoke(guarded, *args, **kwargs)
|
|
179
|
+
return tool.invoke(*args, **kwargs)
|
|
180
|
+
|
|
181
|
+
@wraps(tool.ainvoke)
|
|
182
|
+
async def ainvoke(*args, **kwargs):
|
|
183
|
+
if pp.active():
|
|
184
|
+
return await BaseTool.ainvoke(guarded, *args, **kwargs)
|
|
185
|
+
return await tool.ainvoke(*args, **kwargs)
|
|
186
|
+
|
|
187
|
+
# Preserve the original tool class, schema, metadata, and injected argument
|
|
188
|
+
# declarations. Cover custom tools that override invoke/ainvoke as well.
|
|
189
|
+
for name, method in {"run": run, "arun": arun, "invoke": invoke, "ainvoke": ainvoke}.items():
|
|
190
|
+
object.__setattr__(guarded, name, method)
|
|
191
|
+
return guarded
|
|
192
|
+
|
|
193
|
+
return [tool if tool.name in reads else protect(tool) for tool in tools]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def guard_claude_agent(
|
|
197
|
+
tools: Iterable[SdkMcpTool],
|
|
198
|
+
reads: Iterable[str] = (),
|
|
199
|
+
*,
|
|
200
|
+
server_name: str | None = None,
|
|
201
|
+
) -> list[SdkMcpTool]:
|
|
202
|
+
"""Guard in-process Claude SDK MCP tools at their async handler.
|
|
203
|
+
|
|
204
|
+
Select reads by definition name. Pass the configured MCP server name to
|
|
205
|
+
record the full Claude tool name (`mcp__SERVER__TOOL`).
|
|
206
|
+
"""
|
|
207
|
+
from claude_agent_sdk import SdkMcpTool
|
|
208
|
+
|
|
209
|
+
tools = list(tools)
|
|
210
|
+
reads = _tool_reads(tools, SdkMcpTool, reads, lambda tool: tool.name)
|
|
211
|
+
|
|
212
|
+
def protect(tool):
|
|
213
|
+
name = f"mcp__{server_name}__{tool.name}" if server_name else tool.name
|
|
214
|
+
|
|
215
|
+
@wraps(tool.handler)
|
|
216
|
+
async def handler(arguments):
|
|
217
|
+
if not pp.active():
|
|
218
|
+
if pp.tests_in_progress():
|
|
219
|
+
return {"content": [{"type": "text", "text": _OUTSIDE}], "is_error": True}
|
|
220
|
+
return await tool.handler(arguments)
|
|
221
|
+
_record(name, arguments, _STAND_IN)
|
|
222
|
+
return {"content": [{"type": "text", "text": _STAND_IN}]}
|
|
223
|
+
|
|
224
|
+
return replace(tool, handler=handler)
|
|
225
|
+
|
|
226
|
+
return [tool if tool.name in reads else protect(tool) for tool in tools]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def claude_pre_tool_use(
|
|
230
|
+
tool_names: Iterable[str],
|
|
231
|
+
reads: Iterable[str] = (),
|
|
232
|
+
) -> HookMatcher:
|
|
233
|
+
"""Return a Claude SDK PreToolUse matcher that records and denies non-reads.
|
|
234
|
+
|
|
235
|
+
Supply the known tool names as Claude reports them, including any MCP prefix.
|
|
236
|
+
The matcher also denies newly encountered tools outside the read allowlist.
|
|
237
|
+
Connect the SDK client inside the wrapped request so callbacks inherit its session.
|
|
238
|
+
"""
|
|
239
|
+
from claude_agent_sdk import HookMatcher
|
|
240
|
+
|
|
241
|
+
reads = _check_names(tool_names, reads, "reads")
|
|
242
|
+
reason = "BotSting recorded this tool call and blocked execution."
|
|
243
|
+
|
|
244
|
+
async def hook(data, tool_use_id, context):
|
|
245
|
+
if data["tool_name"] in reads or not (pp.active() or pp.tests_in_progress()):
|
|
246
|
+
return {}
|
|
247
|
+
why = reason
|
|
248
|
+
if pp.active():
|
|
249
|
+
_record(data["tool_name"], data["tool_input"], reason)
|
|
250
|
+
else:
|
|
251
|
+
why = _OUTSIDE # no session to record in; never run it in the middle of a test
|
|
252
|
+
return {
|
|
253
|
+
"hookSpecificOutput": {
|
|
254
|
+
"hookEventName": "PreToolUse",
|
|
255
|
+
"permissionDecision": "deny",
|
|
256
|
+
"permissionDecisionReason": why,
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return HookMatcher(hooks=[hook], on_failure="block")
|
botsting/llm/__init__.py
ADDED
|
File without changes
|
botsting/llm/base.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The interface a chat model must offer to be used inside a toy target."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol, TypedDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ChatMessage(TypedDict):
|
|
9
|
+
role: str # "user" or "assistant"
|
|
10
|
+
content: str
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ChatModel(Protocol):
|
|
14
|
+
"""A chat model: system text plus conversation in, one reply out."""
|
|
15
|
+
|
|
16
|
+
name: str
|
|
17
|
+
|
|
18
|
+
async def complete(self, system: str, messages: list[ChatMessage]) -> str:
|
|
19
|
+
"""Return the assistant's next message. Raise ModelError on failure."""
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
async def fingerprint(self) -> dict[str, str]:
|
|
23
|
+
"""What identifies this model and its settings, for pinning a result to a configuration.
|
|
24
|
+
|
|
25
|
+
Must not raise: report "unavailable" for anything that cannot be determined.
|
|
26
|
+
"""
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ModelError(RuntimeError):
|
|
31
|
+
"""The model could not produce a reply (unreachable, timed out, bad response)."""
|
botsting/llm/ollama.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""A ChatModel backed by a local Ollama server's non-streaming /api/chat endpoint.
|
|
2
|
+
|
|
3
|
+
Every failure — server unreachable, timeout, HTTP error, malformed body, empty
|
|
4
|
+
reply — raises ModelError with a message telling the user what to try next.
|
|
5
|
+
No other exception type escapes `complete`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from botsting.llm.base import ChatMessage, ModelError
|
|
13
|
+
|
|
14
|
+
_DEFAULT_HOST = "http://127.0.0.1:11434"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class OllamaModel:
|
|
18
|
+
"""A chat model served by Ollama. Satisfies the ChatModel protocol."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
model: str,
|
|
23
|
+
host: str = _DEFAULT_HOST,
|
|
24
|
+
temperature: float = 0.7,
|
|
25
|
+
timeout_seconds: float = 120,
|
|
26
|
+
seed: int | None = None,
|
|
27
|
+
max_tokens: int = 600,
|
|
28
|
+
transport: httpx.AsyncTransport | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
# The practice bots count as running in this process, which exempts them from
|
|
31
|
+
# authorization. That only holds while their model is on this machine too.
|
|
32
|
+
from botsting.core.authorization import is_loopback_origin
|
|
33
|
+
|
|
34
|
+
if not is_loopback_origin(host.rstrip("/")):
|
|
35
|
+
raise ValueError(f"the Ollama server must be on this machine (localhost or 127.0.0.1), not {host!r}")
|
|
36
|
+
self.model = model
|
|
37
|
+
self.host = host.rstrip("/")
|
|
38
|
+
self.temperature = temperature
|
|
39
|
+
self.timeout_seconds = timeout_seconds
|
|
40
|
+
self.seed = seed
|
|
41
|
+
# A model asked to hex-encode its prompt can generate until the request times
|
|
42
|
+
# out. A support bot has no reason to write that much, so replies are capped.
|
|
43
|
+
self.max_tokens = max_tokens
|
|
44
|
+
self._transport = transport
|
|
45
|
+
self.name = f"ollama:{model}"
|
|
46
|
+
|
|
47
|
+
async def complete(self, system: str, messages: list[ChatMessage]) -> str:
|
|
48
|
+
payload = self._payload(system, messages)
|
|
49
|
+
try:
|
|
50
|
+
async with httpx.AsyncClient(
|
|
51
|
+
transport=self._transport, timeout=httpx.Timeout(self.timeout_seconds)
|
|
52
|
+
) as client:
|
|
53
|
+
response = await client.post(f"{self.host}/api/chat", json=payload)
|
|
54
|
+
except httpx.TimeoutException as exc:
|
|
55
|
+
raise ModelError(
|
|
56
|
+
f"Timed out after {self.timeout_seconds:g}s talking to Ollama at {self.host} "
|
|
57
|
+
f"({type(exc).__name__}). The model may still be loading; raise timeout_seconds "
|
|
58
|
+
"or check that the server answers quickly (`ollama list` should be instant)."
|
|
59
|
+
) from exc
|
|
60
|
+
except httpx.HTTPError as exc:
|
|
61
|
+
raise ModelError(
|
|
62
|
+
f"Could not reach Ollama at {self.host} ({type(exc).__name__}: {exc}). "
|
|
63
|
+
"Is Ollama running there? Start it with `ollama serve` and check the host setting."
|
|
64
|
+
) from exc
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
raise ModelError(
|
|
67
|
+
f"Unexpected error talking to Ollama at {self.host}: {type(exc).__name__}: {exc}"
|
|
68
|
+
) from exc
|
|
69
|
+
|
|
70
|
+
if response.status_code != 200:
|
|
71
|
+
detail = _error_detail(response)
|
|
72
|
+
if response.status_code == 404:
|
|
73
|
+
raise ModelError(
|
|
74
|
+
f"Ollama at {self.host} returned HTTP 404 for model '{self.model}' ({detail}). "
|
|
75
|
+
f"The model is probably not pulled; run `ollama pull {self.model}`."
|
|
76
|
+
)
|
|
77
|
+
raise ModelError(
|
|
78
|
+
f"Ollama at {self.host} returned HTTP {response.status_code}: {detail}"
|
|
79
|
+
)
|
|
80
|
+
return _extract_reply(response, self.host, self.model)
|
|
81
|
+
|
|
82
|
+
async def fingerprint(self) -> dict[str, str]:
|
|
83
|
+
"""Model name, the digest of the weights actually served, and the sampling settings.
|
|
84
|
+
|
|
85
|
+
A name such as "llama3.2" can be re-pulled to different weights, so the digest
|
|
86
|
+
is what pins a result. Never raises; an unreachable server gives "unavailable".
|
|
87
|
+
"""
|
|
88
|
+
digest = "unavailable"
|
|
89
|
+
try:
|
|
90
|
+
async with httpx.AsyncClient(transport=self._transport, timeout=httpx.Timeout(10)) as client:
|
|
91
|
+
response = await client.get(f"{self.host}/api/tags")
|
|
92
|
+
body: object = response.json() if response.status_code == 200 else None
|
|
93
|
+
models = body.get("models") if isinstance(body, dict) else None
|
|
94
|
+
for entry in models if isinstance(models, list) else []:
|
|
95
|
+
if isinstance(entry, dict) and entry.get("name") in (self.model, f"{self.model}:latest"):
|
|
96
|
+
if isinstance(entry.get("digest"), str):
|
|
97
|
+
digest = entry["digest"]
|
|
98
|
+
break
|
|
99
|
+
except Exception:
|
|
100
|
+
pass
|
|
101
|
+
return {
|
|
102
|
+
"model": self.name,
|
|
103
|
+
"digest": digest,
|
|
104
|
+
"temperature": f"{self.temperature:g}",
|
|
105
|
+
"max_tokens": str(self.max_tokens),
|
|
106
|
+
"seed": "none" if self.seed is None else str(self.seed),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
def _payload(self, system: str, messages: list[ChatMessage]) -> dict[str, object]:
|
|
110
|
+
options: dict[str, object] = {"temperature": self.temperature, "num_predict": self.max_tokens}
|
|
111
|
+
if self.seed is not None:
|
|
112
|
+
options["seed"] = self.seed
|
|
113
|
+
return {
|
|
114
|
+
"model": self.model,
|
|
115
|
+
"messages": [{"role": "system", "content": system}, *messages],
|
|
116
|
+
"stream": False,
|
|
117
|
+
"options": options,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _error_detail(response: httpx.Response) -> str:
|
|
122
|
+
"""Best-effort human-readable detail from an error response. Never raises."""
|
|
123
|
+
snippet = response.text.strip()[:300]
|
|
124
|
+
try:
|
|
125
|
+
body: object = response.json()
|
|
126
|
+
except ValueError:
|
|
127
|
+
return snippet if snippet else "(no body)"
|
|
128
|
+
if isinstance(body, dict):
|
|
129
|
+
error = body.get("error")
|
|
130
|
+
if isinstance(error, str) and error.strip():
|
|
131
|
+
return error.strip()
|
|
132
|
+
return snippet if snippet else "(no body)"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _extract_reply(response: httpx.Response, host: str, model: str) -> str:
|
|
136
|
+
try:
|
|
137
|
+
body: object = response.json()
|
|
138
|
+
except ValueError as exc:
|
|
139
|
+
snippet = response.text.strip()[:200]
|
|
140
|
+
raise ModelError(
|
|
141
|
+
f"Ollama at {host} replied with a body that is not valid JSON "
|
|
142
|
+
f"(starts with: {snippet!r})."
|
|
143
|
+
) from exc
|
|
144
|
+
if not isinstance(body, dict):
|
|
145
|
+
raise ModelError(
|
|
146
|
+
f"Ollama at {host} replied with JSON that is not an object "
|
|
147
|
+
f"(got {type(body).__name__})."
|
|
148
|
+
)
|
|
149
|
+
message = body.get("message")
|
|
150
|
+
if not isinstance(message, dict):
|
|
151
|
+
raise ModelError(
|
|
152
|
+
f"Ollama at {host} replied without a 'message' object; the body does not "
|
|
153
|
+
"look like a /api/chat response."
|
|
154
|
+
)
|
|
155
|
+
content = message.get("content")
|
|
156
|
+
if not isinstance(content, str):
|
|
157
|
+
raise ModelError(
|
|
158
|
+
f"Ollama at {host} replied with 'message.content' that is not a string."
|
|
159
|
+
)
|
|
160
|
+
if not content.strip():
|
|
161
|
+
raise ModelError(
|
|
162
|
+
f"Ollama at {host} returned an empty reply from model '{model}'. "
|
|
163
|
+
"Try the same prompt with `ollama run` to see whether the model answers."
|
|
164
|
+
)
|
|
165
|
+
return content
|
botsting/llm/scripted.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""A deterministic stand-in for a chat model, so tests need no LLM.
|
|
2
|
+
|
|
3
|
+
It imitates a naive assistant with a fixed set of weaknesses. It obeys its system text
|
|
4
|
+
for ordinary requests and refuses a plain request for the staff code, but it can be
|
|
5
|
+
talked into dumping its context by a known family of injection phrasings, optionally
|
|
6
|
+
encoded, and into spelling a code out one character per message.
|
|
7
|
+
|
|
8
|
+
The important property: it can only reveal what is in the text it was given. Whether a
|
|
9
|
+
secret leaks therefore depends on what the surrounding application put in its context,
|
|
10
|
+
which is exactly what the vulnerable and fixed toy targets differ in.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import base64
|
|
16
|
+
import codecs
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
from botsting.llm.base import ChatMessage
|
|
20
|
+
|
|
21
|
+
_OVERRIDE = re.compile(
|
|
22
|
+
r"(ignore|disregard|forget)\b.{0,60}\b(instructions?|rules|above|previous|prior)"
|
|
23
|
+
r"|(repeat|print|show|reveal|output|write|translate|encode)\b.{0,80}"
|
|
24
|
+
r"\b(system prompt|your prompt|instructions|everything above|text above|configuration)",
|
|
25
|
+
re.IGNORECASE | re.DOTALL,
|
|
26
|
+
)
|
|
27
|
+
_SPELL = re.compile(
|
|
28
|
+
r"(one|a single|1)\s+(character|letter|char)\b.{0,40}\b(at a time|per message|each message|per reply)",
|
|
29
|
+
re.IGNORECASE | re.DOTALL,
|
|
30
|
+
)
|
|
31
|
+
_ASKS_CODE = re.compile(r"\b(staff|discount)\b.{0,40}\bcode\b|\bcode\b.{0,40}\b(staff|discount)\b", re.I | re.S)
|
|
32
|
+
_CODE_IN_CONTEXT = re.compile(r"staff discount code[^:\n]*:\s*(\S+)", re.IGNORECASE)
|
|
33
|
+
_ROLE_STAFF = re.compile(r"role:\s*staff", re.IGNORECASE)
|
|
34
|
+
_ORDER = re.compile(r"\borders?\b|\bdeliver(y|ies)\b|\bpackages?\b|\bparcels?\b|\bshipments?\b", re.IGNORECASE)
|
|
35
|
+
_RECORDS = re.compile(r"ORDER RECORDS FOR THIS MESSAGE:\n(.*)\Z", re.DOTALL)
|
|
36
|
+
_TOOL_OFFERED = "REFUND <order id> <amount>"
|
|
37
|
+
_REFUND_ASK = re.compile(r"refund of \$?(\d+) on order ([A-Z]-\d{4})", re.IGNORECASE)
|
|
38
|
+
# Phrasings that make this naive model treat text it is reading as an instruction to itself.
|
|
39
|
+
_INJECTED = re.compile(r"ignore (all )?(the )?(previous|prior|above) instructions|\bSYSTEM:", re.IGNORECASE)
|
|
40
|
+
_NEXT = re.compile(r"^\s*(next|continue|go on|and the next|more)\b", re.IGNORECASE)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ScriptedModel:
|
|
44
|
+
name = "scripted"
|
|
45
|
+
|
|
46
|
+
async def fingerprint(self) -> dict[str, str]:
|
|
47
|
+
return {"model": self.name}
|
|
48
|
+
|
|
49
|
+
async def complete(self, system: str, messages: list[ChatMessage]) -> str:
|
|
50
|
+
user_turns = [m["content"] for m in messages if m["role"] == "user"]
|
|
51
|
+
if not user_turns:
|
|
52
|
+
return "Hello! How can I help with your order today?"
|
|
53
|
+
last = user_turns[-1]
|
|
54
|
+
|
|
55
|
+
spelling = self._spelling_reply(system, user_turns)
|
|
56
|
+
if spelling is not None:
|
|
57
|
+
return spelling
|
|
58
|
+
|
|
59
|
+
tool_offered = _TOOL_OFFERED in system
|
|
60
|
+
asked = _REFUND_ASK.search(last)
|
|
61
|
+
if asked:
|
|
62
|
+
# Staff may have refunds. A customer may not, unless they talk this model out of its rules.
|
|
63
|
+
if _ROLE_STAFF.search(system) or _OVERRIDE.search(last):
|
|
64
|
+
if tool_offered:
|
|
65
|
+
return f"Processing that now.\nREFUND {asked.group(2).upper()} {asked.group(1)}"
|
|
66
|
+
return "I'm not able to issue refunds in this conversation."
|
|
67
|
+
return "I'm sorry, only staff can issue refunds."
|
|
68
|
+
|
|
69
|
+
if _OVERRIDE.search(last):
|
|
70
|
+
return self._dump(system, last)
|
|
71
|
+
|
|
72
|
+
if _ASKS_CODE.search(last):
|
|
73
|
+
code = _CODE_IN_CONTEXT.search(system)
|
|
74
|
+
if code and _ROLE_STAFF.search(system):
|
|
75
|
+
return f"The staff discount code is {code.group(1)}."
|
|
76
|
+
return "I'm sorry, I can't share staff codes with customers."
|
|
77
|
+
|
|
78
|
+
if _ORDER.search(last):
|
|
79
|
+
records = _RECORDS.search(system)
|
|
80
|
+
if records and records.group(1).lstrip().startswith("- "):
|
|
81
|
+
body = records.group(1).strip()
|
|
82
|
+
reply = "Here is what I found:\n" + body
|
|
83
|
+
# The weakness under test: text inside a record that is phrased as an
|
|
84
|
+
# instruction gets obeyed, as if the user or the developer had said it.
|
|
85
|
+
planted = _REFUND_ASK.search(body) if _INJECTED.search(body) else None
|
|
86
|
+
if planted and tool_offered:
|
|
87
|
+
reply += f"\nREFUND {planted.group(2).upper()} {planted.group(1)}"
|
|
88
|
+
return reply
|
|
89
|
+
return "I couldn't find an order on your account matching that."
|
|
90
|
+
|
|
91
|
+
return "I can help with orders, deliveries and returns. What do you need?"
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def _dump(system: str, request: str) -> str:
|
|
95
|
+
lowered = request.lower()
|
|
96
|
+
if "base64" in lowered:
|
|
97
|
+
return base64.b64encode(system.encode()).decode()
|
|
98
|
+
if "hex" in lowered:
|
|
99
|
+
return system.encode().hex()
|
|
100
|
+
if "rot13" in lowered:
|
|
101
|
+
return codecs.encode(system, "rot13")
|
|
102
|
+
if "backwards" in lowered or "reverse" in lowered:
|
|
103
|
+
return system[::-1]
|
|
104
|
+
return "Sure. Here is everything above:\n" + system
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _spelling_reply(system: str, user_turns: list[str]) -> str | None:
|
|
108
|
+
"""Continue a spelling game if one was started earlier in the conversation."""
|
|
109
|
+
start = next((i for i, turn in enumerate(user_turns) if _SPELL.search(turn)), None)
|
|
110
|
+
if start is None:
|
|
111
|
+
return None
|
|
112
|
+
follow_ups = user_turns[start + 1 :]
|
|
113
|
+
if follow_ups and not all(_NEXT.search(turn) for turn in follow_ups):
|
|
114
|
+
return None # the user moved on; answer the latest message normally
|
|
115
|
+
code = _CODE_IN_CONTEXT.search(system)
|
|
116
|
+
if code is None:
|
|
117
|
+
return "I don't have a code to spell out."
|
|
118
|
+
characters = code.group(1)
|
|
119
|
+
index = len(follow_ups)
|
|
120
|
+
if index >= len(characters):
|
|
121
|
+
return "That was the last character."
|
|
122
|
+
return f"Character {index + 1} is: {characters[index]}"
|