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,148 @@
1
+ """`botsting authorize`: record who allows a target to be tested, and prove control of it.
2
+
3
+ botsting authorize https://staging.example.com --by "Dana Levi" \\
4
+ --scope "support bot on the staging site" --environment staging --days 30
5
+ botsting authorize --verify https://staging.example.com
6
+ botsting authorize --list
7
+
8
+ Exit codes: 0 done, 2 refused or failed.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import sys
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+
18
+ from botsting.core.authorization import (
19
+ CHALLENGE_PATH,
20
+ DEFAULT_STORE,
21
+ ENVIRONMENTS,
22
+ MAX_DAYS,
23
+ AuthorizationError,
24
+ AuthorizationStore,
25
+ check_proof,
26
+ new_authorization,
27
+ )
28
+ from botsting.exits import EXIT_FAILED, EXIT_OK
29
+
30
+
31
+ def register(commands: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
32
+ parser = commands.add_parser(
33
+ "authorize",
34
+ help="record who allows a target to be tested, and prove control of it",
35
+ description=(
36
+ "Nothing is sent to a target outside this process without an authorization: a named person, "
37
+ "a scope, an environment and an expiry, and, across a network, a token served by the target's "
38
+ "own site."
39
+ ),
40
+ )
41
+ parser.add_argument("origin", nargs="?", help="where the bot is reached, e.g. https://staging.example.com")
42
+ parser.add_argument("--by", help="the person who authorizes the test")
43
+ parser.add_argument("--scope", help="what may be tested, in a sentence")
44
+ parser.add_argument("--environment", choices=ENVIRONMENTS, help="which environment the origin is")
45
+ parser.add_argument("--days", type=int, default=30, help=f"how long it lasts, 1 to {MAX_DAYS} days (default 30)")
46
+ parser.add_argument(
47
+ "--tool", action="append", default=[], metavar="NAME",
48
+ help="a tool the scan may exercise (repeat for each); tools not named here cannot be tested",
49
+ ) # fmt: skip
50
+ parser.add_argument(
51
+ "--live-tool", action="append", default=[], metavar="NAME",
52
+ help=(
53
+ "a tool the test may carry out FOR REAL, inside the caps written in the bot's code "
54
+ "(repeat for each; implies --tool). Without this, tools are only recorded"
55
+ ),
56
+ ) # fmt: skip
57
+ parser.add_argument("--agent", default="", help="the one agent or bot id covered, if the target names one")
58
+ parser.add_argument("--tenant", default="", help="the one tenant or account covered, if the target names one")
59
+ parser.add_argument("--verify", metavar="ORIGIN", help="check that the origin serves the token, and record it")
60
+ parser.add_argument("--list", action="store_true", help="show the recorded authorizations")
61
+ parser.add_argument("--store", default=str(DEFAULT_STORE), help=f"where they are kept (default {DEFAULT_STORE})")
62
+ parser.set_defaults(handler=_authorize)
63
+
64
+
65
+ def _authorize(args: argparse.Namespace) -> int:
66
+ store = AuthorizationStore(Path(args.store))
67
+ try:
68
+ if args.list:
69
+ return _list(store)
70
+ if args.verify:
71
+ return _verify(store, args.verify)
72
+ return _create(store, args)
73
+ except (AuthorizationError, ValueError) as exc:
74
+ print(f"error: {exc}", file=sys.stderr)
75
+ return EXIT_FAILED
76
+
77
+
78
+ def _create(store: AuthorizationStore, args: argparse.Namespace) -> int:
79
+ missing = [flag for flag, value in (("origin", args.origin), ("--by", args.by), ("--scope", args.scope), ("--environment", args.environment)) if not value]
80
+ if missing:
81
+ print(f"error: also give {', '.join(missing)}", file=sys.stderr)
82
+ return EXIT_FAILED
83
+ authorization = new_authorization(
84
+ args.origin, args.by, args.scope, args.environment, args.days,
85
+ allowed_tools=[*args.tool, *args.live_tool], agent_id=args.agent, tenant=args.tenant,
86
+ live_tools=args.live_tool,
87
+ ) # fmt: skip
88
+ store.add(authorization)
89
+ print(f"Recorded: {authorization.authorized_by} authorizes testing {authorization.origin}")
90
+ print(f" scope: {authorization.scope}")
91
+ print(f" tools that may be exercised: {', '.join(authorization.allowed_tools) or 'none'}")
92
+ if authorization.live_tools:
93
+ print(f" tools that may be CARRIED OUT FOR REAL, inside the bot's caps: {', '.join(authorization.live_tools)}")
94
+ print(" Real money, messages or records may change, up to those caps. Check the caps in the bot's code first.")
95
+ if authorization.agent_id or authorization.tenant:
96
+ print(f" agent: {authorization.agent_id or 'any'}; tenant: {authorization.tenant or 'any'}")
97
+ print(f" environment: {authorization.environment}, until {authorization.expires_at}")
98
+ if authorization.environment == "production":
99
+ print(" Note: this is a production system. Tests send hostile messages and may trigger the bot's tools.")
100
+ if not authorization.needs_proof:
101
+ print("This origin is on this machine, so no proof of control is needed. Scans may now run against it.")
102
+ return EXIT_OK
103
+ print()
104
+ print("To prove you control this origin, serve this exact line as plain text at")
105
+ print(f" {authorization.challenge_url()}")
106
+ print()
107
+ print(f" {authorization.challenge_line()}")
108
+ print()
109
+ print(f"Then run: botsting authorize --verify {authorization.origin}")
110
+ print(f"Keep it there while you scan: it is checked again each time a scan starts. Store: {store.path}")
111
+ return EXIT_OK
112
+
113
+
114
+ def _verify(store: AuthorizationStore, origin: str) -> int:
115
+ authorization = store.find(origin)
116
+ if authorization is None:
117
+ print(f"error: no authorization for {origin}; create one first", file=sys.stderr)
118
+ return EXIT_FAILED
119
+ now = datetime.now(UTC)
120
+ if authorization.expired(now):
121
+ print(f"error: the authorization for {authorization.origin} expired at {authorization.expires_at}", file=sys.stderr)
122
+ return EXIT_FAILED
123
+ result = check_proof(authorization)
124
+ if not result.ok:
125
+ print(f"Not verified: {result.detail}", file=sys.stderr)
126
+ print(f"Serve '{authorization.challenge_line()}' at {CHALLENGE_PATH} over https and try again.", file=sys.stderr)
127
+ return EXIT_FAILED
128
+ store.mark_verified(authorization.origin, now)
129
+ print(f"Verified: {result.detail}. Scans of {authorization.origin} may run until {authorization.expires_at}.")
130
+ return EXIT_OK
131
+
132
+
133
+ def _list(store: AuthorizationStore) -> int:
134
+ authorizations = store.load()
135
+ if not authorizations:
136
+ print(f"No authorizations recorded in {store.path}.")
137
+ return EXIT_OK
138
+ now = datetime.now(UTC)
139
+ for a in authorizations:
140
+ if a.expired(now):
141
+ state = "expired"
142
+ elif not a.needs_proof:
143
+ state = "ready (on this machine)"
144
+ else:
145
+ state = f"verified {a.verified_at}" if a.verified_at else "not verified yet"
146
+ print(f"{a.origin} {state}")
147
+ print(f" by {a.authorized_by}; {a.environment}; until {a.expires_at}; scope: {a.scope}")
148
+ return EXIT_OK
botsting/ci.py ADDED
@@ -0,0 +1,122 @@
1
+ """`botsting ci`: one command for a build pipeline.
2
+
3
+ It runs a scan, writes the JSON, readable and browser reports into one directory, seals
4
+ that directory into an evidence bundle, and exits in a way a pipeline can act on:
5
+
6
+ botsting ci --target http:staging --fail-on violations
7
+
8
+ On GitHub Actions it also adds the readable report to the job summary and sets the
9
+ outputs `status`, `findings`, `seal` and `bundle`. The same command works on any
10
+ other pipeline; those two extras are simply skipped.
11
+
12
+ `--fail-on` chooses what fails the build:
13
+ violations (default) a proven finding fails it; an inconclusive scan does not
14
+ inconclusive a proven finding or an inconclusive scan fails it
15
+ never nothing fails it; read the report
16
+
17
+ A scan that could not run at all (a target that is not described, no authorization)
18
+ fails the build under both `violations` and `inconclusive`: a pipeline that tests
19
+ nothing must not look green. So does a scan whose evidence could not be sealed.
20
+
21
+ An inconclusive scan is not a clean one: it means the scan could not show that its
22
+ attacks would have been seen. With the default, the summary says so in its first line.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ from botsting.exits import EXIT_INCONCLUSIVE, EXIT_NO_VERIFIED, EXIT_OK, EXIT_VIOLATIONS
34
+ from botsting.seal import SealError, seal
35
+
36
+ FAIL_ON = ("violations", "inconclusive", "never")
37
+ _SUMMARY_LIMIT = 900_000 # GitHub refuses step summaries over 1 MB
38
+
39
+
40
+ def register(commands: argparse._SubParsersAction, scan_parents: list[argparse.ArgumentParser]) -> None: # type: ignore[type-arg]
41
+ parser = commands.add_parser(
42
+ "ci",
43
+ parents=scan_parents,
44
+ help="scan, write every report, seal the evidence, and exit for a build pipeline",
45
+ )
46
+ parser.add_argument("--dir", default="botsting-report", help="where the reports go (default botsting-report)")
47
+ parser.add_argument("--fail-on", choices=FAIL_ON, default="violations", help="what fails the build")
48
+ parser.set_defaults(handler=_ci)
49
+
50
+
51
+ def _append(path: str | None, text: str) -> None:
52
+ if not path:
53
+ return
54
+ try:
55
+ with open(path, "a", encoding="utf-8") as file:
56
+ file.write(text)
57
+ except OSError as error:
58
+ print(f"note: could not write to {path}: {error}", file=sys.stderr)
59
+
60
+
61
+ def _ci(args: argparse.Namespace) -> int:
62
+ from botsting.cli import run_scan_command
63
+
64
+ directory = Path(args.dir)
65
+ if directory.exists() and not directory.is_dir():
66
+ print(f"error: {directory} is a file; --dir must be a new or empty folder", file=sys.stderr)
67
+ return EXIT_INCONCLUSIVE
68
+ if directory.exists() and any(directory.iterdir()):
69
+ print(f"error: {directory} is not empty; give an empty or new --dir so old evidence is not mixed in", file=sys.stderr)
70
+ return EXIT_INCONCLUSIVE
71
+ args.out = str(directory / "scan.botsting.json")
72
+ args.markdown = str(directory / "report.md")
73
+ args.html = str(directory / "report.html")
74
+ code = run_scan_command(args)
75
+
76
+ status, findings = "not_run", 0
77
+ report = Path(args.out)
78
+ if report.exists():
79
+ data = json.loads(report.read_text(encoding="utf-8"))
80
+ status, findings = str(data.get("status", "unknown")), len(data.get("findings", []))
81
+
82
+ value, bundle, unsealed = "", directory.with_name(directory.name + ".sealed.zip"), False
83
+ if directory.is_dir() and any(directory.iterdir()):
84
+ try:
85
+ value = seal(directory, bundle)
86
+ print(f"Evidence bundle: {bundle}")
87
+ print(f"Seal: {value}")
88
+ except SealError as error:
89
+ unsealed = True
90
+ print(f"error: the evidence was not sealed: {error}", file=sys.stderr)
91
+
92
+ headline = {
93
+ EXIT_VIOLATIONS: f"BotSting: {findings} proven finding(s).",
94
+ EXIT_NO_VERIFIED: "BotSting: no verified violations under the tested conditions.",
95
+ }.get(code, "BotSting: INCONCLUSIVE. This is not a clean result; the report says what could not be shown.")
96
+ if status == "not_run":
97
+ headline = "BotSting: NOT RUN. Nothing was tested; see the error above."
98
+ summary = f"## {headline}\n\n"
99
+ if value:
100
+ summary += f"Evidence seal: `{value}`\n\n"
101
+ readable = Path(args.markdown)
102
+ if readable.exists():
103
+ text = readable.read_text(encoding="utf-8")
104
+ if len(text) > _SUMMARY_LIMIT:
105
+ text = text[:_SUMMARY_LIMIT] + "\n\n(The report is longer; see the uploaded files.)\n"
106
+ summary += text
107
+ _append(os.environ.get("GITHUB_STEP_SUMMARY"), summary)
108
+ _append(
109
+ os.environ.get("GITHUB_OUTPUT"),
110
+ f"status={status}\nfindings={findings}\nseal={value}\nbundle={bundle if value else ''}\n",
111
+ )
112
+ print(headline)
113
+
114
+ if args.fail_on == "never":
115
+ return EXIT_OK
116
+ if code == EXIT_VIOLATIONS:
117
+ return EXIT_VIOLATIONS
118
+ if status == "not_run" or unsealed:
119
+ return EXIT_INCONCLUSIVE # nothing was tested, or the evidence could not be sealed
120
+ if code != EXIT_NO_VERIFIED and args.fail_on == "inconclusive":
121
+ return EXIT_INCONCLUSIVE
122
+ return EXIT_NO_VERIFIED