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,472 @@
|
|
|
1
|
+
"""Render a ScanReport as the human-readable markdown report.
|
|
2
|
+
|
|
3
|
+
Wording rules (PLAN.md, "What a report may say"):
|
|
4
|
+
|
|
5
|
+
- A report with no verified findings states exactly
|
|
6
|
+
"No verified violations observed under these tested conditions." — never
|
|
7
|
+
that the target is safe, secure, clean, compliant or certified, and never
|
|
8
|
+
that it passed. Those words must not appear anywhere in BotSting-authored text.
|
|
9
|
+
- Lead with the result, then about this test, what was tested, framework
|
|
10
|
+
coverage, slots, task checks, findings, suspected items, contaminated
|
|
11
|
+
attempts, errors, limitations.
|
|
12
|
+
- Empty sections say so in one line, so "none" is distinguishable from
|
|
13
|
+
"not checked".
|
|
14
|
+
- Transcript text comes from attackers and from a model and is rendered
|
|
15
|
+
verbatim in fenced blocks whose fence is longer than any backtick run
|
|
16
|
+
inside the text.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
23
|
+
|
|
24
|
+
from botsting.core.models import Finding, Rate, ScanReport, SlotStatus, ToolCall, Turn
|
|
25
|
+
from botsting.frameworks import (
|
|
26
|
+
FrameworkEntry,
|
|
27
|
+
coverage_rows,
|
|
28
|
+
entries_for,
|
|
29
|
+
group_entries,
|
|
30
|
+
not_covered_sentence,
|
|
31
|
+
objective_kind_for,
|
|
32
|
+
)
|
|
33
|
+
from botsting.shell import replay_command
|
|
34
|
+
|
|
35
|
+
HEADLINE_NO_VERIFIED_VIOLATIONS = "No verified violations observed under these tested conditions."
|
|
36
|
+
|
|
37
|
+
INDEPENDENCE_DESCRIPTIONS: dict[str, str] = {
|
|
38
|
+
"self": "run by the team that built or operates the target",
|
|
39
|
+
"internal": "run by a separate team within the same organization",
|
|
40
|
+
"third-party": "run by an external assessor outside the organization",
|
|
41
|
+
}
|
|
42
|
+
INDEPENDENCE_EXPLANATION = (
|
|
43
|
+
"Independence levels: self means the team that built or operates the target ran the test; "
|
|
44
|
+
"internal means a separate team within the same organization ran it; "
|
|
45
|
+
"third-party means an external assessor outside the organization ran it."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
_EMPTY_SECTION = "None recorded."
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def render_markdown(report: ScanReport, report_path: str | None = None) -> str:
|
|
52
|
+
"""Render the report. `report_path` is the JSON file's path, used in replay commands."""
|
|
53
|
+
lines: list[str] = []
|
|
54
|
+
lines.extend(_headline(report))
|
|
55
|
+
lines.append("")
|
|
56
|
+
lines.append("## About this test")
|
|
57
|
+
lines.extend(_about_this_test(report))
|
|
58
|
+
lines.append("")
|
|
59
|
+
lines.append("## What was tested")
|
|
60
|
+
lines.extend(_what_was_tested(report))
|
|
61
|
+
lines.append("")
|
|
62
|
+
lines.append("## Framework coverage")
|
|
63
|
+
lines.extend(_framework_coverage(report))
|
|
64
|
+
lines.append("")
|
|
65
|
+
lines.append("## What was protected")
|
|
66
|
+
lines.extend(_slots(report))
|
|
67
|
+
lines.append("")
|
|
68
|
+
lines.append("## Normal-task checks")
|
|
69
|
+
lines.extend(_tasks(report))
|
|
70
|
+
lines.append("")
|
|
71
|
+
lines.append("## Verified findings")
|
|
72
|
+
lines.extend(_findings(report, report_path))
|
|
73
|
+
lines.append("")
|
|
74
|
+
lines.append("## Suspected findings")
|
|
75
|
+
lines.extend(_suspected(report))
|
|
76
|
+
lines.append("")
|
|
77
|
+
lines.append("## Contaminated attempts")
|
|
78
|
+
lines.extend(_contaminated(report))
|
|
79
|
+
lines.append("")
|
|
80
|
+
lines.append("## Errors")
|
|
81
|
+
lines.extend(_errors(report))
|
|
82
|
+
lines.append("")
|
|
83
|
+
lines.append("## Limitations")
|
|
84
|
+
lines.extend(_limitations(report))
|
|
85
|
+
text = "\n".join(lines)
|
|
86
|
+
return text if text.endswith("\n") else text + "\n"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _headline(report: ScanReport) -> list[str]:
|
|
90
|
+
lines = _verdict_lines(report)
|
|
91
|
+
gaps = report.not_tested()
|
|
92
|
+
if gaps:
|
|
93
|
+
lines += ["", "Not tested in this scan:", ""]
|
|
94
|
+
lines.extend(f"- {_text(gap)}" for gap in gaps)
|
|
95
|
+
return lines
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _verdict_lines(report: ScanReport) -> list[str]:
|
|
99
|
+
if report.status == "violations_verified":
|
|
100
|
+
count = len(report.findings)
|
|
101
|
+
plural = "" if count == 1 else "s"
|
|
102
|
+
lines = [f"{count} verified violation{plural} found.", "", f"Of these: {report.breakdown()}."]
|
|
103
|
+
if report.inconclusive_reasons:
|
|
104
|
+
# Violations were proven, but a reader must not take the rest as covered.
|
|
105
|
+
lines += ["", "Not everything could be tested:", ""]
|
|
106
|
+
lines.extend(f"- {_text(reason)}" for reason in report.inconclusive_reasons)
|
|
107
|
+
return lines
|
|
108
|
+
if report.status == "no_verified_violations":
|
|
109
|
+
return [HEADLINE_NO_VERIFIED_VIOLATIONS]
|
|
110
|
+
lines = ["The scan could not reach a conclusion.", ""]
|
|
111
|
+
if report.inconclusive_reasons:
|
|
112
|
+
lines.extend(f"- {_text(reason)}" for reason in report.inconclusive_reasons)
|
|
113
|
+
else:
|
|
114
|
+
lines.extend(f"- {reason}" for reason in _inconclusive_reasons(report))
|
|
115
|
+
return lines
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _inconclusive_reasons(report: ScanReport) -> list[str]:
|
|
119
|
+
reasons: list[str] = []
|
|
120
|
+
for slot in report.slots:
|
|
121
|
+
detail = f" ({_code(slot.detail)})" if slot.detail else ""
|
|
122
|
+
if slot.state == "unreachable":
|
|
123
|
+
reasons.append(
|
|
124
|
+
f"Canary slot '{slot.slot_id}' was unreachable{detail}, so nothing "
|
|
125
|
+
"was proven about it."
|
|
126
|
+
)
|
|
127
|
+
elif slot.state == "error":
|
|
128
|
+
reasons.append(f"Canary slot '{slot.slot_id}' could not be checked{detail}.")
|
|
129
|
+
for task in report.tasks:
|
|
130
|
+
if not task.passed:
|
|
131
|
+
detail = f" ({_code(task.detail)})" if task.detail else ""
|
|
132
|
+
reasons.append(
|
|
133
|
+
f"Normal-task check '{task.task_id}' did not work{detail}, so the "
|
|
134
|
+
"target may be broken rather than hardened."
|
|
135
|
+
)
|
|
136
|
+
if report.errors:
|
|
137
|
+
count = len(report.errors)
|
|
138
|
+
plural = "" if count == 1 else "s"
|
|
139
|
+
verb = "was" if count == 1 else "were"
|
|
140
|
+
reasons.append(
|
|
141
|
+
f"{count} error{plural} {verb} recorded during the scan; see Errors below."
|
|
142
|
+
)
|
|
143
|
+
if not reasons:
|
|
144
|
+
reasons.append("The scan was marked inconclusive without a recorded cause; see the sections below.")
|
|
145
|
+
return reasons
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _authorization_markdown(authorization: dict[str, str]) -> str:
|
|
149
|
+
if not authorization:
|
|
150
|
+
return "not recorded (local or in-process target)"
|
|
151
|
+
if "authorized_by" in authorization:
|
|
152
|
+
parts = [f"authorized by {_text(authorization['authorized_by'])}"]
|
|
153
|
+
if authorization.get("origin"):
|
|
154
|
+
parts.append(f"for origin {_code(authorization['origin'])}")
|
|
155
|
+
if authorization.get("environment"):
|
|
156
|
+
parts.append(f"in {_code(authorization['environment'])} environment")
|
|
157
|
+
if authorization.get("scope"):
|
|
158
|
+
parts.append(f"(scope: {_text(authorization['scope'])})")
|
|
159
|
+
if authorization.get("allowed_tools"):
|
|
160
|
+
parts.append(f"Tools that could be exercised: {_text(authorization['allowed_tools'])}.")
|
|
161
|
+
if authorization.get("live_tools"):
|
|
162
|
+
parts.append(f"Tools that could be carried out for real, inside the bot's own caps: {_text(authorization['live_tools'])}.")
|
|
163
|
+
return " ".join(parts)
|
|
164
|
+
if authorization.get("reach") == "in-process":
|
|
165
|
+
return "not required (in-process target)"
|
|
166
|
+
return ", ".join(f"{_text(k)} {_code(v)}" for k, v in sorted(authorization.items()))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _about_this_test(report: ScanReport) -> list[str]:
|
|
170
|
+
tester = _text(report.tester) if report.tester.strip() else "not stated"
|
|
171
|
+
desc = INDEPENDENCE_DESCRIPTIONS.get(report.independence)
|
|
172
|
+
independence = f"{_code(report.independence)} ({desc})" if desc else _code(report.independence)
|
|
173
|
+
return [
|
|
174
|
+
f"- Tool version: {_text(report.tool_version)}",
|
|
175
|
+
f"- Scan dates: {_text(report.started_at)} to {_text(report.finished_at)} (UTC)",
|
|
176
|
+
f"- Authorization: {_authorization_markdown(report.authorization)}",
|
|
177
|
+
f"- Tester: {tester}",
|
|
178
|
+
f"- Independence: {independence}",
|
|
179
|
+
"",
|
|
180
|
+
INDEPENDENCE_EXPLANATION,
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _what_was_tested(report: ScanReport) -> list[str]:
|
|
185
|
+
return [
|
|
186
|
+
f"- Target: {_code(report.target)}",
|
|
187
|
+
f"- Target configuration: {_config(report)}",
|
|
188
|
+
f"- Attacker principal: {_code(report.attacker_principal)}",
|
|
189
|
+
f"- Attacks run: {report.attacks_run}",
|
|
190
|
+
f"- Attempts run: {report.attempts_run}",
|
|
191
|
+
f"- Discovery runs per attack: {report.discovery_runs}",
|
|
192
|
+
f"- Replays per verified finding: {report.reproduction_trials}",
|
|
193
|
+
f"- Spent: {report.messages_sent} messages sent, {report.tool_calls_recorded} tool calls recorded",
|
|
194
|
+
*([f"- Stopped early: {_text(report.stopped_early)}"] if report.stopped_early else []),
|
|
195
|
+
]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _format_entries_inline(entries: tuple[FrameworkEntry, ...]) -> str:
|
|
199
|
+
groups = []
|
|
200
|
+
for label, items in group_entries(entries):
|
|
201
|
+
joined = ", ".join(f"{item.id} {item.title}" for item in items)
|
|
202
|
+
groups.append(f"{label}: {joined}")
|
|
203
|
+
return "; ".join(groups)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _framework_coverage(report: ScanReport) -> list[str]:
|
|
207
|
+
rows = coverage_rows(report)
|
|
208
|
+
if not rows:
|
|
209
|
+
return [_EMPTY_SECTION, "", not_covered_sentence(())]
|
|
210
|
+
lines = [
|
|
211
|
+
"| Objective kind | Framework entries | Attempts judged | Result |",
|
|
212
|
+
"| --- | --- | --- | --- |",
|
|
213
|
+
]
|
|
214
|
+
for row in rows:
|
|
215
|
+
entries_cell = _format_entries_inline(row.entries).replace("|", "\\|")
|
|
216
|
+
lines.append(f"| {row.label} | {entries_cell} | {row.attempts} | {row.result} |")
|
|
217
|
+
lines.append("")
|
|
218
|
+
lines.append(not_covered_sentence([row.kind for row in rows]))
|
|
219
|
+
return lines
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _slots(report: ScanReport) -> list[str]:
|
|
223
|
+
if not report.slots:
|
|
224
|
+
return [_EMPTY_SECTION]
|
|
225
|
+
lines: list[str] = []
|
|
226
|
+
for slot in report.slots:
|
|
227
|
+
detail = f" — {_code(slot.detail)}" if slot.detail else ""
|
|
228
|
+
lines.append(f"- {_code(slot.slot_id)} ({_text(slot.kind)}): {_text(slot.description)}")
|
|
229
|
+
lines.append(f" - State: {slot.state}{detail}")
|
|
230
|
+
if slot.kind == "tool_rule":
|
|
231
|
+
lines.append(f" - Principals whose own request may cause this tool to run: {_principals(slot.authorized)}")
|
|
232
|
+
elif slot.kind == "injection_point":
|
|
233
|
+
lines.append(" - Tested by planting text here and having an ordinary user make an ordinary request")
|
|
234
|
+
else:
|
|
235
|
+
lines.append(f" - Principals authorized to see it: {_principals(slot.authorized)}")
|
|
236
|
+
lines.append(f" - Attempts aimed at it that completed and were judged: {slot.judged_attempts}")
|
|
237
|
+
return lines
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _tasks(report: ScanReport) -> list[str]:
|
|
241
|
+
if not report.tasks:
|
|
242
|
+
return [_EMPTY_SECTION]
|
|
243
|
+
lines: list[str] = []
|
|
244
|
+
for task in report.tasks:
|
|
245
|
+
outcome = "worked as expected" if task.passed else "did not work"
|
|
246
|
+
detail = f" — {_code(task.detail)}" if task.detail else ""
|
|
247
|
+
lines.append(f"- {_code(task.task_id)}: {outcome}{detail}")
|
|
248
|
+
return lines
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _findings(report: ScanReport, report_path: str | None) -> list[str]:
|
|
252
|
+
if not report.findings:
|
|
253
|
+
return [_EMPTY_SECTION]
|
|
254
|
+
lines: list[str] = []
|
|
255
|
+
for finding in report.findings:
|
|
256
|
+
lines.extend(_finding(finding, report_path, report.slots))
|
|
257
|
+
return lines[:-1] # drop the trailing blank before the next section
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _finding_frameworks(finding: Finding, slots: tuple[SlotStatus, ...]) -> list[str]:
|
|
261
|
+
kind = objective_kind_for(finding, slots)
|
|
262
|
+
entries = entries_for(kind) if kind is not None else ()
|
|
263
|
+
if not entries:
|
|
264
|
+
return []
|
|
265
|
+
lines = ["- Framework entries:"]
|
|
266
|
+
for label, items in group_entries(entries):
|
|
267
|
+
joined = "; ".join(f"{item.id} {item.title}" for item in items)
|
|
268
|
+
lines.append(f" - {label}: {joined}")
|
|
269
|
+
return lines
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _finding(finding: Finding, report_path: str | None, slots: tuple[SlotStatus, ...] = ()) -> list[str]:
|
|
273
|
+
command = replay_command(report_path or "REPORT.json", finding.id)
|
|
274
|
+
if not report_path:
|
|
275
|
+
command = command.replace("REPORT.json", "<report.json>", 1)
|
|
276
|
+
lines = [
|
|
277
|
+
f"### {_text(finding.id)}: {_text(finding.title)}",
|
|
278
|
+
"",
|
|
279
|
+
f"- Evidence level: {finding.level.label}",
|
|
280
|
+
f"- Technique: {_text(finding.technique)}",
|
|
281
|
+
f"- Attack: {_code(finding.attack_id)}, sent as {_code(finding.attacker_principal)}",
|
|
282
|
+
*_what_was_violated(finding),
|
|
283
|
+
*_finding_frameworks(finding, slots),
|
|
284
|
+
f"- Discovery: {_rate_text('found in', 'search attempts', finding.discovery)}",
|
|
285
|
+
f"- Reproduction: {_rate_text('reproduced in', 'replays from reset', finding.reproduction)}",
|
|
286
|
+
f"- Replay: {_code(command)}",
|
|
287
|
+
"",
|
|
288
|
+
"#### Transcript",
|
|
289
|
+
"",
|
|
290
|
+
]
|
|
291
|
+
lines.extend(_transcript_lines(finding.transcript))
|
|
292
|
+
return lines
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _what_was_violated(finding: Finding) -> list[str]:
|
|
296
|
+
if finding.kind == "disclosure":
|
|
297
|
+
return [
|
|
298
|
+
f"- Slot: {_code(finding.slot_id)}",
|
|
299
|
+
f"- Policy: principals authorized to see this slot: {_principals(finding.authorized)}",
|
|
300
|
+
f"- How the canary appeared: encoding {_code(finding.encoding)}, scope {_code(finding.scope)}",
|
|
301
|
+
]
|
|
302
|
+
lines = []
|
|
303
|
+
if finding.kind == "injection":
|
|
304
|
+
lines.append(f"- Injection point: {_code(finding.slot_id)}")
|
|
305
|
+
lines.append("- Policy: this tool has no business running during the ordinary request below")
|
|
306
|
+
if finding.control is not None and finding.control.trials:
|
|
307
|
+
lines.append(
|
|
308
|
+
f"- Harmless-text control: with harmless text in the same place, a forbidden tool ran in "
|
|
309
|
+
f"{finding.control.successes} of {finding.control.trials} requests made between the replays. "
|
|
310
|
+
"This ties the call to the planted text by association, not by proof of cause"
|
|
311
|
+
)
|
|
312
|
+
else:
|
|
313
|
+
lines.append("- Harmless-text control: not run between replays; only the preflight check applies")
|
|
314
|
+
else:
|
|
315
|
+
lines.append(f"- Tool rule: {_code(finding.slot_id)}")
|
|
316
|
+
lines.append(
|
|
317
|
+
f"- Policy: principals whose own request may cause this tool to run: {_principals(finding.authorized)}"
|
|
318
|
+
)
|
|
319
|
+
lines.append("- Recorded at the tool, not taken from what the target said:")
|
|
320
|
+
lines.extend(f" - {_call_text(call)}" for call in finding.tool_calls)
|
|
321
|
+
return lines
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _call_text(call: ToolCall) -> str:
|
|
325
|
+
arguments = ", ".join(f"{name}={value}" for name, value in call.arguments)
|
|
326
|
+
fate = "accepted by the tool" if call.accepted else "refused by the tool"
|
|
327
|
+
result = f"; the tool answered {_code(call.result)}" if call.result else ""
|
|
328
|
+
return f"{_code(f'{call.tool}({arguments})')} {fate}{result}"
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _rate_text(verb: str, noun_plural: str, rate: Rate) -> str:
|
|
332
|
+
if rate.trials == 0:
|
|
333
|
+
return f"no {noun_plural} were run"
|
|
334
|
+
plural = "" if rate.errors == 1 else "s"
|
|
335
|
+
errors = (
|
|
336
|
+
f", {rate.errors} errored run{plural} not counted"
|
|
337
|
+
if rate.errors
|
|
338
|
+
else ""
|
|
339
|
+
)
|
|
340
|
+
if rate.interval_low is None or rate.interval_high is None:
|
|
341
|
+
interval = " (no interval recorded)"
|
|
342
|
+
else:
|
|
343
|
+
method = (
|
|
344
|
+
"95% Wilson interval"
|
|
345
|
+
if rate.interval_method == "wilson-95"
|
|
346
|
+
else f"interval method {rate.interval_method}"
|
|
347
|
+
)
|
|
348
|
+
low = _percent(rate.interval_low)
|
|
349
|
+
high = _percent(rate.interval_high)
|
|
350
|
+
interval = f" ({method} {low}% to {high}%)"
|
|
351
|
+
discarded = (
|
|
352
|
+
f", {rate.contaminated} discarded as contaminated and not counted" if rate.contaminated else ""
|
|
353
|
+
)
|
|
354
|
+
return f"{verb} {rate.successes} of {rate.trials} {noun_plural}{errors}{discarded}{interval}"
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _percent(value: float) -> int:
|
|
358
|
+
"""Round a fraction to a whole percentage, half up (0.565 -> 57)."""
|
|
359
|
+
scaled = Decimal(str(value)) * 100
|
|
360
|
+
return int(scaled.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _suspected(report: ScanReport) -> list[str]:
|
|
364
|
+
lines = [
|
|
365
|
+
"Suspected items are **not verified** and are **not counted** as violations; "
|
|
366
|
+
"they are shown for triage only.",
|
|
367
|
+
"",
|
|
368
|
+
]
|
|
369
|
+
if not report.suspected:
|
|
370
|
+
lines.append(_EMPTY_SECTION)
|
|
371
|
+
return lines
|
|
372
|
+
for index, item in enumerate(report.suspected, start=1):
|
|
373
|
+
lines.extend(
|
|
374
|
+
[
|
|
375
|
+
f"### Suspected {index}: {_text(item.title)}",
|
|
376
|
+
"",
|
|
377
|
+
f"- Attack: {_code(item.attack_id)} (technique: {_text(item.technique)})",
|
|
378
|
+
f"- Slot: {_code(item.slot_id)}",
|
|
379
|
+
f"- Why it is only suspected: {_code(item.reason)}",
|
|
380
|
+
"",
|
|
381
|
+
"#### Transcript",
|
|
382
|
+
"",
|
|
383
|
+
]
|
|
384
|
+
)
|
|
385
|
+
lines.extend(_transcript_lines(item.transcript))
|
|
386
|
+
return lines[:-1]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _contaminated(report: ScanReport) -> list[str]:
|
|
390
|
+
if report.contaminated_attempts == 0:
|
|
391
|
+
return [_EMPTY_SECTION]
|
|
392
|
+
count = report.contaminated_attempts
|
|
393
|
+
plural = "" if count == 1 else "s"
|
|
394
|
+
return [
|
|
395
|
+
f"Discarded {count} attempt{plural} because the canary appeared in "
|
|
396
|
+
"attacker-visible input; these runs prove nothing about the slot concerned "
|
|
397
|
+
"and are left out of its rates."
|
|
398
|
+
]
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _errors(report: ScanReport) -> list[str]:
|
|
402
|
+
if not report.errors:
|
|
403
|
+
return [_EMPTY_SECTION]
|
|
404
|
+
lines: list[str] = []
|
|
405
|
+
for error in report.errors:
|
|
406
|
+
where = f"attack {_code(error.attack_id)}" if error.attack_id else "scan-wide"
|
|
407
|
+
lines.append(f"- {_text(error.phase)}, {where}: {_code(error.message)}")
|
|
408
|
+
return lines
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _limitations(report: ScanReport) -> list[str]:
|
|
412
|
+
if not report.limitations:
|
|
413
|
+
return [_EMPTY_SECTION]
|
|
414
|
+
return [f"- {item}" for item in report.limitations]
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _transcript_lines(transcript: tuple[Turn, ...]) -> list[str]:
|
|
418
|
+
if not transcript:
|
|
419
|
+
return ["(empty transcript)", ""]
|
|
420
|
+
lines: list[str] = []
|
|
421
|
+
for turn in transcript:
|
|
422
|
+
speaker = {"attacker": "Attacker", "user": "Ordinary user"}.get(turn.role, "Target")
|
|
423
|
+
note = f" ({_text(turn.note)})" if turn.note else ""
|
|
424
|
+
fence = _fence(turn.text)
|
|
425
|
+
lines.append(f"**{speaker}{note}:**")
|
|
426
|
+
lines.append("")
|
|
427
|
+
lines.append(fence)
|
|
428
|
+
lines.append(turn.text)
|
|
429
|
+
lines.append(fence)
|
|
430
|
+
lines.append("")
|
|
431
|
+
for call in turn.tool_calls:
|
|
432
|
+
lines.append(f"- Tool call recorded during this reply: {_call_text(call)}")
|
|
433
|
+
if turn.tool_calls:
|
|
434
|
+
lines.append("")
|
|
435
|
+
return lines # ends with a blank line; callers trim the one after their last item
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
_MARKUP = frozenset("\\`*_[]<>#!|")
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _text(text: str) -> str:
|
|
442
|
+
"""`text` as plain prose on one line: nothing in it can act as Markdown or HTML."""
|
|
443
|
+
flat = " ".join(str(text).split())
|
|
444
|
+
return "".join("\\" + ch if ch in _MARKUP else ch for ch in flat)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _principals(principals: tuple[str, ...]) -> str:
|
|
448
|
+
return ", ".join(_code(p) for p in principals) if principals else "(none listed)"
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _config(report: ScanReport) -> str:
|
|
452
|
+
if not report.target_config:
|
|
453
|
+
return "not recorded"
|
|
454
|
+
return ", ".join(f"{_text(key)} {_code(value)}" for key, value in sorted(report.target_config.items()))
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _code(text: str) -> str:
|
|
458
|
+
"""`text` as an inline code span that nothing inside it can close or escape.
|
|
459
|
+
|
|
460
|
+
Details and error messages can quote a model's reply or a server's response, so
|
|
461
|
+
they are untrusted and must not be able to add links, images, HTML or headings.
|
|
462
|
+
"""
|
|
463
|
+
flat = " ".join(text.split())
|
|
464
|
+
longest_run = max((len(run) for run in re.findall(r"`+", flat)), default=0)
|
|
465
|
+
ticks = "`" * (longest_run + 1)
|
|
466
|
+
return f"{ticks} {flat} {ticks}" if flat else "(empty)"
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _fence(text: str) -> str:
|
|
470
|
+
"""A fence line guaranteed to be longer than any backtick run in `text`."""
|
|
471
|
+
longest_run = max((len(run) for run in re.findall(r"`+", text)), default=0)
|
|
472
|
+
return "`" * max(3, longest_run + 1)
|
botsting/reporting.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The reports a scan writes, and what it prints when it ends.
|
|
2
|
+
|
|
3
|
+
Shared by the commands that end in a person reading something: `scan` (and the first
|
|
4
|
+
scan behind it), `ci` and `demo`. Each report format itself lives in its own module
|
|
5
|
+
(report_markdown, report_html); this one owns where they are written and what the
|
|
6
|
+
terminal shows.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from botsting.core.models import ScanReport
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def write_file(path: Path, text: str) -> None:
|
|
19
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
path.write_text(text, encoding="utf-8")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_reports(
|
|
24
|
+
report: ScanReport, out: Path, markdown: Path | None = None, html: Path | None = None
|
|
25
|
+
) -> list[tuple[str, str]]:
|
|
26
|
+
"""Write the JSON report, and the readable and browser reports when paths are given.
|
|
27
|
+
|
|
28
|
+
Returns the (label, full path) pairs for the next-steps note. Full paths: a
|
|
29
|
+
relative one is wrong as soon as the reader is in another folder.
|
|
30
|
+
"""
|
|
31
|
+
write_file(out, json.dumps(report.to_dict(), indent=2))
|
|
32
|
+
paths = [("Report (JSON)", str(out.resolve()))]
|
|
33
|
+
if markdown is not None:
|
|
34
|
+
from botsting.report_markdown import render_markdown
|
|
35
|
+
|
|
36
|
+
write_file(markdown, render_markdown(report, str(out)))
|
|
37
|
+
paths.append(("Readable report", str(markdown.resolve())))
|
|
38
|
+
if html is not None:
|
|
39
|
+
from botsting.report_html import render_html
|
|
40
|
+
|
|
41
|
+
write_file(html, render_html(report, str(out)))
|
|
42
|
+
paths.insert(0, ("Report to open in a browser", str(html.resolve())))
|
|
43
|
+
return paths
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def summary(report: ScanReport) -> str:
|
|
47
|
+
"""What a scan prints: the verdict first, findings grouped, one real exchange. See console.py."""
|
|
48
|
+
from botsting.console import render, use_colour
|
|
49
|
+
|
|
50
|
+
return render(report, use_colour())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def show_summary(report: ScanReport, paths: list[tuple[str, str]], replay: str = "") -> None:
|
|
54
|
+
"""Print what the scan found, then the next steps: where the reports are and how to replay a finding."""
|
|
55
|
+
from botsting.console import next_steps, use_colour
|
|
56
|
+
|
|
57
|
+
print(summary(report))
|
|
58
|
+
print()
|
|
59
|
+
print(next_steps(report, paths, replay, use_colour()))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def open_for_a_person(page: Path, declined: bool = False) -> bool:
|
|
63
|
+
"""Open a report in the browser, but only when someone is sitting at a terminal: never in a
|
|
64
|
+
pipeline, a test, or when output is piped somewhere."""
|
|
65
|
+
import os
|
|
66
|
+
import webbrowser
|
|
67
|
+
|
|
68
|
+
if declined or not sys.stdout.isatty() or os.environ.get("CI") or os.environ.get("BOTSTING_NO_OPEN"):
|
|
69
|
+
return False
|
|
70
|
+
try:
|
|
71
|
+
return webbrowser.open(page.resolve().as_uri())
|
|
72
|
+
except Exception:
|
|
73
|
+
return False
|