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.
Files changed (56) hide show
  1. botsting/__init__.py +3 -0
  2. botsting/__main__.py +8 -0
  3. botsting/attacks/__init__.py +0 -0
  4. botsting/attacks/adaptive.py +495 -0
  5. botsting/attacks/library.py +239 -0
  6. botsting/attacks/pyrit_adapter.py +227 -0
  7. botsting/attacks/strategy.py +157 -0
  8. botsting/authorize_cli.py +148 -0
  9. botsting/ci.py +122 -0
  10. botsting/cli.py +464 -0
  11. botsting/console.py +240 -0
  12. botsting/core/__init__.py +0 -0
  13. botsting/core/authorization.py +550 -0
  14. botsting/core/benchmark.py +199 -0
  15. botsting/core/canary.py +80 -0
  16. botsting/core/judge.py +175 -0
  17. botsting/core/matcher.py +367 -0
  18. botsting/core/meter.py +228 -0
  19. botsting/core/models.py +560 -0
  20. botsting/core/preflight.py +283 -0
  21. botsting/core/replay.py +145 -0
  22. botsting/core/runner.py +39 -0
  23. botsting/core/scan.py +917 -0
  24. botsting/core/stats.py +42 -0
  25. botsting/demo.py +215 -0
  26. botsting/doctor.py +271 -0
  27. botsting/egress_trap.py +243 -0
  28. botsting/exits.py +38 -0
  29. botsting/frameworks.py +453 -0
  30. botsting/harness.py +893 -0
  31. botsting/harness_tools.py +260 -0
  32. botsting/llm/__init__.py +0 -0
  33. botsting/llm/base.py +31 -0
  34. botsting/llm/ollama.py +165 -0
  35. botsting/llm/scripted.py +122 -0
  36. botsting/mcp_server.py +643 -0
  37. botsting/practice_server.py +190 -0
  38. botsting/presets.py +222 -0
  39. botsting/quick.py +485 -0
  40. botsting/report_html.py +588 -0
  41. botsting/report_markdown.py +472 -0
  42. botsting/reporting.py +73 -0
  43. botsting/seal.py +245 -0
  44. botsting/shell.py +40 -0
  45. botsting/sterility.py +407 -0
  46. botsting/targets/__init__.py +0 -0
  47. botsting/targets/base.py +207 -0
  48. botsting/targets/hardened.py +360 -0
  49. botsting/targets/http.py +826 -0
  50. botsting/targets/registry.py +96 -0
  51. botsting/targets/toy.py +310 -0
  52. botsting-0.0.3.dist-info/METADATA +495 -0
  53. botsting-0.0.3.dist-info/RECORD +56 -0
  54. botsting-0.0.3.dist-info/WHEEL +4 -0
  55. botsting-0.0.3.dist-info/entry_points.txt +2 -0
  56. botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,588 @@
