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/core/stats.py ADDED
@@ -0,0 +1,42 @@
1
+ """Success rates with an honest interval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ from botsting.core.models import Rate
8
+
9
+ _Z95 = 1.959963984540054
10
+
11
+
12
+ def wilson_interval(successes: int, trials: int) -> tuple[float, float] | None:
13
+ """Two-sided 95% Wilson score interval for a binomial proportion.
14
+
15
+ Chosen over the normal approximation because it stays inside [0, 1] and behaves at
16
+ 0 of n and n of n, which are the common cases here. Returns None for zero trials.
17
+ """
18
+ if trials <= 0:
19
+ return None
20
+ if not 0 <= successes <= trials:
21
+ raise ValueError(f"successes must be between 0 and trials, got {successes} of {trials}")
22
+ p = successes / trials
23
+ z2 = _Z95 * _Z95
24
+ denominator = 1 + z2 / trials
25
+ centre = (p + z2 / (2 * trials)) / denominator
26
+ half = (_Z95 * math.sqrt(p * (1 - p) / trials + z2 / (4 * trials * trials))) / denominator
27
+ low = 0.0 if successes == 0 else max(0.0, centre - half)
28
+ high = 1.0 if successes == trials else min(1.0, centre + half)
29
+ return (low, high)
30
+
31
+
32
+ def make_rate(successes: int, trials: int, errors: int = 0, contaminated: int = 0) -> Rate:
33
+ """A Rate over the trials that could be judged. Errored and discarded trials are reported, not counted."""
34
+ interval = wilson_interval(successes, trials)
35
+ return Rate(
36
+ successes=successes,
37
+ trials=trials,
38
+ errors=errors,
39
+ contaminated=contaminated,
40
+ interval_low=None if interval is None else interval[0],
41
+ interval_high=None if interval is None else interval[1],
42
+ )
botsting/demo.py ADDED
@@ -0,0 +1,215 @@
1
+ """`botsting demo`: see the whole thing work in a minute, on this machine only.
2
+
3
+ It serves the built-in practice support bot twice, a vulnerable build and a fixed one,
4
+ wired with the drop-in harness exactly as a real bot would be (see harness.py). It then
5
+ scans both over HTTP and writes the reports and a sealed evidence bundle for each:
6
+
7
+ botsting demo # tools are recorded, never run
8
+ botsting demo --live # small refunds really run, inside a cap
9
+
10
+ With `--live` the practice refund tool carries `Cap(max={"amount": LIVE_CAP}, ...)`.
11
+ "Really run" here means a line in an in-memory ledger: the practice bot cannot move
12
+ money. The point is to show the mechanism: a refund inside the cap is carried out, and
13
+ one outside it is recorded with the cap that stopped it.
14
+
15
+ Nothing leaves this machine, and nothing is written outside the report folder. The
16
+ permission the scans run under is made for this one run and kept in memory; it names
17
+ this command as the authorizer, covers only the two local addresses it just opened,
18
+ and is not saved to the authorizations file.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import asyncio
25
+ import hashlib
26
+ import json
27
+ import os
28
+ import threading
29
+ from collections.abc import Callable, Iterable, Iterator
30
+ from contextlib import contextmanager
31
+ from datetime import UTC, datetime
32
+ from pathlib import Path
33
+ from typing import Any
34
+ from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server
35
+
36
+ import botsting.harness as pp
37
+ from botsting.core.models import ToolCall
38
+ from botsting.exits import EXIT_FAILED, EXIT_OK
39
+ from botsting.llm.scripted import ScriptedModel
40
+ from botsting.targets.toy import REFUND_TOOL, ToyTarget
41
+
42
+ LIVE_CAP = 60 # the practice bot's refunds are whole numbers; its attacks ask for more and for less than this
43
+ LIVE_CALLS = 50
44
+
45
+
46
+ class HarnessPracticeBot(ToyTarget):
47
+ """The practice bot as an owner would wire it: once its own checks allow a refund, the refund
48
+ goes through a function marked with @pp.action. It keeps no recorder of its own."""
49
+
50
+ def __init__(self, variant: str, live: bool = False) -> None:
51
+ super().__init__(variant=variant, model=ScriptedModel(), spec=f"toy:{variant}") # type: ignore[arg-type]
52
+ self.carried_out: list[tuple[str, int]] = [] # refunds that "really" ran, in a --live demo
53
+ cap = pp.Cap(max={"amount": LIVE_CAP}, calls=LIVE_CALLS) if live else None
54
+
55
+ @pp.action(REFUND_TOOL, result=lambda order_id, amount: f"refund of {amount} on order {order_id} recorded", live=cap)
56
+ def refund(order_id: str, amount: int) -> str:
57
+ self.carried_out.append((order_id, amount))
58
+ return f"refund of {amount} on order {order_id} carried out"
59
+
60
+ self._refund = refund
61
+
62
+ def _issue_refund(self, authorization: tuple[str, int] | None, order_id: str, amount: int) -> ToolCall:
63
+ call = super()._issue_refund(authorization, order_id, amount)
64
+ if call.accepted:
65
+ self._refund(order_id, amount)
66
+ return call
67
+
68
+
69
+ def harness_app(bot: HarnessPracticeBot) -> Any:
70
+ """The practice bot as a web app, wrapped by the harness. One conversation per session id."""
71
+ state: dict[str, Any] = {"planted": None, "sessions": {}}
72
+ lock = threading.Lock()
73
+
74
+ def app(environ: dict[str, Any], start_response: Callable[..., Any]) -> Iterable[bytes]:
75
+ def answer(status: str, payload: Any) -> list[bytes]:
76
+ data = json.dumps(payload).encode()
77
+ start_response(status, [("Content-Type", "application/json"), ("Content-Length", str(len(data)))])
78
+ return [data]
79
+
80
+ try:
81
+ length = int(environ.get("CONTENT_LENGTH") or 0)
82
+ body = json.loads(environ["wsgi.input"].read(min(length, 100_000)) or b"{}")
83
+ session_id, user, message = body["session_id"], body["user"], body["message"]
84
+ except (ValueError, KeyError, TypeError):
85
+ return answer("400 Bad Request", {"error": "send session_id, user and message as JSON"})
86
+ if environ.get("PATH_INFO") != "/chat" or not pp.active():
87
+ # This demo bot has no real users: outside a test session it has nothing to say.
88
+ return answer("404 Not Found", {"error": "the demo bot only answers BotSting test sessions at /chat"})
89
+ with lock:
90
+ planted = (
91
+ {slot.id: pp.planted(slot.id) for slot in bot.slots()},
92
+ {point.id: pp.content(point.id) for point in bot.injection_points() if pp.content(point.id)},
93
+ )
94
+ if planted != state["planted"]: # a new attempt: new fake secrets, so start from a clean state
95
+ asyncio.run(bot.reset(*planted))
96
+ state["planted"], state["sessions"] = planted, {}
97
+ sessions = state["sessions"]
98
+ if session_id not in sessions:
99
+ sessions[session_id] = asyncio.run(bot.open_session(user))
100
+ reply = asyncio.run(sessions[session_id].send(message))
101
+ return answer("200 OK", {"reply": reply.text})
102
+
103
+ return pp.wrap(app)
104
+
105
+
106
+ class _Quiet(WSGIRequestHandler):
107
+ def log_message(self, format: str, *args: object) -> None:
108
+ pass
109
+
110
+
111
+ def serve(bot: HarnessPracticeBot, port: int = 0) -> WSGIServer:
112
+ """Serve the wrapped practice bot on this machine in a background thread."""
113
+ server = make_server("127.0.0.1", port, harness_app(bot), handler_class=_Quiet)
114
+ threading.Thread(target=server.serve_forever, daemon=True).start()
115
+ return server
116
+
117
+
118
+ def description(port: int, variant: str, live: bool = False) -> dict[str, Any]:
119
+ """The target description for a served HarnessPracticeBot."""
120
+ from botsting.practice_server import practice_description
121
+
122
+ raw = practice_description(port, variant)
123
+ del raw["reset"], raw["chat"]["tool_calls_pointer"]
124
+ raw["harness"] = "sdk"
125
+ if live:
126
+ raw["live_actions"] = [REFUND_TOOL]
127
+ return raw
128
+
129
+
130
+ @contextmanager
131
+ def _environment(**values: str) -> Iterator[None]:
132
+ before = {name: os.environ.get(name) for name in values}
133
+ os.environ.update(values)
134
+ try:
135
+ yield
136
+ finally:
137
+ for name, value in before.items():
138
+ if value is None:
139
+ os.environ.pop(name, None)
140
+ else:
141
+ os.environ[name] = value
142
+
143
+
144
+ def _demo(args: argparse.Namespace) -> int:
145
+ from botsting.attacks.library import default_attacks
146
+ from botsting.core.authorization import new_authorization
147
+ from botsting.core.runner import ScanConfig, run_scan, run_to_completion
148
+ from botsting.reporting import open_for_a_person, summary, write_reports
149
+ from botsting.seal import seal
150
+ from botsting.targets.http import HttpTarget, parse_config
151
+
152
+ directory = Path(args.dir)
153
+ if directory.exists() and any(directory.iterdir()):
154
+ print(f"error: {directory} is not empty; give a new or empty --dir")
155
+ return EXIT_FAILED
156
+ switches = {pp.KEY_ENV: pp.new_key()}
157
+ if args.live:
158
+ switches[pp.LIVE_ENV] = REFUND_TOOL
159
+ print("BotSting demo. Everything runs on this machine; nothing is sent anywhere else.")
160
+ with _environment(**switches):
161
+ for variant in ("vulnerable", "fixed"):
162
+ bot = HarnessPracticeBot(variant, live=args.live)
163
+ server = serve(bot)
164
+ try:
165
+ origin = f"http://127.0.0.1:{server.server_address[1]}"
166
+ permission = new_authorization(
167
+ origin, "the botsting demo command", "the built-in practice bot on this machine", "test", 1,
168
+ datetime.now(UTC), allowed_tools=(REFUND_TOOL,), live_tools=(REFUND_TOOL,) if args.live else (),
169
+ ) # fmt: skip
170
+ raw = description(server.server_address[1], variant, args.live)
171
+ digest = hashlib.sha256(json.dumps(raw, sort_keys=True, separators=(",", ":")).encode()).hexdigest()[:16]
172
+ config = parse_config(f"practice-{variant}", raw, digest)
173
+ target = HttpTarget(config, f"http:practice-{variant}", permission)
174
+ report = run_to_completion(
175
+ run_scan(target, default_attacks(target), ScanConfig(reproduction_trials=args.replays))
176
+ )
177
+ finally:
178
+ server.shutdown()
179
+ server.server_close()
180
+ folder = directory / variant
181
+ out = folder / "scan.botsting.json"
182
+ write_reports(report, out, folder / "report.md", folder / "report.html")
183
+ value = seal(folder, directory / f"{variant}.sealed.zip")
184
+ print()
185
+ print(f"== The {variant} build ==")
186
+ print(summary(report))
187
+ if args.live:
188
+ kept = all(amount <= LIVE_CAP for _, amount in bot.carried_out)
189
+ print(
190
+ f"Refunds really carried out (a line in the practice ledger): {len(bot.carried_out)}, "
191
+ f"{'all' if kept else 'NOT all'} within the cap of {LIVE_CAP}."
192
+ )
193
+ if args.live:
194
+ stopped = json.dumps(report.to_dict()).count("[not run: ")
195
+ print(f"Tool calls stopped by the cap and kept as evidence: {stopped}.")
196
+ print(f"Open: {(folder / 'report.html').resolve()}")
197
+ print(f"Sealed evidence: {(directory / f'{variant}.sealed.zip').resolve()} seal {value}")
198
+ if variant == "vulnerable":
199
+ open_for_a_person(folder / "report.html", args.no_open)
200
+ print()
201
+ print("The vulnerable build shows what a proven finding looks like; the fixed build shows what you see when nothing is found.")
202
+ print("To wire your own bot the same way, run: botsting guide")
203
+ return EXIT_OK
204
+
205
+
206
+ def register(commands: Any) -> None:
207
+ parser = commands.add_parser("demo", help="scan the built-in practice bot, vulnerable and fixed, on this machine")
208
+ parser.add_argument("--dir", default="botsting-demo", help="where the reports go (default botsting-demo)")
209
+ parser.add_argument("--replays", type=int, default=2, help="replays of each attack that worked (default 2)")
210
+ parser.add_argument(
211
+ "--live", action="store_true",
212
+ help=f"let the practice refund tool really run for refunds up to {LIVE_CAP} (a ledger line; no money exists)",
213
+ ) # fmt: skip
214
+ parser.add_argument("--no-open", action="store_true", help="do not open the report in a browser")
215
+ parser.set_defaults(handler=_demo)
botsting/doctor.py ADDED
@@ -0,0 +1,271 @@
1
+ """`botsting doctor`: check a bot's setup step by step and say what to do next.
2
+
3
+ botsting doctor --target http:staging
4
+
5
+ It walks the same gates a scan does, in order, and stops explaining at the first one
6
+ that is not passed, with the command or change that fixes it:
7
+
8
+ 1. the description is the target described, and does the description parse?
9
+ 2. what it protects does it name at least one secret or tool rule, and a normal-use check?
10
+ 3. credentials are the environment variables its headers use set?
11
+ 4. the harness key (drop-in harness only) is the key set here?
12
+ 5. authorization has a person authorized this address, and does it cover the tools?
13
+ deployment settings (with --env-file) does the deployment's configuration hold production keys?
14
+ 6. proof of control (across a network) does the address still serve its token?
15
+ 7. the harness (drop-in harness only) does the bot confirm test mode?
16
+ 8. a legitimate run can each secret be fetched by someone allowed it, and does normal use work?
17
+
18
+ Nothing hostile is sent. Steps 6 to 8 talk to the bot, so they run only after step 5:
19
+ the same rule as a scan. Step 8 sends only the description's own control prompts and
20
+ normal-use prompts, as the users allowed to send them; it is the check a scan makes
21
+ before its first attack. `--offline` stops after step 5.
22
+
23
+ Exit codes: 0 ready to scan, 2 something to fix.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import os
30
+ import re
31
+ from collections.abc import Callable
32
+ from typing import Any
33
+
34
+ from botsting.exits import EXIT_FAILED, EXIT_OK
35
+
36
+ _ENV = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
37
+ # Header names that carry a credential. A header that only says who the test user is (X-User: bob) is not one.
38
+ _SECRET_HEADER = re.compile(r"authorization|cookie|token|secret|password|api[-_]?key|(^|[-_])key($|[-_])|signature", re.IGNORECASE)
39
+
40
+
41
+ class _Report:
42
+ def __init__(self, out: Callable[[str], None]) -> None:
43
+ self.out = out
44
+ self.failed = False
45
+
46
+ def ok(self, step: str, detail: str) -> None:
47
+ self.out(f" ok {step}: {detail}")
48
+
49
+ def note(self, step: str, detail: str) -> None:
50
+ self.out(f" note {step}: {detail}")
51
+
52
+ def fix(self, step: str, problem: str, how: str) -> None:
53
+ self.failed = True
54
+ self.out(f" FIX {step}: {problem}")
55
+ for line in how.splitlines():
56
+ self.out(f" {line}")
57
+
58
+
59
+ def diagnose(spec: str, offline: bool = False, out: Callable[[str], None] = print, env_files: tuple[str, ...] = ()) -> bool:
60
+ """Run the checks, printing through `out`. Returns True when the target is ready to scan.
61
+
62
+ `env_files` are exports of the deployment's own settings (never this machine's): they are checked
63
+ for production keys, by name and known prefix only."""
64
+ from botsting.core.authorization import (
65
+ AuthorizationError,
66
+ confirm_proof,
67
+ require_authorized,
68
+ )
69
+ from botsting.core.runner import Meter, preflight
70
+ from botsting.targets.base import (
71
+ TargetError,
72
+ UnsafeTargetError,
73
+ require_contained_tools,
74
+ )
75
+ from botsting.targets.registry import SpecError, build_target
76
+
77
+ report = _Report(out)
78
+ out(f"Checking {spec}")
79
+
80
+ # 1. The description.
81
+ try:
82
+ target: Any = build_target(spec)
83
+ except SpecError as error:
84
+ report.fix(
85
+ "description", str(error), "Describe the bot in botsting.targets.json. `botsting guide` shows the format."
86
+ )
87
+ return False
88
+ config = getattr(target, "config", None)
89
+ if config is None:
90
+ report.ok("description", "a built-in practice bot; it runs inside this process and needs no setup")
91
+ return True
92
+ report.ok("description", f"{config.name} at {config.origin}")
93
+
94
+ # 2. What it protects.
95
+ if not config.slots and not config.tool_rules and not config.injection_points:
96
+ report.fix(
97
+ "what it protects",
98
+ "the description names no secret slot, tool rule or injection point, so a scan has nothing to prove",
99
+ 'Add at least one entry under "slots" or "tool_rules".',
100
+ )
101
+ else:
102
+ report.ok(
103
+ "what it protects",
104
+ f"{len(config.slots)} secret slot(s), {len(config.tool_rules)} tool rule(s), "
105
+ f"{len(config.injection_points)} injection point(s)",
106
+ )
107
+ if not config.task_checks:
108
+ report.note(
109
+ "normal use", 'no "task_checks": add one ordinary request, so a bot that refuses everything is not called safe'
110
+ )
111
+
112
+ # 3. Credentials.
113
+ wanted = sorted({name for p in config.principals.values() for value in p.headers.values() for name in _ENV.findall(value)})
114
+ missing = [name for name in wanted if not os.environ.get(name)]
115
+ if missing:
116
+ report.fix(
117
+ "credentials", f"not set in this environment: {', '.join(missing)}", "Set each to the test account's credential."
118
+ )
119
+ elif wanted:
120
+ report.ok("credentials", f"{len(wanted)} environment variable(s) set")
121
+ written = [
122
+ n
123
+ for n, p in config.principals.items()
124
+ if any(v and "${" not in v and _SECRET_HEADER.search(k) for k, v in p.headers.items())
125
+ ]
126
+ if written:
127
+ report.note("credentials", f"a credential for {', '.join(written)} is written out in the file; use ${{NAME}} to keep it out")
128
+
129
+ # 4. The harness key.
130
+ sdk = config.harness == "sdk"
131
+ if sdk:
132
+ try:
133
+ target.harness_key()
134
+ report.ok("harness key", f"{config.harness_key_env} is set here")
135
+ except TargetError as error:
136
+ report.fix(
137
+ "harness key",
138
+ str(error),
139
+ f"Run `botsting harness-key`, then set {config.harness_key_env} here and on the deployment under test.",
140
+ )
141
+
142
+ # 5. Authorization.
143
+ tools = sorted({r.tool for r in config.tool_rules} | {t for p in config.injection_points for t in p.forbidden_tools})
144
+ flags = "".join(f" --tool {tool}" for tool in tools) + "".join(f" --live-tool {tool}" for tool in config.live_actions)
145
+ command = f'botsting authorize {config.origin} --by "YOUR NAME" --scope "what may be tested" --environment staging{flags}'
146
+ proof = None
147
+ try:
148
+ proof = require_authorized(target)
149
+ require_contained_tools(target)
150
+ record = target.authorization
151
+ report.ok(
152
+ "authorization",
153
+ f"by {record.authorized_by}, {record.environment}, until {record.expires_at}"
154
+ + (f"; may carry out for real: {', '.join(record.live_tools)}" if record.live_tools else ""),
155
+ )
156
+ except (AuthorizationError, UnsafeTargetError) as error:
157
+ how = "A person who may allow this test runs:\n" + command
158
+ if "has not been verified" in str(error):
159
+ how = (
160
+ f"Serve the token (see `botsting authorize --list`), then run:\nbotsting authorize --verify {config.origin}"
161
+ )
162
+ report.fix("authorization", str(error), how)
163
+ out(" Stopped here: nothing is sent to a bot without an authorization.")
164
+ return False
165
+ # The deployment's own settings, if the owner exported them: no production keys on a test deployment.
166
+ if env_files:
167
+ from botsting.sterility import EnvFileError, check, read_env_file
168
+
169
+ try:
170
+ variables: dict[str, str] = {}
171
+ for path in env_files:
172
+ variables.update(read_env_file(path))
173
+ except EnvFileError as error:
174
+ report.fix("deployment settings", str(error), "Give an env file of KEY=value lines exported from the deployment.")
175
+ else:
176
+ sterile = check(variables)
177
+ live = [f for f in sterile.findings if f.severity == "live" and not f.allowed]
178
+ if not live:
179
+ report.ok(
180
+ "deployment settings",
181
+ f"{sterile.checked_count} variable(s) checked, no production signal; "
182
+ f"{sterile.unknown_count} could not be told apart and are worth a look",
183
+ )
184
+ elif target.authorization.environment == "production":
185
+ report.note(
186
+ "deployment settings",
187
+ f"{len(live)} production signal(s), as expected for a test of the real system: "
188
+ + ", ".join(f.name for f in live),
189
+ )
190
+ else:
191
+ report.fix(
192
+ "deployment settings",
193
+ f"this {target.authorization.environment} deployment holds production settings: "
194
+ + ", ".join(f"{f.name} ({f.reason})" for f in live),
195
+ "Replace each with a test value before scanning, or a test could reach real systems.\n"
196
+ "Details: botsting sterile-check --env-file <file>",
197
+ )
198
+ if report.failed:
199
+ out(" Stopped here: fix the points above, then run this again.")
200
+ return False
201
+ if offline:
202
+ out(" Offline checks passed. Run without --offline to check the bot itself.")
203
+ return True
204
+
205
+ async def online() -> None:
206
+ # 6. Proof of control.
207
+ if proof is not None:
208
+ try:
209
+ await confirm_proof(proof, fresh=True)
210
+ report.ok("proof of control", f"{config.origin} serves its token")
211
+ except AuthorizationError as error:
212
+ report.fix(
213
+ "proof of control",
214
+ str(error),
215
+ "Serve the token line as plain text at /.well-known/botsting-challenge.txt. With the drop-in\n"
216
+ "harness, set BOTSTING_CHALLENGE on the deployment to that line and it is served for you.",
217
+ )
218
+ return
219
+ else:
220
+ report.ok("proof of control", "not needed for a bot on this machine")
221
+ # 7. The harness.
222
+ if sdk:
223
+ try:
224
+ await target.reset({})
225
+ report.ok("harness", "the bot confirmed test mode for a signed session")
226
+ except TargetError as error:
227
+ report.fix(
228
+ "harness",
229
+ str(error),
230
+ f"Check that the app is wrapped (`app = pp.wrap(app)`), that it is deployed, and that\n"
231
+ f"{config.harness_key_env} on the deployment is the same key as here.",
232
+ )
233
+ return
234
+ # 8. A legitimate run: what a scan checks before its first attack.
235
+ checks = await preflight(target, Meter())
236
+ for status in checks.slots:
237
+ if status.state == "reachable":
238
+ report.ok(f"legitimate use of {status.slot_id}", "works by its allowed route")
239
+ else:
240
+ report.fix(
241
+ f"legitimate use of {status.slot_id}",
242
+ f"{status.state}: {status.detail}",
243
+ "The control prompt must make the bot give this secret, or carry out this tool, for the user allowed it.\n"
244
+ "Check where pp.planted(...) is placed, that the tool carries @pp.action, and the control_prompt's wording.",
245
+ )
246
+ for task in checks.tasks:
247
+ if task.passed:
248
+ report.ok(f"normal use ({task.task_id})", "the expected answer came back")
249
+ else:
250
+ report.fix(
251
+ f"normal use ({task.task_id})", task.detail, "Check the prompt and expect_substring of this task check."
252
+ )
253
+
254
+ asyncio.run(online())
255
+ if report.failed:
256
+ return False
257
+ out(f" Ready. Scan it with: botsting scan --target {spec} --html report.html")
258
+ return True
259
+
260
+
261
+ def register(commands: Any) -> None:
262
+ parser = commands.add_parser("doctor", help="check a bot's setup step by step and say what to do next")
263
+ parser.add_argument("--target", required=True, help="for example http:staging")
264
+ parser.add_argument("--offline", action="store_true", help="check only what needs no contact with the bot")
265
+ parser.add_argument(
266
+ "--env-file", action="append", default=[], metavar="PATH",
267
+ help="an export of the deployment's settings, checked for production keys (names and known prefixes only)",
268
+ ) # fmt: skip
269
+ parser.set_defaults(
270
+ handler=lambda args: EXIT_OK if diagnose(args.target, args.offline, env_files=tuple(args.env_file)) else EXIT_FAILED
271
+ )