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
botsting/cli.py ADDED
@@ -0,0 +1,464 @@
1
+ """Command line: `botsting scan` and `botsting replay`.
2
+
3
+ Exit codes: 0 no verified violations, 1 violations verified (or reproduced, for replay),
4
+ 2 inconclusive or a usage error. A script can therefore tell "found nothing" from
5
+ "could not tell", and a broken target can never be mistaken for a fixed one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import signal
13
+ import sys
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+
17
+ from botsting import __version__
18
+ from botsting.attacks.adaptive import LLMAdaptiveStrategy
19
+ from botsting.attacks.library import default_attacks
20
+ from botsting.console import NO_VERIFIED_HEADLINE, what_happened # noqa: F401 (re-exported)
21
+ from botsting.core.benchmark import DEFAULT_MARGIN, compare_strategies, render_benchmark_markdown
22
+ from botsting.core.models import Rate, ScanReport
23
+ from botsting.core.runner import ScanConfig, identity_unknown, replay_finding, run_scan, run_to_completion
24
+ from botsting.exits import EXIT_FAILED, EXIT_INCONCLUSIVE, EXIT_NO_VERIFIED, EXIT_OK, EXIT_VIOLATIONS
25
+ from botsting.reporting import open_for_a_person, show_summary, write_file, write_reports
26
+ from botsting.shell import replay_command
27
+ from botsting.targets.registry import SpecError, build_model, build_target
28
+
29
+
30
+ def _percent(value: float | None) -> str:
31
+ return "n/a" if value is None else f"{round(value * 100)}%"
32
+
33
+
34
+ def describe_rate(rate: Rate, noun: str) -> str:
35
+ text = f"{rate.successes} of {rate.trials} {noun}"
36
+ if rate.trials:
37
+ text += f" (95% Wilson interval {_percent(rate.interval_low)} to {_percent(rate.interval_high)})"
38
+ if rate.errors:
39
+ text += f", {rate.errors} more did not complete"
40
+ if rate.contaminated:
41
+ text += f", {rate.contaminated} more discarded as contaminated"
42
+ return text
43
+
44
+
45
+ def _run_until_done_or_cancelled(start: Callable[[Callable[[], bool]], object]) -> object:
46
+ """Run a scan so that Ctrl+C stops it after the current message and a partial report is still written.
47
+
48
+ A second Ctrl+C gives up immediately.
49
+ """
50
+ state = {"cancelled": False}
51
+
52
+ def on_interrupt(signum: int, frame: object) -> None:
53
+ if state["cancelled"]:
54
+ raise KeyboardInterrupt
55
+ state["cancelled"] = True
56
+ print("Stopping after the current message. Press Ctrl+C again to abandon the scan.", file=sys.stderr)
57
+
58
+ try:
59
+ previous = signal.signal(signal.SIGINT, on_interrupt)
60
+ except ValueError: # not the main thread; run without the handler
61
+ return run_to_completion(start(lambda: False)) # type: ignore[arg-type]
62
+ try:
63
+ return run_to_completion(start(lambda: state["cancelled"])) # type: ignore[arg-type]
64
+ finally:
65
+ signal.signal(signal.SIGINT, previous)
66
+
67
+
68
+ def run_scan_command(args: argparse.Namespace) -> int:
69
+ """The `botsting scan` command, once the target is known: scan it, write the reports, say what to do next.
70
+
71
+ `quick` (a first scan of a URL) and `ci` call this too, with their own arguments
72
+ already folded into `args`.
73
+ """
74
+ if not args.target:
75
+ print(
76
+ "error: say what to scan: a chat URL (botsting scan http://localhost:8000/chat) or --target NAME",
77
+ file=sys.stderr,
78
+ )
79
+ return EXIT_INCONCLUSIVE
80
+ try:
81
+ target = build_target(args.target)
82
+ limits: dict[str, object] = {
83
+ "discovery_runs": args.discovery_runs,
84
+ "reproduction_trials": args.replays,
85
+ "max_messages": args.max_messages,
86
+ "max_tool_calls": args.max_tool_calls,
87
+ "max_seconds": args.max_seconds,
88
+ "discovery_budget_per_objective": args.budget_per_objective,
89
+ "tester": args.tester,
90
+ "independence": args.independence,
91
+ }
92
+ ScanConfig(**limits) # type: ignore[arg-type]
93
+ attacks = default_attacks(target) if args.strategy in ("static", "both") else []
94
+ strategy = None
95
+ if args.strategy in ("adaptive", "both"):
96
+ attacker_model = build_model(args.attacker_model)
97
+ strategy = LLMAdaptiveStrategy(
98
+ model=attacker_model,
99
+ max_turns=args.max_turns,
100
+ max_episodes=args.max_episodes,
101
+ )
102
+ except (SpecError, ValueError) as exc:
103
+ print(f"error: {exc}", file=sys.stderr)
104
+ return EXIT_INCONCLUSIVE
105
+ try:
106
+ report = _run_until_done_or_cancelled(
107
+ lambda cancelled: run_scan(
108
+ target,
109
+ attacks,
110
+ ScanConfig(**limits, cancelled=cancelled), # type: ignore[arg-type]
111
+ strategy=strategy,
112
+ )
113
+ )
114
+ except ValueError as exc: # the runner refused the target or the attack list
115
+ print(f"error: {exc}", file=sys.stderr)
116
+ return EXIT_INCONCLUSIVE
117
+ assert isinstance(report, ScanReport)
118
+
119
+ paths = write_reports(
120
+ report,
121
+ Path(args.out),
122
+ Path(args.markdown) if args.markdown else None,
123
+ Path(args.html) if args.html else None,
124
+ )
125
+ if args.html:
126
+ open_for_a_person(Path(args.html), getattr(args, "no_open", False))
127
+ replay = replay_command(str(args.out), report.findings[0].id) if report.findings else ""
128
+ show_summary(report, paths, replay)
129
+ return {
130
+ "violations_verified": EXIT_VIOLATIONS,
131
+ "no_verified_violations": EXIT_NO_VERIFIED,
132
+ "inconclusive": EXIT_INCONCLUSIVE,
133
+ }[report.status]
134
+
135
+
136
+ def _scan_or_first_scan(args: argparse.Namespace) -> int:
137
+ if args.url and args.target:
138
+ print("error: give a URL for a first scan, or --target for a described target, not both", file=sys.stderr)
139
+ return EXIT_INCONCLUSIVE
140
+ if args.url:
141
+ from botsting.quick import run
142
+
143
+ return run(args)
144
+ return run_scan_command(args)
145
+
146
+
147
+ def _replay(args: argparse.Namespace) -> int:
148
+ try:
149
+ report = ScanReport.from_dict(json.loads(Path(args.report).read_text(encoding="utf-8")))
150
+ except (OSError, ValueError, KeyError, TypeError) as exc:
151
+ print(f"error: could not read report {args.report}: {exc}", file=sys.stderr)
152
+ return EXIT_INCONCLUSIVE
153
+ finding = next((f for f in report.findings if f.id == args.finding), None)
154
+ if finding is None:
155
+ known = ", ".join(f.id for f in report.findings) or "none"
156
+ print(f"error: no finding {args.finding!r} in this report (findings: {known})", file=sys.stderr)
157
+ return EXIT_INCONCLUSIVE
158
+ if args.trials < 1:
159
+ print("error: --trials must be at least 1", file=sys.stderr)
160
+ return EXIT_INCONCLUSIVE
161
+ try:
162
+ target = build_target(args.target or report.target)
163
+ except SpecError as exc:
164
+ print(f"error: {exc}", file=sys.stderr)
165
+ return EXIT_INCONCLUSIVE
166
+
167
+ result = run_to_completion(replay_finding(target, finding, args.trials))
168
+ verb = "leaked" if finding.kind == "disclosure" else "was violated"
169
+ print(
170
+ f"{finding.id} ({finding.attack_id}) against {target.spec}: {finding.slot_id} {verb} in "
171
+ f"{describe_rate(result.rate, 'replays from reset with fresh canaries')}."
172
+ )
173
+ changed = sorted(
174
+ key
175
+ for key in set(report.target_config) | set(result.target_config)
176
+ if report.target_config.get(key) != result.target_config.get(key)
177
+ )
178
+ if changed:
179
+ print("Note: this is not the configuration that was scanned. Changed: " + ", ".join(changed) + ".")
180
+ unknown = sorted(set(identity_unknown(report.target_config)) | set(identity_unknown(result.target_config)))
181
+ if unknown:
182
+ print(
183
+ f"Note: the target's {', '.join(unknown)} could not be read, then or now, so it is not known "
184
+ "whether this is the configuration that was scanned."
185
+ )
186
+ if result.unattributable:
187
+ print("Inconclusive: the tool ran, but that cannot be pinned on the planted text:")
188
+ print(f" {result.unattributable}")
189
+ return EXIT_INCONCLUSIVE
190
+ if result.rate.successes:
191
+ return EXIT_VIOLATIONS
192
+ if result.problems:
193
+ print("Inconclusive: no leak was observed, but that cannot be relied on:")
194
+ for problem in result.problems:
195
+ print(f" {problem}")
196
+ return EXIT_INCONCLUSIVE
197
+ print("What it reached still works by its legitimate route, and normal use still works.")
198
+ return EXIT_NO_VERIFIED
199
+
200
+
201
+ def _benchmark(args: argparse.Namespace) -> int:
202
+ try:
203
+ hardened = [build_target(spec) for spec in args.hardened]
204
+ controls = [build_target(spec) for spec in args.controls]
205
+ attacker_model = build_model(args.attacker_model)
206
+ strategy = LLMAdaptiveStrategy(
207
+ model=attacker_model,
208
+ max_turns=args.max_turns,
209
+ max_episodes=args.max_episodes,
210
+ )
211
+ except (SpecError, ValueError) as exc:
212
+ print(f"error: {exc}", file=sys.stderr)
213
+ return EXIT_INCONCLUSIVE
214
+
215
+ try:
216
+ report = run_to_completion(
217
+ compare_strategies(
218
+ hardened,
219
+ controls,
220
+ strategy,
221
+ budget_per_objective=args.budget_per_objective,
222
+ reproduction_trials=args.replays,
223
+ required_margin=args.margin,
224
+ max_seconds=args.max_seconds,
225
+ )
226
+ )
227
+ except ValueError as exc:
228
+ print(f"error: {exc}", file=sys.stderr)
229
+ return EXIT_INCONCLUSIVE
230
+
231
+ text = render_benchmark_markdown(report)
232
+ print(text, end="")
233
+ if args.out:
234
+ write_file(Path(args.out), json.dumps(report.to_dict(), indent=2))
235
+ print(f"Benchmark JSON: {args.out}")
236
+ return EXIT_NO_VERIFIED if report.passed else EXIT_VIOLATIONS
237
+
238
+
239
+ def _practice_server(args: argparse.Namespace) -> int:
240
+ import time
241
+
242
+ from botsting.practice_server import PracticeBot, practice_description, start, write_description
243
+ from botsting.targets.http import targets_file
244
+ from botsting.targets.registry import build_model
245
+
246
+ try:
247
+ bot = PracticeBot(args.variant, build_model(args.model))
248
+ server = start(bot, port=args.port)
249
+ except (SpecError, ValueError, OSError) as exc:
250
+ print(f"error: {exc}", file=sys.stderr)
251
+ return EXIT_FAILED
252
+ port = server.server_address[1]
253
+ print(f"Practice bot ({args.variant}) listening on http://127.0.0.1:{port}. Press Ctrl+C to stop.")
254
+ if args.write_config:
255
+ path = targets_file()
256
+ write_description(path, "practice", practice_description(port, args.variant))
257
+ print(f"Described it as target 'practice' in {path}. Scan it with: botsting scan --target http:practice")
258
+ try:
259
+ while True:
260
+ time.sleep(3600)
261
+ except KeyboardInterrupt:
262
+ server.shutdown()
263
+ return EXIT_OK
264
+
265
+
266
+ def build_parser() -> argparse.ArgumentParser:
267
+ parser = argparse.ArgumentParser(
268
+ prog="botsting",
269
+ formatter_class=argparse.RawDescriptionHelpFormatter,
270
+ description=(
271
+ "Evidence-first security testing for LLM applications.\n\n"
272
+ "Start here:\n"
273
+ " botsting demo see it work on a built-in practice bot, in a minute\n"
274
+ " botsting guide the lines to add to your own bot\n"
275
+ " botsting scan http://localhost:8000/chat scan your own bot, at its chat address\n"
276
+ " botsting doctor --target http:NAME when something is not working: what to fix next"
277
+ ),
278
+ )
279
+ parser.add_argument("--version", action="version", version=f"botsting {__version__}")
280
+ commands = parser.add_subparsers(dest="command", required=True)
281
+
282
+ # What a scan does, shared by `scan` and `ci`. Where the reports go is each command's own.
283
+ scan = options = argparse.ArgumentParser(add_help=False)
284
+ scan.add_argument("--target", help="for example toy:vulnerable, or http:NAME for a bot described in the targets file")
285
+ scan.add_argument(
286
+ "--strategy",
287
+ choices=("static", "adaptive", "both"),
288
+ default="static",
289
+ help="run the static attack list, the adaptive attacker, or both",
290
+ )
291
+ scan.add_argument(
292
+ "--attacker-model",
293
+ default="scripted-attacker",
294
+ help="model driving the adaptive attacker (scripted-attacker or ollama:<model>)",
295
+ )
296
+ scan.add_argument("--max-turns", type=int, default=3, help="maximum turns per adaptive conversation episode")
297
+ scan.add_argument("--max-episodes", type=int, default=4, help="maximum adaptive episodes per objective")
298
+ scan.add_argument(
299
+ "--budget-per-objective",
300
+ type=int,
301
+ default=None,
302
+ help="optional cap on discovery target messages per objective",
303
+ )
304
+ scan.add_argument("--discovery-runs", type=int, default=1, help="attempts per attack while searching")
305
+ scan.add_argument("--replays", type=int, default=5, help="replays of each attack that worked")
306
+ scan.add_argument("--max-messages", type=int, default=5000, help="stop after sending this many messages")
307
+ scan.add_argument("--max-tool-calls", type=int, default=500, help="stop once more than this many tool calls were recorded")
308
+ scan.add_argument("--max-seconds", type=float, default=3600, help="stop after this much time")
309
+ scan.add_argument(
310
+ "--tester",
311
+ default="",
312
+ help='who ran this scan, for example "Dana Levi, Example Audit"',
313
+ )
314
+ scan.add_argument(
315
+ "--independence",
316
+ choices=("self", "internal", "third-party"),
317
+ default="self",
318
+ help="independence of the tester from the team that built or operates the target",
319
+ )
320
+ scan = commands.add_parser(
321
+ "scan",
322
+ parents=[options],
323
+ help="attack a target and report what was proven",
324
+ description=(
325
+ "botsting scan http://localhost:8000/chat a first scan of a bot that carries the drop-in harness: "
326
+ "no description file is needed. botsting scan --target NAME a described target."
327
+ ),
328
+ )
329
+ scan.add_argument("url", nargs="?", help="the chat address of a bot that carries the drop-in harness")
330
+ scan.add_argument("--name", help="with a URL: the name to save the worked-out description under")
331
+ scan.add_argument("--field", help="with a URL: the request field that carries the message, if it is not found")
332
+ scan.add_argument("--session-field", help="with a URL: a request field for the conversation id, if the bot has one")
333
+ scan.add_argument("--reply", help="with a URL: a JSON pointer to the reply text, such as /data/answer")
334
+ scan.add_argument(
335
+ "--message",
336
+ help='with a URL: an ordinary request to send while working the bot out (default "Hello"); give one that '
337
+ "makes the bot read its notes or documents, so planted text there is tested",
338
+ )
339
+ scan.add_argument("--out", default="reports/scan.botsting.json", help="where to write the JSON report")
340
+ scan.add_argument("--markdown", help="also write a readable report to this path")
341
+ scan.add_argument("--html", help="also write a self-contained report to open in a browser or print")
342
+ scan.add_argument("--no-open", action="store_true", help="do not open the browser report when the scan ends")
343
+ scan.set_defaults(handler=_scan_or_first_scan)
344
+
345
+ rep = commands.add_parser("replay", help="replay a finding from a reset state with fresh canaries")
346
+ rep.add_argument("report", help="a JSON report written by scan")
347
+ rep.add_argument("--finding", required=True, help="finding id, for example F1")
348
+ rep.add_argument("--trials", type=int, default=5)
349
+ rep.add_argument("--target", help="replay against a different target, for example the fixed build")
350
+ rep.set_defaults(handler=_replay)
351
+
352
+ bench = commands.add_parser(
353
+ "benchmark",
354
+ help="compare static vs. adaptive attacks at equal per-objective target-message budgets",
355
+ )
356
+ bench.add_argument(
357
+ "--hardened",
358
+ nargs="+",
359
+ default=["hardened:keyword", "hardened:multiturn"],
360
+ help="held-out hardened target specs",
361
+ )
362
+ bench.add_argument(
363
+ "--controls",
364
+ nargs="*",
365
+ default=["hardened:keyword-fixed", "hardened:multiturn-fixed"],
366
+ help="fixed control target specs that must return no verified violations",
367
+ )
368
+ bench.add_argument("--attacker-model", default="scripted-attacker")
369
+ bench.add_argument("--budget-per-objective", type=int, default=8)
370
+ bench.add_argument("--max-turns", type=int, default=3)
371
+ bench.add_argument("--max-episodes", type=int, default=4)
372
+ bench.add_argument("--replays", type=int, default=3)
373
+ bench.add_argument("--margin", type=float, default=DEFAULT_MARGIN)
374
+ bench.add_argument("--max-seconds", type=float, default=300.0)
375
+ bench.add_argument("--out", help="optional path to write benchmark JSON")
376
+ bench.set_defaults(handler=_benchmark)
377
+
378
+ from botsting.authorize_cli import register as register_authorize
379
+
380
+ register_authorize(commands)
381
+
382
+ from botsting.seal import register as register_seal
383
+
384
+ register_seal(commands)
385
+
386
+ from botsting.egress_trap import register as register_trap
387
+
388
+ register_trap(commands)
389
+
390
+ from botsting.ci import register as register_ci
391
+
392
+ register_ci(commands, [options])
393
+
394
+ from botsting.mcp_server import register as register_mcp
395
+
396
+ register_mcp(commands)
397
+
398
+ from botsting.demo import register as register_demo
399
+
400
+ register_demo(commands)
401
+
402
+ from botsting.doctor import register as register_doctor
403
+
404
+ register_doctor(commands)
405
+
406
+ from botsting.presets import register as register_presets
407
+
408
+ register_presets(commands)
409
+
410
+ from botsting.sterility import register as register_sterility
411
+
412
+ register_sterility(commands)
413
+
414
+ key = commands.add_parser("harness-key", help="make a key for the drop-in test harness (botsting.harness)")
415
+ key.set_defaults(handler=_harness_key)
416
+
417
+ practice = commands.add_parser(
418
+ "practice-server",
419
+ help="serve the practice bot over HTTP on this machine, to try the HTTP adapter",
420
+ )
421
+ practice.add_argument("--variant", choices=["vulnerable", "hardened", "fixed"], default="vulnerable")
422
+ practice.add_argument("--port", type=int, default=8765)
423
+ practice.add_argument("--model", default="scripted", help="scripted, or ollama:<model name>")
424
+ practice.add_argument(
425
+ "--write-config", action="store_true",
426
+ help="add this server as target 'practice' to the targets file (botsting.targets.json)",
427
+ ) # fmt: skip
428
+ practice.set_defaults(handler=_practice_server)
429
+ return parser
430
+
431
+
432
+ def _harness_key(args: argparse.Namespace) -> int:
433
+ from botsting.harness import KEY_ENV, new_key
434
+
435
+ print(new_key())
436
+ print(
437
+ f"Set this as {KEY_ENV} on the deployment under test and in the environment where you run the scan. "
438
+ "Keep it off production unless you mean to test the real system (see the README).",
439
+ file=sys.stderr,
440
+ )
441
+ return EXIT_OK
442
+
443
+
444
+ def _print_anything() -> None:
445
+ """A bot may answer in any alphabet, and its words are printed in the summary. A Windows console or
446
+ pipe in a legacy code page cannot encode all of them, and would stop the command with an error
447
+ after the scan had finished. Characters it cannot show are replaced instead."""
448
+ for stream in (sys.stdout, sys.stderr):
449
+ reconfigure = getattr(stream, "reconfigure", None)
450
+ if callable(reconfigure):
451
+ try:
452
+ reconfigure(errors="replace")
453
+ except (ValueError, OSError): # a stream that is closed or was replaced by something else
454
+ pass
455
+
456
+
457
+ def main(argv: list[str] | None = None) -> int:
458
+ _print_anything()
459
+ args = build_parser().parse_args(argv)
460
+ return args.handler(args)
461
+
462
+
463
+ if __name__ == "__main__":
464
+ sys.exit(main())