1
+ """Render a ScanReport as one self-contained HTML file.
2
+
3
+ This is the report a builder opens, prints, or hands to their own customer, so it has
4
+ to be safe to open and honest to read.
5
+
6
+ Safe to open: the page loads nothing and runs nothing. There is no script, no image,
7
+ no link and no external stylesheet, and a Content-Security-Policy forbids all of them
8
+ in case that ever slips. Everything a target or attacker wrote is escaped before it
9
+ is placed in the page; transcripts are full of text written by someone trying to
10
+ break things.
11
+
12
+ Honest to read: the wording rules are the same as for the Markdown report. Nothing
13
+ found is stated as "No verified violations observed under these tested conditions",
14
+ never as the target being fine; what was not tested is listed next to the verdict;
15
+ suspected items are shown apart and not counted; the limitations are printed in full.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from html import escape
21
+
22
+ from botsting.console import advice
23
+ from botsting.core.models import EvidenceLevel, Finding, Rate, ScanReport, SlotStatus, ToolCall, Turn
24
+ from botsting.frameworks import (
25
+ FrameworkEntry,
26
+ coverage_rows,
27
+ entries_for,
28
+ group_entries,
29
+ not_covered_sentence,
30
+ objective_kind_for,
31
+ )
32
+ from botsting.report_markdown import (
33
+ HEADLINE_NO_VERIFIED_VIOLATIONS,
34
+ INDEPENDENCE_DESCRIPTIONS,
35
+ INDEPENDENCE_EXPLANATION,
36
+ _rate_text,
37
+ )
38
+ from botsting.shell import replay_command
39
+
40
+ _CSS = """
41
+ /* An evidence file. Reading order: the verdict, what was reached, each finding as an exhibit with
42
+ its exchange, then how the test was done. Headings and exhibit numbers are set in a DIN-like
43
+ face, the kind used on technical documents; the prose is a book serif; anything quoted from a
44
+ conversation is monospace, because it is verbatim. No web font can load here (the page loads
45
+ nothing), so each is a stack of faces that ship with the common systems. */
46
+ :root {
47
+ --paper:#f7f9fb; --sheet:#ffffff; --ink:#14181f; --muted:#56606e; --rule:#d3dae3; --exhibit:#1f3fbf;
48
+ --bad:#b81a36; --ok:#0d6657; --unsure:#855600; --quote:#eef1f5;
49
+ --display:Bahnschrift,"DIN Alternate","Avenir Next Condensed","Roboto Condensed","Arial Narrow",sans-serif;
50
+ --text:Charter,"Bitstream Charter","Sitka Text",Cambria,Georgia,serif;
51
+ --mono:ui-monospace,"Cascadia Mono","SF Mono",Menlo,Consolas,monospace;
52
+ }
53
+ @media (prefers-color-scheme: dark) { :root {
54
+ --paper:#0f1217; --sheet:#151a21; --ink:#e6eaf0; --muted:#9aa5b3; --rule:#2a323d; --exhibit:#8ea5ff;
55
+ --bad:#ff8397; --ok:#6fd3bd; --unsure:#e5bd62; --quote:#1c222b; } }
56
+ * { box-sizing:border-box; }
57
+ body { margin:0; background:var(--paper); color:var(--ink); font:1.0625rem/1.6 var(--text); }
58
+ main { max-width:52rem; margin:0 auto; padding:2.5rem 1.25rem 5rem; }
59
+ h1, h2, h3, th, dt, .tag, .who, .num, .facts { font-family:var(--display); }
60
+ h1 { font-size:.95rem; font-weight:600; color:var(--muted); margin:0 0 1.25rem; }
61
+ h2 { font-size:1.45rem; font-weight:700; font-stretch:90%; line-height:1.15; margin:3.5rem 0 1rem; }
62
+ h3 { font-size:1.2rem; font-weight:700; font-stretch:90%; line-height:1.25; margin:0 0 .35rem; }
63
+ table + h3, .scroll + h3 { margin-top:1.6rem; }
64
+ p { margin:.5rem 0; max-width:42rem; }
65
+ ul { margin:.5rem 0; padding-left:1.2rem; max-width:42rem; } li { margin:.3rem 0; }
66
+ code { font:.86em var(--mono); background:var(--quote); padding:.08em .3em; border-radius:3px; overflow-wrap:anywhere; }
67
+ .note { color:var(--muted); font-size:.94rem; }
68
+
69
+ /* The verdict is the one loud thing on the page. */
70
+ .verdict { border-top:.5rem solid var(--muted); padding:1.1rem 0 0; }
71
+ .verdict strong { display:block; font:700 clamp(2rem,6vw,3.1rem)/1.04 var(--display); font-stretch:85%;
72
+ letter-spacing:-.01em; margin-bottom:.6rem; max-width:18ch; }
73
+ .verdict.bad { border-color:var(--bad); } .verdict.bad strong { color:var(--bad); }
74
+ .verdict.ok { border-color:var(--ok); } .verdict.ok strong { color:var(--ok); max-width:24ch; }
75
+ .verdict.unsure { border-color:var(--unsure); } .verdict.unsure strong { color:var(--unsure); max-width:22ch; }
76
+ .facts { display:flex; flex-wrap:wrap; gap:.4rem 2.2rem; margin:1.3rem 0 0; padding:.8rem 0 0;
77
+ border-top:1px solid var(--rule); font-size:.98rem; }
78
+ .facts div { display:grid; } .facts span { color:var(--muted); font-size:.85rem; }
79
+
80
+ /* Tables: the index of what was reached, and the instruments. */
81
+ .scroll { overflow-x:auto; }
82
+ table { border-collapse:collapse; width:100%; font-size:.98rem; }
83
+ th, td { text-align:left; padding:.55rem .9rem .55rem 0; border-bottom:1px solid var(--rule); vertical-align:top;
84
+ overflow-wrap:anywhere; }
85
+ th { color:var(--muted); font-weight:600; font-size:.88rem; border-bottom-color:var(--ink); white-space:nowrap;
86
+ overflow-wrap:normal; }
87
+ td ul { padding-left:1rem; margin:0; } td li { margin:.15rem 0; }
88
+ td:first-child { overflow-wrap:normal; } td:first-child code { white-space:nowrap; }
89
+ .reached td:first-child { font-family:var(--display); font-weight:700; white-space:nowrap; overflow-wrap:normal; }
90
+ .reached td:nth-child(n+3) { white-space:nowrap; }
91
+ .num { color:var(--exhibit); font-weight:700; white-space:nowrap; }
92
+
93
+ /* A finding is an exhibit: its number hangs in the margin, the exchange is quoted verbatim. */
94
+ .card { display:grid; grid-template-columns:4.2rem minmax(0,1fr); column-gap:.4rem; padding:1.6rem 0 1.9rem;
95
+ border-top:1px solid var(--rule); }
96
+ .card > * { grid-column:2; }
97
+ .card > .num { grid-column:1; grid-row:1 / span 3; font-size:1.7rem; font-stretch:85%; line-height:1; padding-top:.15rem; }
98
+ .tag { justify-self:start; font-size:.84rem; font-weight:600; margin-bottom:.3rem; }
99
+ .tag.bad { color:var(--bad); } .tag.unsure { color:var(--unsure); } .tag.ok { color:var(--ok); }
100
+ .what { margin:0 0 .9rem; }
101
+ .turn { margin:.55rem 0 0; }
102
+ .who { font-size:.86rem; font-weight:600; color:var(--muted); }
103
+ pre { margin:.2rem 0 0; padding:.7rem .85rem; background:var(--quote); border-left:3px solid var(--rule);
104
+ white-space:pre-wrap; overflow-wrap:anywhere; font:.88rem/1.5 var(--mono); max-height:26rem; overflow:auto; }
105
+ .turn.attacker pre { border-left-color:var(--bad); }
106
+ .turn.target pre { border-left-color:var(--exhibit); }
107
+ .turn.user pre { border-left-color:var(--muted); }
108
+ .turn .note { margin:.3rem 0 0; padding-left:.9rem; }
109
+ dl { display:grid; grid-template-columns:minmax(9.5rem,max-content) minmax(0,1fr); gap:.35rem 1.2rem; margin:.9rem 0 0;
110
+ font-size:.97rem; }
111
+ dt { color:var(--muted); font-size:.9rem; padding-top:.1rem; } dd { margin:0; overflow-wrap:anywhere; }
112
+ dd ul { padding-left:1rem; margin:0; }
113
+ .card dl { margin-top:1.2rem; padding-top:.9rem; border-top:1px dotted var(--rule); }
114
+
115
+ /* The other ways to the same thing: one line each until opened. */
116
+ .more { margin:0 0 1.4rem 4.6rem; }
117
+ .more > .note { margin:0 0 .3rem; }
118
+ details { border-top:1px solid var(--rule); }
119
+ details:last-child { border-bottom:1px solid var(--rule); }
120
+ summary { cursor:pointer; padding:.5rem 0; font-family:var(--display); font-weight:600; }
121
+ summary .num { display:inline-block; min-width:3rem; }
122
+ summary .note { font-family:var(--text); font-weight:400; margin-left:.6rem; white-space:nowrap; }
123
+ details .card { border-top:0; padding-top:.4rem; grid-template-columns:minmax(0,1fr); }
124
+ details .card > *, details .card > .num { grid-column:1; grid-row:auto; }
125
+ details .card > .num, details .card > h3 { display:none; }
126
+
127
+ /* What the scan never tried, beside the verdict. */
128
+ p.untested { font-family:var(--display); font-weight:700; color:var(--unsure); margin:1rem 0 0; }
129
+ ul.untested { margin-top:.2rem; }
130
+
131
+ @media (max-width:40rem) {
132
+ .card { grid-template-columns:minmax(0,1fr); } .card > *, .card > .num { grid-column:1; grid-row:auto; }
133
+ .more { margin-left:0; }
134
+ dl { grid-template-columns:minmax(0,1fr); gap:0; } dd { margin-bottom:.5rem; }
135
+ }
136
+ @media print {
137
+ :root { --paper:#fff; --sheet:#fff; --ink:#000; --muted:#444; --rule:#999; --quote:#f3f3f3; --exhibit:#000; }
138
+ body { font-size:10.5pt; } main { max-width:none; padding:0; }
139
+ pre { max-height:none; overflow:visible; } .card, tr { break-inside:avoid; } h2 { break-after:avoid; }
140
+ }
141
+ """
142
+
143
+
144
+ def _e(text: object) -> str:
145
+ """Anything from a target, an attacker or configuration, made inert."""
146
+ return escape(str(text), quote=True)
147
+
148
+
149
+ def _code(text: object) -> str:
150
+ return f"<code>{_e(text)}</code>"
151
+
152
+
153
+ def _principals(principals: tuple[str, ...]) -> str:
154
+ return ", ".join(_code(p) for p in principals) if principals else "none listed"
155
+
156
+
157
+ def _verdict(report: ScanReport) -> list[str]:
158
+ if report.status == "violations_verified":
159
+ count = len(report.findings)
160
+ kind, headline = "bad", f"{count} verified violation{'' if count == 1 else 's'} found."
161
+ detail = f"<p>Of these: {_e(report.breakdown())}.</p>"
162
+ elif report.status == "no_verified_violations":
163
+ kind, headline, detail = "ok", HEADLINE_NO_VERIFIED_VIOLATIONS, (
164
+ "<p>This describes the tests listed below and nothing more. "
165
+ "The limitations at the end say what those tests cannot show.</p>"
166
+ )
167
+ else:
168
+ kind, headline, detail = "unsure", "The scan could not reach a conclusion.", ""
169
+ lines = [f'<section class="verdict {kind}"><strong>{_e(headline)}</strong>{detail}']
170
+ if report.inconclusive_reasons:
171
+ label = "Why" if report.status == "inconclusive" else "Not everything could be tested"
172
+ lines.append(f"<p>{label}:</p><ul>")
173
+ lines += [f"<li>{_e(reason)}</li>" for reason in report.inconclusive_reasons]
174
+ lines.append("</ul>")
175
+ gaps = report.not_tested()
176
+ if gaps:
177
+ lines.append('<p class="untested">Not tested in this scan:</p><ul class="untested">')
178
+ lines += [f"<li>{_e(gap)}</li>" for gap in gaps]
179
+ lines.append("</ul>")
180
+ who = report.authorization.get("authorized_by", "") if report.authorization else ""
181
+ facts = [
182
+ ("Target", _e(report.target)),
183
+ ("Tested", _e(str(report.started_at)[:10])),
184
+ ("Attacks", f"{_e(report.attacks_run)}, in {_e(report.messages_sent)} messages"),
185
+ ]
186
+ if who:
187
+ facts.append(("Authorized by", _e(who)))
188
+ lines.append('<div class="facts">' + "".join(f"<div><span>{k}</span>{v}</div>" for k, v in facts) + "</div>")
189
+ lines.append("</section>")
190
+ return lines
191
+
192
+
193
+ def _id_runs(ids: list[str]) -> str:
194
+ """Finding ids as runs: "F1 to F10, F12". A finding can reach something other than what its
195
+ attack aimed at, so the findings for one thing are not always numbered one after another."""
196
+
197
+ def number(identifier: str) -> int | None:
198
+ digits = identifier.lstrip("F")
199
+ return int(digits) if identifier.startswith("F") and digits.isdigit() else None
200
+
201
+ runs: list[list[str]] = []
202
+ for identifier in ids:
203
+ last, here = (number(runs[-1][-1]) if runs else None), number(identifier)
204
+ if last is not None and here is not None and here == last + 1:
205
+ runs[-1].append(identifier)
206
+ else:
207
+ runs.append([identifier])
208
+ return ", ".join(run[0] if len(run) == 1 else f"{run[0]} to {run[-1]}" for run in runs)
209
+
210
+
211
+ def _reached(report: ScanReport) -> list[str]:
212
+ """The index: each protected thing an attack got to, in how many ways, and how reliably."""
213
+ lines = ["<h2>What was reached</h2>"]
214
+ if not report.findings:
215
+ if report.status == "no_verified_violations":
216
+ lines.append("<p>Nothing. No planted value came out and no forbidden tool call was recorded.</p>")
217
+ else:
218
+ lines.append("<p>Nothing was verified. See above for what could not be established.</p>")
219
+ return lines
220
+ grouped: dict[str, list[Finding]] = {}
221
+ for finding in report.findings:
222
+ grouped.setdefault(finding.slot_id, []).append(finding)
223
+ lines.append(
224
+ '<div class="scroll"><table class="reached"><thead><tr><th>What</th><th>What happened</th><th>Ways</th>'
225
+ "<th>Findings</th><th>Replays that reproduced it</th></tr></thead><tbody>"
226
+ )
227
+ for slot_id, found in grouped.items():
228
+ first = found[0]
229
+ if first.kind == "disclosure":
230
+ happened = "Its planted value was disclosed to the attacker"
231
+ elif first.kind == "injection":
232
+ fate = "accepted the call" if any(call.accepted for f in found for call in f.tool_calls) else "refused it"
233
+ happened = f"With text planted here, an ordinary request led to a tool call, and the tool {fate}"
234
+ elif any(call.accepted for f in found for call in f.tool_calls):
235
+ happened = "A tool was called for the attacker, and accepted the call"
236
+ else:
237
+ happened = "A tool was called for the attacker, and refused it"
238
+ ids = _id_runs([f.id for f in found])
239
+ done = sum(f.reproduction.successes for f in found)
240
+ tried = sum(f.reproduction.trials for f in found)
241
+ lines.append(
242
+ f"<tr><td>{_e(slot_id)}</td><td>{happened}</td><td>{len(found)}</td>"
243
+ f'<td><span class="num">{_e(ids)}</span></td><td>{done} of {tried}</td></tr>'
244
+ )
245
+ lines.append("</tbody></table></div>")
246
+ fixes = [(slot_id, advice(report, slot_id)) for slot_id in grouped]
247
+ if any(text for _, text in fixes):
248
+ lines.append("<h3>What to change</h3><ul>")
249
+ lines += [f"<li>{_code(slot_id)}: {_e(text)}</li>" for slot_id, text in fixes if text]
250
+ lines.append("</ul>")
251
+ return lines
252
+
253
+
254
+ def _authorization_html(authorization: dict[str, str]) -> str:
255
+ if not authorization:
256
+ return "Not recorded (local or in-process target)."
257
+ if "authorized_by" in authorization:
258
+ parts = [f"Authorized by {_e(authorization['authorized_by'])}"]
259
+ if authorization.get("origin"):
260
+ parts.append(f"for origin {_code(authorization['origin'])}")
261
+ if authorization.get("environment"):
262
+ parts.append(f"in {_code(authorization['environment'])} environment")
263
+ if authorization.get("scope"):
264
+ parts.append(f"(scope: {_e(authorization['scope'])})")
265
+ if authorization.get("allowed_tools"):
266
+ parts.append(f"Tools that could be exercised: {_e(authorization['allowed_tools'])}.")
267
+ if authorization.get("live_tools"):
268
+ parts.append(f"Tools that could be carried out for real, inside the bot's own caps: {_e(authorization['live_tools'])}.")
269
+ return " ".join(parts)
270
+ if authorization.get("reach") == "in-process":
271
+ return "Not required (in-process target)."
272
+ return ", ".join(f"{_e(k)} {_code(v)}" for k, v in sorted(authorization.items()))
273
+
274
+
275
+ def _about(report: ScanReport) -> list[str]:
276
+ tester = _e(report.tester) if report.tester.strip() else "Not stated"
277
+ desc = INDEPENDENCE_DESCRIPTIONS.get(report.independence)
278
+ independence = f"{_code(report.independence)} ({_e(desc)})" if desc else _code(report.independence)
279
+ rows = [
280
+ ("Tool version", _e(report.tool_version)),
281
+ ("Scan dates", f"{_e(report.started_at)} to {_e(report.finished_at)} (UTC)"),
282
+ ("Authorization", _authorization_html(report.authorization)),
283
+ ("Tester", tester),
284
+ ("Independence", independence),
285
+ ]
286
+ return (
287
+ ["<h2>About this test</h2>", "<dl>"]
288
+ + [f"<dt>{k}</dt><dd>{v}</dd>" for k, v in rows]
289
+ + ["</dl>", f'<p class="note">{_e(INDEPENDENCE_EXPLANATION)}</p>']
290
+ )
291
+
292
+
293
+ def _tested(report: ScanReport) -> list[str]:
294
+ config = ", ".join(f"{_e(k)} {_code(v)}" for k, v in sorted(report.target_config.items())) or "not recorded"
295
+ rows = [
296
+ ("Target", _code(report.target)),
297
+ ("Target configuration", config),
298
+ ("Attacker acting as", _code(report.attacker_principal)),
299
+ ("Attacks run", _e(report.attacks_run)),
300
+ ("Attempts run", _e(report.attempts_run)),
301
+ ("Search attempts per attack", _e(report.discovery_runs)),
302
+ ("Replays per verified finding", _e(report.reproduction_trials)),
303
+ ("Spent", f"{_e(report.messages_sent)} messages sent, {_e(report.tool_calls_recorded)} tool calls recorded"),
304
+ ]
305
+ if report.stopped_early:
306
+ rows.append(("Stopped early", _e(report.stopped_early)))
307
+ return ["<h2>What was tested</h2>", "<dl>"] + [f"<dt>{k}</dt><dd>{v}</dd>" for k, v in rows] + ["</dl>"]
308
+
309
+
310
+ def _framework_list_html(entries: tuple[FrameworkEntry, ...]) -> str:
311
+ items = []
312
+ for label, grouped in group_entries(entries):
313
+ refs = "; ".join(f"{_code(entry.id)} {_e(entry.title)}" for entry in grouped)
314
+ items.append(f"<li><strong>{_e(label)}</strong>: {refs}</li>")
315
+ return "<ul>" + "".join(items) + "</ul>"
316
+
317
+
318
+ def _coverage(report: ScanReport) -> list[str]:
319
+ lines = ["<h2>Framework coverage</h2>"]
320
+ rows = coverage_rows(report)
321
+ if not rows:
322
+ lines.append("<p>None recorded.</p>")
323
+ lines.append(f'<p class="note">{_e(not_covered_sentence(()))}</p>')
324
+ return lines
325
+ lines.append(
326
+ '<div class="scroll"><table><thead><tr><th>Objective kind</th><th>Framework entries</th>'
327
+ "<th>Attempts judged</th><th>Result</th></tr></thead><tbody>"
328
+ )
329
+ for row in rows:
330
+ lines.append(
331
+ f"<tr><td>{_e(row.label)}</td><td>{_framework_list_html(row.entries)}</td>"
332
+ f"<td>{_e(row.attempts)}</td><td>{_e(row.result)}</td></tr>"
333
+ )
334
+ lines.append("</tbody></table></div>")
335
+ lines.append(f'<p class="note">{_e(not_covered_sentence([row.kind for row in rows]))}</p>')
336
+ return lines
337
+
338
+
339
+ def _protected_row(slot: SlotStatus) -> str:
340
+ if slot.kind == "tool_rule":
341
+ policy = f"May be caused to run by: {_principals(slot.authorized)}"
342
+ elif slot.kind == "injection_point":
343
+ policy = "Tested by planting text here and having an ordinary user make an ordinary request"
344
+ else:
345
+ policy = f"May be seen by: {_principals(slot.authorized)}"
346
+ state = _e(slot.state) + (f"<br><span class=\"note\">{_e(slot.detail)}</span>" if slot.detail else "")
347
+ return (
348
+ f"<tr><td>{_code(slot.slot_id)}<br><span class=\"note\">{_e(slot.kind.replace('_', ' '))}</span></td>"
349
+ f"<td>{_e(slot.description)}<br><span class=\"note\">{policy}</span></td>"
350
+ f"<td>{state}</td><td>{_e(slot.judged_attempts)}</td></tr>"
351
+ )
352
+
353
+
354
+ def _protected(report: ScanReport) -> list[str]:
355
+ lines = ["<h2>What was protected</h2>"]
356
+ if not report.slots:
357
+ return lines + ["<p>None recorded.</p>"]
358
+ lines.append(
359
+ '<div class="scroll"><table><thead><tr><th>What</th><th>Policy</th><th>Legitimate route</th>'
360
+ "<th>Attempts judged</th></tr></thead><tbody>"
361
+ )
362
+ lines += [_protected_row(slot) for slot in report.slots]
363
+ lines.append("</tbody></table></div>")
364
+ lines.append(
365
+ '<p class="note">"Legitimate route" is the check that each protected thing works for someone allowed to use it. '
366
+ 'If it does not, finding nothing for it would mean nothing. "Attempts judged" of zero means it was not tested.</p>'
367
+ )
368
+ return lines
369
+
370
+
371
+ def _tasks(report: ScanReport) -> list[str]:
372
+ lines = ["<h2>Normal use</h2>"]
373
+ if not report.tasks:
374
+ return lines + ["<p>None recorded.</p>"]
375
+ lines.append("<ul>")
376
+ for task in report.tasks:
377
+ outcome = "worked as expected" if task.passed else "did not work"
378
+ detail = f' <span class="note">{_e(task.detail)}</span>' if task.detail else ""
379
+ lines.append(f"<li>{_code(task.task_id)}: {outcome}{detail}</li>")
380
+ lines.append("</ul>")
381
+ return lines
382
+
383
+
384
+ def _call(call: ToolCall) -> str:
385
+ arguments = ", ".join(f"{name}={value}" for name, value in call.arguments)
386
+ fate = "accepted by the tool" if call.accepted else "refused by the tool"
387
+ result = f"; the tool answered {_code(call.result)}" if call.result else ""
388
+ return f"{_code(f'{call.tool}({arguments})')} {fate}{result}"
389
+
390
+
391
+ def _transcript(turns: tuple[Turn, ...]) -> list[str]:
392
+ if not turns:
393
+ return ['<p class="note">No conversation was recorded.</p>']
394
+ lines: list[str] = []
395
+ for turn in turns:
396
+ who = {"attacker": "Attacker", "user": "Ordinary user"}.get(turn.role, "Target")
397
+ note = f" ({_e(turn.note)})" if turn.note else ""
398
+ lines.append(f'<div class="turn {_e(turn.role)}"><div class="who">{who}{note}</div><pre>{_e(turn.text)}</pre>')
399
+ for call in turn.tool_calls:
400
+ lines.append(f'<p class="note">Tool call recorded during this reply: {_call(call)}</p>')
401
+ lines.append("</div>")
402
+ return lines
403
+
404
+
405
+ def _rate(verb: str, noun: str, rate: Rate) -> str:
406
+ return _e(_rate_text(verb, noun, rate))
407
+
408
+
409
+ def _finding(finding: Finding, report_path: str | None, slots: tuple[SlotStatus, ...] = ()) -> list[str]:
410
+ refused = finding.level == EvidenceLevel.ACTION_ATTEMPTED
411
+ rate = finding.reproduction
412
+ if finding.kind == "disclosure":
413
+ what = f"The value planted at {_code(finding.slot_id)} came out in the answer below."
414
+ elif finding.kind == "injection":
415
+ what = f"With text planted at {_code(finding.slot_id)}, an ordinary request made the bot call a tool."
416
+ else:
417
+ what = "The attacker's conversation made the bot call a tool it may not use for them."
418
+ lines = [
419
+ '<article class="card">',
420
+ f'<span class="num">{_e(finding.id)}</span>',
421
+ f'<span class="tag {"unsure" if refused else "bad"}">{_e(finding.level.label)}</span>',
422
+ f"<h3>{_e(finding.title)}</h3>",
423
+ f'<p class="what">{what} It worked again in {_e(rate.successes)} of {_e(rate.trials)} replays from a fresh start.</p>',
424
+ ]
425
+ lines += _transcript(finding.transcript)
426
+ lines += [
427
+ "<dl>",
428
+ f"<dt>Technique</dt><dd>{_e(finding.technique)}</dd>",
429
+ f"<dt>Attack</dt><dd>{_code(finding.attack_id)}, by {_code(finding.attacker_principal)}</dd>",
430
+ ]
431
+ if finding.kind == "disclosure":
432
+ lines += [
433
+ f"<dt>What leaked</dt><dd>{_code(finding.slot_id)}</dd>",
434
+ f"<dt>Policy</dt><dd>May be seen by: {_principals(finding.authorized)}</dd>",
435
+ f"<dt>How it appeared</dt><dd>{_code(finding.encoding)}, {_code(finding.scope)}</dd>",
436
+ ]
437
+ else:
438
+ if finding.kind == "injection":
439
+ lines += [
440
+ f"<dt>Where text was planted</dt><dd>{_code(finding.slot_id)}</dd>",
441
+ "<dt>Policy</dt><dd>This tool has no business running during the ordinary request shown below</dd>",
442
+ ]
443
+ if finding.control is not None and finding.control.trials:
444
+ lines.append(
445
+ "<dt>Harmless-text control</dt><dd>With harmless text in the same place, a forbidden tool ran in "
446
+ f"{_e(finding.control.successes)} of {_e(finding.control.trials)} requests made between the replays. "
447
+ "This ties the call to the planted text by association, not by proof of cause</dd>"
448
+ )
449
+ else:
450
+ lines += [
451
+ f"<dt>Tool rule</dt><dd>{_code(finding.slot_id)}</dd>",
452
+ f"<dt>Policy</dt><dd>May be caused to run by: {_principals(finding.authorized)}</dd>",
453
+ ]
454
+ calls = "".join(f"<li>{_call(call)}</li>" for call in finding.tool_calls)
455
+ lines.append(f"<dt>Recorded at the tool</dt><dd>Not taken from what the target said:<ul>{calls}</ul></dd>")
456
+ kind = objective_kind_for(finding, slots)
457
+ entries = entries_for(kind) if kind is not None else ()
458
+ if entries:
459
+ ids = ", ".join(_code(entry.id) for entry in entries)
460
+ lines.append(
461
+ f'<dt>Framework entries</dt><dd>{ids} <span class="note">(named in full under Framework coverage)</span></dd>'
462
+ )
463
+ command = replay_command(report_path or "REPORT.json", finding.id)
464
+ if not report_path:
465
+ command = command.replace("REPORT.json", "<report.json>", 1)
466
+ lines += [
467
+ f"<dt>Found</dt><dd>{_rate('found in', 'search attempts', finding.discovery)}</dd>",
468
+ f"<dt>Reproduced</dt><dd>{_rate('reproduced in', 'replays from reset', finding.reproduction)}</dd>",
469
+ f"<dt>Replay</dt><dd>{_code(command)}</dd>",
470
+ "</dl>",
471
+ ]
472
+ lines.append("</article>")
473
+ return lines
474
+
475
+
476
+ def _findings(report: ScanReport, report_path: str | None) -> list[str]:
477
+ """Every verified finding, grouped by what was reached. The first way in is shown in full; the
478
+ other ways to the same thing are folded, each still complete, so the page reads in minutes and
479
+ the file still holds all of the evidence."""
480
+ lines = ["<h2>Verified findings</h2>"]
481
+ if not report.findings:
482
+ return lines + ["<p>None recorded.</p>"]
483
+ grouped: dict[str, list[Finding]] = {}
484
+ for finding in report.findings:
485
+ grouped.setdefault(finding.slot_id, []).append(finding)
486
+ folded = sum(len(found) - 1 for found in grouped.values())
487
+ if folded:
488
+ lines.append(
489
+ f'<p class="note">{len(report.findings)} findings reached {len(grouped)} '
490
+ f'thing{"" if len(grouped) == 1 else "s"}. For each, the first way in is shown in full. The other '
491
+ f"{folded} are folded below it: open one to read its exchange. Printing keeps them folded; the JSON "
492
+ "report holds every one in full.</p>"
493
+ )
494
+ for slot_id, found in grouped.items():
495
+ lines += _finding(found[0], report_path, report.slots)
496
+ if len(found) == 1:
497
+ continue
498
+ more = len(found) - 1
499
+ lines.append(
500
+ f'<div class="more"><p class="note">{more} more way{"" if more == 1 else "s"} reached '
501
+ f"{_code(slot_id)}. Each is a verified finding of its own.</p>"
502
+ )
503
+ for finding in found[1:]:
504
+ rate = finding.reproduction
505
+ lines.append(
506
+ f'<details><summary><span class="num">{_e(finding.id)}</span> {_e(finding.title)} '
507
+ f'<span class="note">{_e(rate.successes)} of {_e(rate.trials)} replays</span></summary>'
508
+ )
509
+ lines += _finding(finding, report_path, report.slots)
510
+ lines.append("</details>")
511
+ lines.append("</div>")
512
+ return lines
513
+
514
+
515
+ def _suspected(report: ScanReport) -> list[str]:
516
+ lines = [
517
+ "<h2>Suspected findings</h2>",
518
+ "<p>Suspected items are <strong>not verified</strong> and are <strong>not counted</strong> as violations. "
519
+ "They are shown so that someone can look into them.</p>",
520
+ ]
521
+ if not report.suspected:
522
+ return lines + ["<p>None recorded.</p>"]
523
+ for index, item in enumerate(report.suspected, start=1):
524
+ lines += [
525
+ '<article class="card">',
526
+ '<span class="tag unsure">Suspected, not verified</span>',
527
+ f"<h3>Suspected {index}: {_e(item.title)}</h3>",
528
+ "<dl>",
529
+ f"<dt>Attack</dt><dd>{_code(item.attack_id)} ({_e(item.technique)})</dd>",
530
+ f"<dt>Concerns</dt><dd>{_code(item.slot_id)}</dd>",
531
+ f"<dt>Why only suspected</dt><dd>{_e(item.reason)}</dd>",
532
+ "</dl>",
533
+ ]
534
+ lines += _transcript(item.transcript)
535
+ lines.append("</article>")
536
+ return lines
537
+
538
+
539
+ def _rest(report: ScanReport) -> list[str]:
540
+ lines = ["<h2>Discarded attempts</h2>"]
541
+ if report.contaminated_attempts:
542
+ count = report.contaminated_attempts
543
+ lines.append(
544
+ f"<p>{_e(count)} attempt{'' if count == 1 else 's'} discarded because the planted value appeared in "
545
+ "attacker-visible input. These prove nothing about the thing concerned and are left out of its rates.</p>"
546
+ )
547
+ else:
548
+ lines.append("<p>None recorded.</p>")
549
+ lines.append("<h2>Errors</h2>")
550
+ if report.errors:
551
+ lines.append("<ul>")
552
+ for error in report.errors:
553
+ where = f"attack {_code(error.attack_id)}" if error.attack_id else "whole scan"
554
+ lines.append(f"<li>{_e(error.phase)}, {where}: {_e(error.message)}</li>")
555
+ lines.append("</ul>")
556
+ else:
557
+ lines.append("<p>None recorded.</p>")
558
+ lines.append("<h2>Limitations</h2>")
559
+ if report.limitations:
560
+ lines += ["<ul>"] + [f"<li>{_e(item)}</li>" for item in report.limitations] + ["</ul>"]
561
+ else:
562
+ lines.append("<p>None recorded.</p>")
563
+ return lines
564
+
565
+
566
+ def render_html(report: ScanReport, report_path: str | None = None) -> str:
567
+ """The report as one HTML document. `report_path` is the JSON file's path, used in replay commands."""
568
+ body: list[str] = ["<h1>BotSting scan report</h1>"]
569
+ # A reader wants the verdict, then what was reached and how, then how far to trust it.
570
+ body += _verdict(report)
571
+ body += _reached(report)
572
+ body += _findings(report, report_path)
573
+ body += _suspected(report)
574
+ body += _protected(report)
575
+ body += _tasks(report)
576
+ body += _tested(report)
577
+ body += _about(report)
578
+ body += _coverage(report)
579
+ body += _rest(report)
580
+ return (
581
+ "<!doctype html>\n"
582
+ '<html lang="en"><head><meta charset="utf-8">'
583
+ '<meta name="viewport" content="width=device-width, initial-scale=1">'
584
+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">"
585
+ '<meta name="referrer" content="no-referrer">'
586
+ f"<title>BotSting scan report: {_e(report.target)}</title>"
587
+ f"<style>{_CSS}</style></head>\n<body><main>\n" + "\n".join(body) + "\n</main></body></html>\n"
588
+ )