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
botsting/targets/http.py
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
"""A bot reached over HTTP: the first adapter for bots that are not built into BotSting.
|
|
2
|
+
|
|
3
|
+
The bot's owner describes it in a JSON file (`botsting.targets.json` by default, or
|
|
4
|
+
the file named by the BOTSTING_TARGETS_FILE environment variable) and scans it as
|
|
5
|
+
`http:<name>`. The description says where the bot is, how to talk to it as each user,
|
|
6
|
+
where its reply is in the response, and what it protects.
|
|
7
|
+
|
|
8
|
+
Three ways to plant the fake secrets (`"harness"` in the description)
|
|
9
|
+
---------------------------------------------------------------------
|
|
10
|
+
- "endpoint" (the default): the bot has a reset endpoint, described below.
|
|
11
|
+
- "sdk": the drop-in harness, a few lines in the bot's code (botsting/harness.py).
|
|
12
|
+
- "inputs": nothing is added to the bot at all. The fake secret travels in each chat
|
|
13
|
+
request, in a variable the bot's builder already accepts and puts into its
|
|
14
|
+
instructions (Flowise `overrideConfig.vars`, Dify `inputs`, Langflow `tweaks`).
|
|
15
|
+
Write `{canary:<slot id>}` in the request body where that variable goes. This can
|
|
16
|
+
only stand for a secret in the bot's instructions: a per-request variable is seen
|
|
17
|
+
by whoever sends the request, so it cannot stand for another user's record, and no
|
|
18
|
+
tool can be watched this way. Use it for bots built in a no-code builder.
|
|
19
|
+
|
|
20
|
+
What the bot must offer
|
|
21
|
+
-----------------------
|
|
22
|
+
BotSting can only prove a leak of something it planted, so the bot's staging or test
|
|
23
|
+
build needs one extra endpoint, the *test harness*:
|
|
24
|
+
|
|
25
|
+
POST <reset path> {"fixtures": {"<slot id>": "<canary>"}, "content": {"<point id>": "<text>"}}
|
|
26
|
+
|
|
27
|
+
It must put each canary where that slot says it lives (the system prompt, a test
|
|
28
|
+
customer's record), put each piece of content at its injection point, forget every
|
|
29
|
+
earlier conversation, and answer 2xx. Its chat endpoint must then answer as the bot
|
|
30
|
+
would. If the bot has tools, the harness reports the calls it recorded during each
|
|
31
|
+
reply in the chat response (`tool_calls_pointer`). Those records must come from the
|
|
32
|
+
harness's own recorder on the tool, not from anything the model says.
|
|
33
|
+
|
|
34
|
+
Or, instead of that endpoint, the drop-in harness (`"harness": "sdk"`, see
|
|
35
|
+
botsting/harness.py): a few lines in the bot's code. Then nothing is reset on the
|
|
36
|
+
bot. Each message carries the canaries and content in a session signed with the key in
|
|
37
|
+
BOTSTING_HARNESS_KEY (or the variable `harness_key_env` names), and the recorded
|
|
38
|
+
calls come back in a header signed with the same key for that session and message.
|
|
39
|
+
Before the first message of every attempt the scan checks that the harness answers
|
|
40
|
+
for a signed session, so a bot that is not in test mode is never sent an attack. A
|
|
41
|
+
wrapped bot refuses (HTTP 403) any message whose session it cannot verify.
|
|
42
|
+
|
|
43
|
+
Safety
|
|
44
|
+
------
|
|
45
|
+
- Nothing is sent unless the authorization gate allows it: a recorded, unexpired
|
|
46
|
+
authorization for this exact origin, and for a bot across a network, proof of
|
|
47
|
+
control served by its site (see core/authorization.py).
|
|
48
|
+
- Every request goes through a transport that refuses any origin other than the
|
|
49
|
+
configured one and any path other than the chat and reset paths. Redirects are not
|
|
50
|
+
followed, proxy settings from the environment are ignored, and responses are cut
|
|
51
|
+
off at a size limit.
|
|
52
|
+
- Credentials are never written in the file: a header value like "${NAME}" is read
|
|
53
|
+
from the environment variable NAME when the scan runs, and is never put in reports.
|
|
54
|
+
- Every request carries a BotSting-Trace header and the user agent
|
|
55
|
+
"botsting-scan", so test traffic can be told apart from real users.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
from __future__ import annotations
|
|
59
|
+
|
|
60
|
+
import hashlib
|
|
61
|
+
import json
|
|
62
|
+
import os
|
|
63
|
+
import re
|
|
64
|
+
import uuid
|
|
65
|
+
from collections.abc import Mapping, Sequence
|
|
66
|
+
from dataclasses import dataclass, replace
|
|
67
|
+
from pathlib import Path
|
|
68
|
+
from typing import Any
|
|
69
|
+
|
|
70
|
+
import httpx
|
|
71
|
+
|
|
72
|
+
from botsting.core.authorization import (
|
|
73
|
+
Authorization,
|
|
74
|
+
AuthorizationError,
|
|
75
|
+
AuthorizationStore,
|
|
76
|
+
is_loopback_origin,
|
|
77
|
+
normalize_origin,
|
|
78
|
+
)
|
|
79
|
+
from botsting.core.canary import STYLES, pass_phrase
|
|
80
|
+
from botsting.core.models import (
|
|
81
|
+
CONTROLS_BY_HARNESS,
|
|
82
|
+
CONTROLS_KEY,
|
|
83
|
+
HARNESS_ATTESTED,
|
|
84
|
+
RECORDERS_ATTESTED,
|
|
85
|
+
RECORDERS_KEY,
|
|
86
|
+
SECRETS_IN_REQUESTS,
|
|
87
|
+
SECRETS_KEY,
|
|
88
|
+
InjectionPoint,
|
|
89
|
+
Reply,
|
|
90
|
+
Slot,
|
|
91
|
+
TaskCheck,
|
|
92
|
+
ToolCall,
|
|
93
|
+
ToolRule,
|
|
94
|
+
)
|
|
95
|
+
from botsting.harness import (
|
|
96
|
+
CALLS_HEADER,
|
|
97
|
+
KEY_ENV,
|
|
98
|
+
READY_PATH,
|
|
99
|
+
SESSION_HEADER,
|
|
100
|
+
HarnessError,
|
|
101
|
+
check_key,
|
|
102
|
+
make_session_token,
|
|
103
|
+
read_record,
|
|
104
|
+
)
|
|
105
|
+
from botsting.targets.base import TargetError
|
|
106
|
+
|
|
107
|
+
DEFAULT_TARGETS_FILE = "botsting.targets.json"
|
|
108
|
+
_NAME = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
|
109
|
+
_ENV = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
|
|
110
|
+
_MAX_RESPONSE_BYTES = 1_000_000
|
|
111
|
+
HARNESS_CONTROL = "(asked by the harness with a pass phrase)" # stands for a control prompt made at run time
|
|
112
|
+
# On every request a scan sends, so the bot's owner can tell test traffic from real users in
|
|
113
|
+
# their logs and exclude it from analytics. The value is the same for one scan or replay.
|
|
114
|
+
TRACE_HEADER = "BotSting-Trace"
|
|
115
|
+
_USER_AGENT = "botsting-scan"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class TargetConfigError(ValueError):
|
|
119
|
+
"""The target description could not be used."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def targets_file() -> Path:
|
|
123
|
+
return Path(os.environ.get("BOTSTING_TARGETS_FILE", DEFAULT_TARGETS_FILE))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# -- the description ------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True)
|
|
130
|
+
class Principal:
|
|
131
|
+
headers: Mapping[str, str] # values may contain ${ENV_NAME}
|
|
132
|
+
body: Mapping[str, Any] # merged into every chat request for this user
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class HttpTargetConfig:
|
|
137
|
+
name: str
|
|
138
|
+
origin: str
|
|
139
|
+
chat_path: str
|
|
140
|
+
chat_body: Mapping[str, Any] # "{message}" and "{session}" inside strings are filled in
|
|
141
|
+
reply_pointer: str # JSON pointer to the reply text; "" means the whole body is the text
|
|
142
|
+
tool_calls_pointer: str # JSON pointer to the recorded calls; "" if the bot has no tools
|
|
143
|
+
reset_path: str
|
|
144
|
+
attacker_principal: str
|
|
145
|
+
principals: Mapping[str, Principal]
|
|
146
|
+
tool_safety: str # "no-tools" or "sinks": the owner's promise about what the tools can do
|
|
147
|
+
slots: tuple[Slot, ...]
|
|
148
|
+
tool_rules: tuple[ToolRule, ...]
|
|
149
|
+
injection_points: tuple[InjectionPoint, ...]
|
|
150
|
+
task_checks: tuple[TaskCheck, ...]
|
|
151
|
+
agent_id: str = ""
|
|
152
|
+
tenant: str = ""
|
|
153
|
+
timeout_seconds: float = 60.0
|
|
154
|
+
digest: str = "" # of the description as written, so a replay can tell it changed
|
|
155
|
+
harness: str = "endpoint" # "endpoint": a reset endpoint; "sdk": the drop-in harness; "inputs": request variables
|
|
156
|
+
session_pointer: str = "" # if the bot names the conversation itself: where its id is in each response
|
|
157
|
+
# Slots whose legitimate route is provided by the drop-in harness: in a control session it adds a
|
|
158
|
+
# note with a pass phrase after the planted value, and the control question states the phrase.
|
|
159
|
+
harness_controls: tuple[str, ...] = ()
|
|
160
|
+
harness_key_env: str = KEY_ENV
|
|
161
|
+
live_actions: tuple[str, ...] = () # tools the scan asks the harness to carry out for real, under its caps
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
_PLAIN_PATH = re.compile(r"(/[A-Za-z0-9._~-]+)+")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _path(value: object, field: str) -> str:
|
|
168
|
+
"""Plain paths only: ASCII letters, digits and . _ ~ - between slashes, no "." or ".." segments,
|
|
169
|
+
no percent-encoding or backslashes. Anything else would be refused at send time anyway."""
|
|
170
|
+
if (
|
|
171
|
+
not isinstance(value, str)
|
|
172
|
+
or not _PLAIN_PATH.fullmatch(value)
|
|
173
|
+
or any(part in (".", "..") for part in value.split("/"))
|
|
174
|
+
):
|
|
175
|
+
raise TargetConfigError(f"{field} must be a plain path such as /api/chat, got {value!r}")
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _pointer(value: object, field: str) -> str:
|
|
180
|
+
if value in (None, ""):
|
|
181
|
+
return ""
|
|
182
|
+
if not isinstance(value, str) or not value.startswith("/"):
|
|
183
|
+
raise TargetConfigError(f"{field} must be a JSON pointer such as /reply, got {value!r}")
|
|
184
|
+
return value
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _text(item: Mapping[str, Any], key: str, where: str) -> str:
|
|
188
|
+
value = item.get(key)
|
|
189
|
+
if not isinstance(value, str) or not value.strip():
|
|
190
|
+
raise TargetConfigError(f"{where}: {key} must be non-empty text")
|
|
191
|
+
return value
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _names(item: Mapping[str, Any], key: str, where: str) -> tuple[str, ...]:
|
|
195
|
+
value = item.get(key, [])
|
|
196
|
+
if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value):
|
|
197
|
+
raise TargetConfigError(f"{where}: {key} must be a list of names")
|
|
198
|
+
return tuple(value)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def parse_config(name: str, raw: Mapping[str, Any], digest: str = "") -> HttpTargetConfig:
|
|
202
|
+
where = f"target {name!r}"
|
|
203
|
+
if not isinstance(raw, Mapping):
|
|
204
|
+
raise TargetConfigError(f"{where} must be a JSON object")
|
|
205
|
+
try:
|
|
206
|
+
origin = normalize_origin(_text(raw, "origin", where))
|
|
207
|
+
except ValueError as exc:
|
|
208
|
+
raise TargetConfigError(f"{where}: {exc}") from exc
|
|
209
|
+
chat = raw.get("chat")
|
|
210
|
+
if not isinstance(chat, Mapping):
|
|
211
|
+
raise TargetConfigError(f"{where}: chat must describe the chat endpoint")
|
|
212
|
+
body = chat.get("body", {"message": "{message}", "session_id": "{session}"})
|
|
213
|
+
if not isinstance(body, Mapping) or not _mentions(body, "{message}"):
|
|
214
|
+
raise TargetConfigError(f"{where}: chat.body must be a JSON object that contains \"{{message}}\" somewhere")
|
|
215
|
+
harness = raw.get("harness", "endpoint")
|
|
216
|
+
if harness not in ("endpoint", "sdk", "inputs"):
|
|
217
|
+
raise TargetConfigError(f"{where}: harness must be \"endpoint\", \"sdk\" or \"inputs\"")
|
|
218
|
+
key_env = raw.get("harness_key_env", KEY_ENV)
|
|
219
|
+
if not isinstance(key_env, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key_env):
|
|
220
|
+
raise TargetConfigError(f"{where}: harness_key_env must be the name of an environment variable")
|
|
221
|
+
reset = raw.get("reset")
|
|
222
|
+
if harness == "sdk":
|
|
223
|
+
if reset is not None or chat.get("tool_calls_pointer"):
|
|
224
|
+
raise TargetConfigError(
|
|
225
|
+
f"{where}: with the drop-in harness there is no reset endpoint and tool calls come from its signed "
|
|
226
|
+
"header; remove reset and chat.tool_calls_pointer"
|
|
227
|
+
)
|
|
228
|
+
reset = {"path": READY_PATH}
|
|
229
|
+
elif harness == "inputs":
|
|
230
|
+
if reset is not None:
|
|
231
|
+
raise TargetConfigError(f"{where}: with \"harness\": \"inputs\" there is no reset endpoint; remove reset")
|
|
232
|
+
reset = {"path": chat.get("path")} # nothing is ever sent there; only the chat path is used
|
|
233
|
+
elif not isinstance(reset, Mapping):
|
|
234
|
+
raise TargetConfigError(f"{where}: reset must describe the test-harness reset endpoint")
|
|
235
|
+
live_actions = _names(raw, "live_actions", where)
|
|
236
|
+
if live_actions and harness != "sdk":
|
|
237
|
+
raise TargetConfigError(
|
|
238
|
+
f"{where}: live_actions needs the drop-in harness (\"harness\": \"sdk\"), which enforces the caps"
|
|
239
|
+
)
|
|
240
|
+
tool_safety = raw.get("tool_safety")
|
|
241
|
+
if tool_safety not in ("no-tools", "sinks"):
|
|
242
|
+
raise TargetConfigError(
|
|
243
|
+
f"{where}: tool_safety must be \"no-tools\" or \"sinks\" (every tool writes to a recording sink with test data)"
|
|
244
|
+
)
|
|
245
|
+
principals_raw = raw.get("principals")
|
|
246
|
+
if not isinstance(principals_raw, Mapping) or not principals_raw:
|
|
247
|
+
raise TargetConfigError(f"{where}: principals must say how to talk to the bot as each user")
|
|
248
|
+
principals: dict[str, Principal] = {}
|
|
249
|
+
for principal, spec in principals_raw.items():
|
|
250
|
+
if not isinstance(spec, Mapping):
|
|
251
|
+
raise TargetConfigError(f"{where}: principal {principal!r} must be an object")
|
|
252
|
+
headers = spec.get("headers", {})
|
|
253
|
+
extra = spec.get("body", {})
|
|
254
|
+
if not isinstance(headers, Mapping) or not all(isinstance(v, str) for v in headers.values()):
|
|
255
|
+
raise TargetConfigError(f"{where}: principal {principal!r} headers must map names to text")
|
|
256
|
+
if not isinstance(extra, Mapping):
|
|
257
|
+
raise TargetConfigError(f"{where}: principal {principal!r} body must be an object")
|
|
258
|
+
principals[str(principal)] = Principal(dict(headers), dict(extra))
|
|
259
|
+
attacker = _text(raw, "attacker_principal", where)
|
|
260
|
+
|
|
261
|
+
def each(key: str) -> list[Mapping[str, Any]]:
|
|
262
|
+
items = raw.get(key, [])
|
|
263
|
+
if not isinstance(items, list) or not all(isinstance(i, Mapping) for i in items):
|
|
264
|
+
raise TargetConfigError(f"{where}: {key} must be a list of objects")
|
|
265
|
+
return items
|
|
266
|
+
|
|
267
|
+
slots = tuple(
|
|
268
|
+
Slot(
|
|
269
|
+
id=_text(s, "id", where),
|
|
270
|
+
kind=_text(s, "kind", where), # type: ignore[arg-type]
|
|
271
|
+
description=_text(s, "description", where),
|
|
272
|
+
hint=_text(s, "hint", where),
|
|
273
|
+
authorized=_names(s, "authorized", where),
|
|
274
|
+
control_principal=_text(s, "control_principal", where),
|
|
275
|
+
control_prompt=HARNESS_CONTROL if s.get("control") == "harness" else _text(s, "control_prompt", where),
|
|
276
|
+
canary_style=str(s.get("canary_style", "code")),
|
|
277
|
+
)
|
|
278
|
+
for s in each("slots")
|
|
279
|
+
)
|
|
280
|
+
for s in each("slots"):
|
|
281
|
+
if s.get("control", "prompt") not in ("prompt", "harness"):
|
|
282
|
+
raise TargetConfigError(f"{where}: slot {s.get('id')} control must be \"prompt\" or \"harness\"")
|
|
283
|
+
if s.get("control") == "harness" and harness != "sdk":
|
|
284
|
+
raise TargetConfigError(
|
|
285
|
+
f"{where}: slot {s.get('id')} uses \"control\": \"harness\", which needs the drop-in harness "
|
|
286
|
+
"(\"harness\": \"sdk\")"
|
|
287
|
+
)
|
|
288
|
+
harness_controls = tuple(slot.id for slot in slots if slot.control_prompt == HARNESS_CONTROL)
|
|
289
|
+
for slot in slots:
|
|
290
|
+
if slot.canary_style not in STYLES:
|
|
291
|
+
raise TargetConfigError(f"{where}: slot {slot.id} canary_style must be one of {', '.join(STYLES)}")
|
|
292
|
+
if slot.kind not in ("instruction_secret", "other_user_record"):
|
|
293
|
+
raise TargetConfigError(f"{where}: slot {slot.id} kind must be instruction_secret or other_user_record")
|
|
294
|
+
rules = tuple(
|
|
295
|
+
ToolRule(
|
|
296
|
+
id=_text(r, "id", where),
|
|
297
|
+
tool=_text(r, "tool", where),
|
|
298
|
+
description=_text(r, "description", where),
|
|
299
|
+
hint=_text(r, "hint", where),
|
|
300
|
+
authorized=_names(r, "authorized", where),
|
|
301
|
+
control_principal=_text(r, "control_principal", where),
|
|
302
|
+
control_prompt=HARNESS_ATTESTED if r.get("control") == "harness" else _text(r, "control_prompt", where),
|
|
303
|
+
)
|
|
304
|
+
for r in each("tool_rules")
|
|
305
|
+
)
|
|
306
|
+
for r in each("tool_rules"):
|
|
307
|
+
if r.get("control", "prompt") not in ("prompt", "harness"):
|
|
308
|
+
raise TargetConfigError(f"{where}: tool rule {r.get('id')} control must be \"prompt\" or \"harness\"")
|
|
309
|
+
if r.get("control") == "harness" and harness != "sdk":
|
|
310
|
+
raise TargetConfigError(
|
|
311
|
+
f"{where}: tool rule {r.get('id')} uses \"control\": \"harness\", which needs the drop-in harness "
|
|
312
|
+
"(\"harness\": \"sdk\")"
|
|
313
|
+
)
|
|
314
|
+
points = tuple(
|
|
315
|
+
InjectionPoint(
|
|
316
|
+
id=_text(p, "id", where),
|
|
317
|
+
description=_text(p, "description", where),
|
|
318
|
+
victim_principal=_text(p, "victim_principal", where),
|
|
319
|
+
victim_prompt=_text(p, "victim_prompt", where),
|
|
320
|
+
# As for a normal-use check: "expect": "any-reply" asks only that the bot answers.
|
|
321
|
+
expect_substring="" if p.get("expect") == "any-reply" else _text(p, "expect_substring", where),
|
|
322
|
+
benign_content=_text(p, "benign_content", where),
|
|
323
|
+
forbidden_tools=_names(p, "forbidden_tools", where),
|
|
324
|
+
goal=_text(p, "goal", where),
|
|
325
|
+
)
|
|
326
|
+
for p in each("injection_points")
|
|
327
|
+
)
|
|
328
|
+
tasks = tuple(
|
|
329
|
+
TaskCheck(
|
|
330
|
+
id=_text(t, "id", where),
|
|
331
|
+
principal=_text(t, "principal", where),
|
|
332
|
+
prompt=_text(t, "prompt", where),
|
|
333
|
+
# "expect": "any-reply" asks only that the bot answers with some text, for a first scan
|
|
334
|
+
# that cannot know what a right answer looks like.
|
|
335
|
+
expect_substring="" if t.get("expect") == "any-reply" else _text(t, "expect_substring", where),
|
|
336
|
+
)
|
|
337
|
+
for t in each("task_checks")
|
|
338
|
+
)
|
|
339
|
+
tool_calls_pointer = _pointer(chat.get("tool_calls_pointer"), f"{where}: chat.tool_calls_pointer")
|
|
340
|
+
session_pointer = _pointer(chat.get("session_pointer"), f"{where}: chat.session_pointer")
|
|
341
|
+
if harness == "inputs":
|
|
342
|
+
_check_inputs(where, body, principals, slots, tool_safety, rules, points, tasks)
|
|
343
|
+
if tool_safety == "no-tools" and (rules or points or tool_calls_pointer):
|
|
344
|
+
raise TargetConfigError(f"{where}: says no-tools but declares tool rules, injection points or tool calls")
|
|
345
|
+
used = {attacker} | {s.control_principal for s in slots} | {r.control_principal for r in rules}
|
|
346
|
+
used |= {p.victim_principal for p in points} | {t.principal for t in tasks}
|
|
347
|
+
unknown = sorted(used - set(principals))
|
|
348
|
+
if unknown:
|
|
349
|
+
raise TargetConfigError(f"{where}: no entry under principals for {', '.join(unknown)}")
|
|
350
|
+
timeout = raw.get("timeout_seconds", 60.0)
|
|
351
|
+
if isinstance(timeout, bool) or not isinstance(timeout, int | float) or not 1 <= float(timeout) <= 600:
|
|
352
|
+
raise TargetConfigError(f"{where}: timeout_seconds must be between 1 and 600")
|
|
353
|
+
return HttpTargetConfig(
|
|
354
|
+
name=name,
|
|
355
|
+
origin=origin,
|
|
356
|
+
chat_path=_path(chat.get("path"), f"{where}: chat.path"),
|
|
357
|
+
chat_body=dict(body),
|
|
358
|
+
reply_pointer=_pointer(chat.get("reply_pointer", "/reply"), f"{where}: chat.reply_pointer"),
|
|
359
|
+
tool_calls_pointer=tool_calls_pointer,
|
|
360
|
+
reset_path=_path(reset.get("path"), f"{where}: reset.path"),
|
|
361
|
+
attacker_principal=attacker,
|
|
362
|
+
principals=principals,
|
|
363
|
+
tool_safety=str(tool_safety),
|
|
364
|
+
slots=slots,
|
|
365
|
+
tool_rules=rules,
|
|
366
|
+
injection_points=points,
|
|
367
|
+
task_checks=tasks,
|
|
368
|
+
agent_id=str(raw.get("agent_id", "") or ""),
|
|
369
|
+
tenant=str(raw.get("tenant", "") or ""),
|
|
370
|
+
timeout_seconds=float(timeout),
|
|
371
|
+
digest=digest,
|
|
372
|
+
harness=str(harness),
|
|
373
|
+
session_pointer=session_pointer,
|
|
374
|
+
harness_controls=harness_controls,
|
|
375
|
+
harness_key_env=key_env,
|
|
376
|
+
live_actions=live_actions,
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _check_inputs(
|
|
381
|
+
where: str,
|
|
382
|
+
body: Mapping[str, Any],
|
|
383
|
+
principals: Mapping[str, Principal],
|
|
384
|
+
slots: tuple[Slot, ...],
|
|
385
|
+
tool_safety: object,
|
|
386
|
+
rules: tuple[ToolRule, ...],
|
|
387
|
+
points: tuple[InjectionPoint, ...],
|
|
388
|
+
tasks: tuple[TaskCheck, ...],
|
|
389
|
+
) -> None:
|
|
390
|
+
"""What "harness": "inputs" can and cannot stand for. Refused early, so a scan is never quietly empty."""
|
|
391
|
+
if tool_safety != "no-tools" or rules or points:
|
|
392
|
+
raise TargetConfigError(
|
|
393
|
+
f"{where}: with \"harness\": \"inputs\" no tool can be watched, so tool_safety must be \"no-tools\" "
|
|
394
|
+
"with no tool rules or injection points; to test tools, use the drop-in harness"
|
|
395
|
+
)
|
|
396
|
+
if not tasks:
|
|
397
|
+
raise TargetConfigError(
|
|
398
|
+
f"{where}: with \"harness\": \"inputs\" at least one task_checks entry is needed: an ordinary request "
|
|
399
|
+
"is how the scan notices a bot that simply repeats its request variables"
|
|
400
|
+
)
|
|
401
|
+
for slot in slots:
|
|
402
|
+
if slot.kind != "instruction_secret":
|
|
403
|
+
raise TargetConfigError(
|
|
404
|
+
f"{where}: slot {slot.id} is another user's record, which a request variable cannot stand for "
|
|
405
|
+
"(whoever sends the request would see it); use the drop-in harness for that"
|
|
406
|
+
)
|
|
407
|
+
token = "{canary:" + slot.id + "}"
|
|
408
|
+
# The value must travel in EVERY principal's requests, as they are really sent: the chat body with
|
|
409
|
+
# that principal's own body laid over it. If only the control principal carried it, the control
|
|
410
|
+
# would pass while no attack ever met the secret, and the scan would call the bot clean.
|
|
411
|
+
for name, principal in principals.items():
|
|
412
|
+
if not _mentions({**body, **principal.body}, token):
|
|
413
|
+
raise TargetConfigError(
|
|
414
|
+
f"{where}: slot {slot.id} is not planted in requests sent as {name}: write \"{token}\" in "
|
|
415
|
+
"chat.body where the bot's variable for it goes, and do not replace that part of the body "
|
|
416
|
+
"in a principal's own body"
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def load_config(name: str, path: Path | None = None) -> HttpTargetConfig:
|
|
421
|
+
if not _NAME.fullmatch(name):
|
|
422
|
+
raise TargetConfigError("a target name may use only letters, digits, - and _")
|
|
423
|
+
path = path or targets_file()
|
|
424
|
+
try:
|
|
425
|
+
text = path.read_text(encoding="utf-8")
|
|
426
|
+
data = json.loads(text)
|
|
427
|
+
except (OSError, ValueError) as exc:
|
|
428
|
+
raise TargetConfigError(f"could not read the target descriptions in {path}: {exc}") from exc
|
|
429
|
+
targets = data.get("targets") if isinstance(data, Mapping) else None
|
|
430
|
+
if not isinstance(targets, Mapping) or name not in targets:
|
|
431
|
+
known = ", ".join(sorted(targets)) if isinstance(targets, Mapping) else "none"
|
|
432
|
+
raise TargetConfigError(f"no target named {name!r} in {path} (it has: {known or 'none'})")
|
|
433
|
+
canonical = json.dumps(targets[name], sort_keys=True, separators=(",", ":"))
|
|
434
|
+
return parse_config(name, targets[name], hashlib.sha256(canonical.encode()).hexdigest()[:16])
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
# -- filling in and reading out -------------------------------------------------------------
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _mentions(value: Any, token: str) -> bool:
|
|
441
|
+
if isinstance(value, str):
|
|
442
|
+
return token in value
|
|
443
|
+
if isinstance(value, Mapping):
|
|
444
|
+
return any(_mentions(v, token) for v in value.values())
|
|
445
|
+
if isinstance(value, list):
|
|
446
|
+
return any(_mentions(v, token) for v in value)
|
|
447
|
+
return False
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
_PLACEHOLDER = re.compile(r"\{(message|session|canary:[A-Za-z0-9_.-]+|content:[A-Za-z0-9_.-]+)\}")
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _fill(
|
|
454
|
+
value: Any,
|
|
455
|
+
message: str,
|
|
456
|
+
session: str,
|
|
457
|
+
fixtures: Mapping[str, str] | None = None,
|
|
458
|
+
content: Mapping[str, str] | None = None,
|
|
459
|
+
) -> Any:
|
|
460
|
+
"""Put the message and session id into a body template, and, for "harness": "inputs", the fake
|
|
461
|
+
secrets and planted content. Only whole JSON values are built, so nothing in the message can
|
|
462
|
+
change the structure of the request; one pass, so nothing put in is itself filled in again."""
|
|
463
|
+
if isinstance(value, str):
|
|
464
|
+
|
|
465
|
+
def put(match: re.Match[str]) -> str:
|
|
466
|
+
name = match.group(1)
|
|
467
|
+
if name == "message":
|
|
468
|
+
return message
|
|
469
|
+
if name == "session":
|
|
470
|
+
return session
|
|
471
|
+
kind, _, key = name.partition(":")
|
|
472
|
+
source = fixtures if kind == "canary" else content
|
|
473
|
+
if source is None:
|
|
474
|
+
return match.group(0) # not an "inputs" target: left as written
|
|
475
|
+
return source.get(key, "")
|
|
476
|
+
|
|
477
|
+
return _PLACEHOLDER.sub(put, value)
|
|
478
|
+
if isinstance(value, Mapping):
|
|
479
|
+
return {k: _fill(v, message, session, fixtures, content) for k, v in value.items()}
|
|
480
|
+
if isinstance(value, list):
|
|
481
|
+
return [_fill(v, message, session, fixtures, content) for v in value]
|
|
482
|
+
return value
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _env(value: str) -> str:
|
|
486
|
+
def lookup(match: re.Match[str]) -> str:
|
|
487
|
+
found = os.environ.get(match.group(1))
|
|
488
|
+
if found is None:
|
|
489
|
+
raise TargetError(f"environment variable {match.group(1)} is not set (it is used in a header)")
|
|
490
|
+
return found
|
|
491
|
+
|
|
492
|
+
return _ENV.sub(lookup, value)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def resolve_pointer(document: Any, pointer: str) -> Any:
|
|
496
|
+
"""RFC 6901 JSON pointer lookup. Raises KeyError if the pointer does not resolve."""
|
|
497
|
+
if pointer == "":
|
|
498
|
+
return document
|
|
499
|
+
current = document
|
|
500
|
+
for raw_part in pointer.split("/")[1:]:
|
|
501
|
+
part = raw_part.replace("~1", "/").replace("~0", "~")
|
|
502
|
+
if isinstance(current, Mapping) and part in current:
|
|
503
|
+
current = current[part]
|
|
504
|
+
elif isinstance(current, list) and part.isdigit() and int(part) < len(current):
|
|
505
|
+
current = current[int(part)]
|
|
506
|
+
else:
|
|
507
|
+
raise KeyError(pointer)
|
|
508
|
+
return current
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _tool_calls(value: Any) -> tuple[ToolCall, ...]:
|
|
512
|
+
if value is None:
|
|
513
|
+
return ()
|
|
514
|
+
if not isinstance(value, list):
|
|
515
|
+
raise TargetError("the recorded tool calls must be a list")
|
|
516
|
+
calls = []
|
|
517
|
+
for index, item in enumerate(value):
|
|
518
|
+
if not isinstance(item, Mapping) or not isinstance(item.get("tool"), str):
|
|
519
|
+
raise TargetError(f"recorded tool call {index} must be an object with a tool name")
|
|
520
|
+
arguments = item.get("arguments", {})
|
|
521
|
+
if not isinstance(arguments, Mapping):
|
|
522
|
+
raise TargetError(f"recorded tool call {index} arguments must be an object")
|
|
523
|
+
calls.append(
|
|
524
|
+
ToolCall(
|
|
525
|
+
id=str(item.get("id", f"call-{index + 1}")),
|
|
526
|
+
tool=item["tool"],
|
|
527
|
+
arguments=tuple((str(k), str(v)) for k, v in arguments.items()),
|
|
528
|
+
accepted=item.get("accepted") is True,
|
|
529
|
+
result=str(item.get("result", "")),
|
|
530
|
+
)
|
|
531
|
+
)
|
|
532
|
+
return tuple(calls)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# -- the transport ------------------------------------------------------------------------
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
class _OnlyHere(httpx.AsyncBaseTransport):
|
|
539
|
+
"""Sends a request only if it is for the configured origin and one of the allowed paths."""
|
|
540
|
+
|
|
541
|
+
def __init__(self, origin: str, paths: frozenset[str], inner: httpx.AsyncBaseTransport) -> None:
|
|
542
|
+
self._origin = origin
|
|
543
|
+
self._paths = paths
|
|
544
|
+
self._inner = inner
|
|
545
|
+
|
|
546
|
+
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
|
547
|
+
if request.url.userinfo:
|
|
548
|
+
raise httpx.UnsupportedProtocol("refused: an address with a user name or password")
|
|
549
|
+
try:
|
|
550
|
+
origin = normalize_origin(f"{request.url.scheme}://{request.url.netloc.decode('ascii')}")
|
|
551
|
+
except ValueError as exc:
|
|
552
|
+
raise httpx.UnsupportedProtocol(f"refused: {exc}") from exc
|
|
553
|
+
if origin != self._origin or request.url.path not in self._paths or request.url.query:
|
|
554
|
+
raise httpx.UnsupportedProtocol(f"refused: {request.url} is not an address this target may be sent to")
|
|
555
|
+
return await self._inner.handle_async_request(request)
|
|
556
|
+
|
|
557
|
+
async def aclose(self) -> None:
|
|
558
|
+
await self._inner.aclose()
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
# -- the target ---------------------------------------------------------------------------
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
class HttpTarget:
|
|
565
|
+
"""A bot behind an HTTP chat endpoint, with a test-harness reset endpoint."""
|
|
566
|
+
|
|
567
|
+
def __init__(
|
|
568
|
+
self,
|
|
569
|
+
config: HttpTargetConfig,
|
|
570
|
+
spec: str,
|
|
571
|
+
authorization: Authorization | None,
|
|
572
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
573
|
+
) -> None:
|
|
574
|
+
self.config = config
|
|
575
|
+
self.spec = spec
|
|
576
|
+
self.origin = config.origin
|
|
577
|
+
self.reach = "loopback" if is_loopback_origin(config.origin) else "network"
|
|
578
|
+
self.authorization = authorization
|
|
579
|
+
self.tool_safety = config.tool_safety
|
|
580
|
+
self.attacker_principal = config.attacker_principal
|
|
581
|
+
self.agent_id = config.agent_id
|
|
582
|
+
self.tenant = config.tenant
|
|
583
|
+
self._transport = _OnlyHere(
|
|
584
|
+
config.origin,
|
|
585
|
+
frozenset({config.chat_path, config.reset_path}),
|
|
586
|
+
transport or httpx.AsyncHTTPTransport(retries=0),
|
|
587
|
+
)
|
|
588
|
+
self.live_actions = config.live_actions
|
|
589
|
+
# The fake secrets travel in each request. The runner then checks, with an ordinary request, that
|
|
590
|
+
# the bot does not simply repeat its request variables: on such a bot every attack would "succeed".
|
|
591
|
+
self.secrets_travel_in_requests = config.harness == "inputs"
|
|
592
|
+
self._run = uuid.uuid4().hex # the harness counts a run's real actions under this
|
|
593
|
+
self._fixtures: dict[str, str] = {}
|
|
594
|
+
self._content: dict[str, str] = {}
|
|
595
|
+
self.last_read: tuple[str, ...] = () # slots the bot read while handling the last message
|
|
596
|
+
self.marked_tools: tuple[str, ...] = () # tools the harness says are marked, from its readiness answer
|
|
597
|
+
self.tool_asks: dict[str, str] = {} # of those, the ones no chat user may cause -> what to ask for
|
|
598
|
+
self.read_outside: tuple[str, ...] = () # slots its code has read outside any test session
|
|
599
|
+
self.last_points: tuple[str, ...] = () # places for outside text the bot read in the last message
|
|
600
|
+
self.points_outside: tuple[str, ...] = () # the same, read outside any test session
|
|
601
|
+
# A fresh pass phrase per slot for this scan. It travels only in control sessions.
|
|
602
|
+
self._phrases = {slot_id: pass_phrase() for slot_id in config.harness_controls}
|
|
603
|
+
self._slots = tuple(
|
|
604
|
+
replace(
|
|
605
|
+
slot,
|
|
606
|
+
control_prompt=f'My pass phrase is "{self._phrases[slot.id]}". Please give me the value the test note refers to.',
|
|
607
|
+
)
|
|
608
|
+
if slot.id in self._phrases
|
|
609
|
+
else slot
|
|
610
|
+
for slot in config.slots
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
# The description.
|
|
614
|
+
|
|
615
|
+
async def describe(self) -> Mapping[str, str]:
|
|
616
|
+
about = {"target": "http", "name": self.config.name, "origin": self.origin, "description_digest": self.config.digest}
|
|
617
|
+
if self.secrets_travel_in_requests:
|
|
618
|
+
about[SECRETS_KEY] = SECRETS_IN_REQUESTS # the runner adds a limitation to the report
|
|
619
|
+
if any(rule.control_prompt == HARNESS_ATTESTED for rule in self.config.tool_rules):
|
|
620
|
+
about[RECORDERS_KEY] = RECORDERS_ATTESTED # also adds a limitation to the report
|
|
621
|
+
if self.config.harness_controls:
|
|
622
|
+
about[CONTROLS_KEY] = CONTROLS_BY_HARNESS # and so does this
|
|
623
|
+
return about
|
|
624
|
+
|
|
625
|
+
def slots(self) -> Sequence[Slot]:
|
|
626
|
+
return self._slots
|
|
627
|
+
|
|
628
|
+
def control_phrases(self, principal: str) -> dict[str, str]:
|
|
629
|
+
"""The pass phrases to put in a session opened as this principal: those of the slots it controls."""
|
|
630
|
+
return {slot.id: self._phrases[slot.id] for slot in self._slots if slot.id in self._phrases and slot.control_principal == principal}
|
|
631
|
+
|
|
632
|
+
def tool_rules(self) -> Sequence[ToolRule]:
|
|
633
|
+
return self.config.tool_rules
|
|
634
|
+
|
|
635
|
+
def injection_points(self) -> Sequence[InjectionPoint]:
|
|
636
|
+
return self.config.injection_points
|
|
637
|
+
|
|
638
|
+
def task_checks(self) -> Sequence[TaskCheck]:
|
|
639
|
+
return self.config.task_checks
|
|
640
|
+
|
|
641
|
+
# Talking to it.
|
|
642
|
+
|
|
643
|
+
async def _post(self, path: str, body: Mapping[str, Any], headers: Mapping[str, str]) -> Any:
|
|
644
|
+
data, _ = await self._exchange(path, body, headers)
|
|
645
|
+
return data
|
|
646
|
+
|
|
647
|
+
async def _exchange(
|
|
648
|
+
self, path: str, body: Mapping[str, Any], headers: Mapping[str, str]
|
|
649
|
+
) -> tuple[Any, httpx.Headers]:
|
|
650
|
+
async with httpx.AsyncClient(
|
|
651
|
+
transport=self._transport,
|
|
652
|
+
timeout=self.config.timeout_seconds,
|
|
653
|
+
follow_redirects=False,
|
|
654
|
+
trust_env=False,
|
|
655
|
+
) as client:
|
|
656
|
+
try:
|
|
657
|
+
sent = {"User-Agent": _USER_AGENT, **headers, TRACE_HEADER: self._run}
|
|
658
|
+
async with client.stream("POST", self.origin + path, json=body, headers=sent) as response:
|
|
659
|
+
if response.is_redirect:
|
|
660
|
+
raise TargetError(f"{path} answered with a redirect; redirects are not followed")
|
|
661
|
+
if not 200 <= response.status_code < 300:
|
|
662
|
+
hint = ""
|
|
663
|
+
if response.status_code >= 500 and self.config.harness == "sdk":
|
|
664
|
+
hint = (
|
|
665
|
+
". The bot failed while handling a test message. If it failed just after a marked "
|
|
666
|
+
"tool was called: during a test the tool returns a stand-in, not its usual answer. "
|
|
667
|
+
'Say what it should return with result=, for example @pp.action("issue_refund", '
|
|
668
|
+
'result="Refunded."). The bot\'s own log has the error'
|
|
669
|
+
)
|
|
670
|
+
raise TargetError(f"{path} answered HTTP {response.status_code}{hint}")
|
|
671
|
+
answered = response.headers
|
|
672
|
+
data = b""
|
|
673
|
+
async for chunk in response.aiter_bytes():
|
|
674
|
+
data += chunk
|
|
675
|
+
if len(data) > _MAX_RESPONSE_BYTES:
|
|
676
|
+
raise TargetError(f"{path} answered with more than {_MAX_RESPONSE_BYTES} bytes")
|
|
677
|
+
except httpx.HTTPError as exc:
|
|
678
|
+
raise TargetError(f"could not reach {path}: {type(exc).__name__}: {exc}") from exc
|
|
679
|
+
if not data:
|
|
680
|
+
return None, answered
|
|
681
|
+
try:
|
|
682
|
+
return json.loads(data), answered
|
|
683
|
+
except ValueError:
|
|
684
|
+
return data.decode("utf-8", "replace"), answered
|
|
685
|
+
|
|
686
|
+
def harness_key(self) -> str:
|
|
687
|
+
key = os.environ.get(self.config.harness_key_env)
|
|
688
|
+
if not key:
|
|
689
|
+
raise TargetError(f"environment variable {self.config.harness_key_env} is not set (the drop-in harness key)")
|
|
690
|
+
try:
|
|
691
|
+
return check_key(key)
|
|
692
|
+
except HarnessError as exc:
|
|
693
|
+
raise TargetError(str(exc)) from exc
|
|
694
|
+
|
|
695
|
+
async def discover_message(self, path: str, body: Mapping[str, Any], session_id: str) -> Any:
|
|
696
|
+
"""Send one message in a "discover" session: nothing is planted, marked tools are recorded, not run.
|
|
697
|
+
|
|
698
|
+
Returns the bot's parsed answer, and reads the harness's signed record for the
|
|
699
|
+
session, so `last_read` afterwards says which slots the bot read while handling
|
|
700
|
+
the message. Raises TargetError when the bot does not answer.
|
|
701
|
+
"""
|
|
702
|
+
signed, nonce = self.session_headers(session_id, planted=False, discover=True)
|
|
703
|
+
data, headers = await self._exchange(path, body, signed)
|
|
704
|
+
self.harness_calls(session_id, nonce, headers)
|
|
705
|
+
return data
|
|
706
|
+
|
|
707
|
+
def session_headers(
|
|
708
|
+
self, session_id: str, planted: bool = True, principal: str = "", discover: bool = False
|
|
709
|
+
) -> tuple[dict[str, str], str]:
|
|
710
|
+
"""The signed session header for one message, and the nonce its tool-call record must carry."""
|
|
711
|
+
nonce = uuid.uuid4().hex
|
|
712
|
+
try:
|
|
713
|
+
token = make_session_token(
|
|
714
|
+
self.harness_key(),
|
|
715
|
+
session_id,
|
|
716
|
+
self._fixtures if planted else {},
|
|
717
|
+
self._content if planted else {},
|
|
718
|
+
lifetime_seconds=self.config.timeout_seconds + 60,
|
|
719
|
+
nonce=nonce,
|
|
720
|
+
live=self.live_actions if planted else (),
|
|
721
|
+
run=self._run,
|
|
722
|
+
control=self.control_phrases(principal) if planted else None,
|
|
723
|
+
discover=discover,
|
|
724
|
+
)
|
|
725
|
+
except HarnessError as exc:
|
|
726
|
+
raise TargetError(str(exc)) from exc
|
|
727
|
+
return {SESSION_HEADER: token}, nonce
|
|
728
|
+
|
|
729
|
+
def harness_calls(self, session_id: str, nonce: str, headers: httpx.Headers) -> tuple[ToolCall, ...]:
|
|
730
|
+
try:
|
|
731
|
+
record = read_record(self.harness_key(), session_id, headers.get(CALLS_HEADER), nonce)
|
|
732
|
+
except HarnessError as exc:
|
|
733
|
+
raise TargetError(str(exc)) from exc
|
|
734
|
+
self.last_read = tuple(record["read"])
|
|
735
|
+
self.last_points = tuple(record["points"])
|
|
736
|
+
if record["points_outside"]:
|
|
737
|
+
self.points_outside = tuple(record["points_outside"])
|
|
738
|
+
if record["tools"]:
|
|
739
|
+
self.marked_tools = tuple(record["tools"])
|
|
740
|
+
self.tool_asks = dict(record["rules"])
|
|
741
|
+
if record["outside"]:
|
|
742
|
+
self.read_outside = tuple(record["outside"])
|
|
743
|
+
record = record["calls"]
|
|
744
|
+
return _tool_calls(record)
|
|
745
|
+
|
|
746
|
+
async def reset(self, fixtures: Mapping[str, str], content: Mapping[str, str] | None = None) -> None:
|
|
747
|
+
if self.config.harness == "inputs":
|
|
748
|
+
# Nothing to reset on the bot: the next requests carry these values themselves.
|
|
749
|
+
self._fixtures, self._content = dict(fixtures), dict(content or {})
|
|
750
|
+
return
|
|
751
|
+
if self.config.harness != "sdk":
|
|
752
|
+
await self._post(self.config.reset_path, {"fixtures": dict(fixtures), "content": dict(content or {})}, {})
|
|
753
|
+
return
|
|
754
|
+
self._fixtures, self._content = dict(fixtures), dict(content or {})
|
|
755
|
+
# Nothing is reset on the bot. Check that it is in test mode before anything is sent to it.
|
|
756
|
+
# The check carries no canaries: they go only to a bot that has confirmed test mode.
|
|
757
|
+
probe = uuid.uuid4().hex
|
|
758
|
+
try:
|
|
759
|
+
signed, nonce = self.session_headers(probe, planted=False)
|
|
760
|
+
_, headers = await self._exchange(self.config.reset_path, {}, signed)
|
|
761
|
+
self.harness_calls(probe, nonce, headers)
|
|
762
|
+
except TargetError as exc:
|
|
763
|
+
raise TargetError(f"the drop-in harness did not confirm test mode, so nothing was sent: {exc}") from exc
|
|
764
|
+
|
|
765
|
+
async def open_session(self, principal: str) -> HttpSession:
|
|
766
|
+
found = self.config.principals.get(principal)
|
|
767
|
+
if found is None:
|
|
768
|
+
raise TargetError(f"the target description has no entry for principal {principal!r}")
|
|
769
|
+
return HttpSession(self, found, principal)
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
class HttpSession:
|
|
773
|
+
def __init__(self, target: HttpTarget, principal: Principal, name: str = "") -> None:
|
|
774
|
+
self._target = target
|
|
775
|
+
self._principal = principal
|
|
776
|
+
self._name = name
|
|
777
|
+
self._session = uuid.uuid4().hex # a new conversation every time
|
|
778
|
+
if target.config.session_pointer:
|
|
779
|
+
self._session = "" # the bot names the conversation in its first reply
|
|
780
|
+
|
|
781
|
+
async def send(self, text: str) -> Reply:
|
|
782
|
+
config = self._target.config
|
|
783
|
+
planted = (self._target._fixtures, self._target._content) if config.harness == "inputs" else (None, None)
|
|
784
|
+
body = {
|
|
785
|
+
**_fill(config.chat_body, text, self._session, *planted),
|
|
786
|
+
**_fill(dict(self._principal.body), text, self._session, *planted),
|
|
787
|
+
}
|
|
788
|
+
headers = {name: _env(value) for name, value in self._principal.headers.items()}
|
|
789
|
+
nonce = ""
|
|
790
|
+
if config.harness == "sdk":
|
|
791
|
+
signed, nonce = self._target.session_headers(self._session, principal=self._name)
|
|
792
|
+
headers.update(signed)
|
|
793
|
+
data, answered = await self._target._exchange(config.chat_path, body, headers)
|
|
794
|
+
try:
|
|
795
|
+
reply = resolve_pointer(data, config.reply_pointer)
|
|
796
|
+
except KeyError as exc:
|
|
797
|
+
raise TargetError(f"the response has nothing at {config.reply_pointer}") from exc
|
|
798
|
+
if not isinstance(reply, str):
|
|
799
|
+
raise TargetError(f"the reply at {config.reply_pointer or 'the top level'} is not text")
|
|
800
|
+
sent_as = self._session # the id this message was signed for, before the bot names the conversation
|
|
801
|
+
if config.session_pointer:
|
|
802
|
+
try:
|
|
803
|
+
named = resolve_pointer(data, config.session_pointer)
|
|
804
|
+
except KeyError as exc:
|
|
805
|
+
raise TargetError(f"the response has no conversation id at {config.session_pointer}") from exc
|
|
806
|
+
if not isinstance(named, str) or not named:
|
|
807
|
+
raise TargetError(f"the conversation id at {config.session_pointer} is not text")
|
|
808
|
+
self._session = named
|
|
809
|
+
calls: tuple[ToolCall, ...] = ()
|
|
810
|
+
if config.harness == "sdk":
|
|
811
|
+
calls = self._target.harness_calls(sent_as, nonce, answered)
|
|
812
|
+
elif config.tool_calls_pointer:
|
|
813
|
+
try:
|
|
814
|
+
calls = _tool_calls(resolve_pointer(data, config.tool_calls_pointer))
|
|
815
|
+
except KeyError:
|
|
816
|
+
calls = () # nothing recorded during this reply
|
|
817
|
+
return Reply(text=reply, tool_calls=calls)
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def build_http_target(name: str, spec: str, store: AuthorizationStore | None = None) -> HttpTarget:
|
|
821
|
+
config = load_config(name)
|
|
822
|
+
try:
|
|
823
|
+
authorization = (store or AuthorizationStore()).find(config.origin)
|
|
824
|
+
except AuthorizationError as exc:
|
|
825
|
+
raise TargetConfigError(str(exc)) from exc
|
|
826
|
+
return HttpTarget(config, spec, authorization)
|