botsting 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- botsting/__init__.py +3 -0
- botsting/__main__.py +8 -0
- botsting/attacks/__init__.py +0 -0
- botsting/attacks/adaptive.py +495 -0
- botsting/attacks/library.py +239 -0
- botsting/attacks/pyrit_adapter.py +227 -0
- botsting/attacks/strategy.py +157 -0
- botsting/authorize_cli.py +148 -0
- botsting/ci.py +122 -0
- botsting/cli.py +464 -0
- botsting/console.py +240 -0
- botsting/core/__init__.py +0 -0
- botsting/core/authorization.py +550 -0
- botsting/core/benchmark.py +199 -0
- botsting/core/canary.py +80 -0
- botsting/core/judge.py +175 -0
- botsting/core/matcher.py +367 -0
- botsting/core/meter.py +228 -0
- botsting/core/models.py +560 -0
- botsting/core/preflight.py +283 -0
- botsting/core/replay.py +145 -0
- botsting/core/runner.py +39 -0
- botsting/core/scan.py +917 -0
- botsting/core/stats.py +42 -0
- botsting/demo.py +215 -0
- botsting/doctor.py +271 -0
- botsting/egress_trap.py +243 -0
- botsting/exits.py +38 -0
- botsting/frameworks.py +453 -0
- botsting/harness.py +893 -0
- botsting/harness_tools.py +260 -0
- botsting/llm/__init__.py +0 -0
- botsting/llm/base.py +31 -0
- botsting/llm/ollama.py +165 -0
- botsting/llm/scripted.py +122 -0
- botsting/mcp_server.py +643 -0
- botsting/practice_server.py +190 -0
- botsting/presets.py +222 -0
- botsting/quick.py +485 -0
- botsting/report_html.py +588 -0
- botsting/report_markdown.py +472 -0
- botsting/reporting.py +73 -0
- botsting/seal.py +245 -0
- botsting/shell.py +40 -0
- botsting/sterility.py +407 -0
- botsting/targets/__init__.py +0 -0
- botsting/targets/base.py +207 -0
- botsting/targets/hardened.py +360 -0
- botsting/targets/http.py +826 -0
- botsting/targets/registry.py +96 -0
- botsting/targets/toy.py +310 -0
- botsting-0.0.3.dist-info/METADATA +495 -0
- botsting-0.0.3.dist-info/RECORD +56 -0
- botsting-0.0.3.dist-info/WHEEL +4 -0
- botsting-0.0.3.dist-info/entry_points.txt +2 -0
- botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
"""Authorization to scan a target that is not running inside this process.
|
|
2
|
+
|
|
3
|
+
BotSting sends hostile messages. Pointed at someone else's bot, it is an attack
|
|
4
|
+
tool, so nothing is sent to a target across a network unless all of these hold:
|
|
5
|
+
|
|
6
|
+
1. **Someone is named as authorizing it.** A person, for one exact origin
|
|
7
|
+
(scheme, host and port), for a stated scope and environment, until a stated date
|
|
8
|
+
no more than MAX_DAYS away. The authorization names every tool the scan may
|
|
9
|
+
exercise, and, if it restricts the agent or tenant, the target must name the same.
|
|
10
|
+
2. **Control of that origin has been shown.** The origin serves a fresh random token
|
|
11
|
+
at `/.well-known/botsting-challenge.txt`, as plain text over HTTPS, without
|
|
12
|
+
redirects. Only someone who controls what the site serves can put it there.
|
|
13
|
+
3. **The proof is still in place when the scan runs.** It is fetched again, ignoring
|
|
14
|
+
anything remembered, at the start of every scan and replay, and again whenever
|
|
15
|
+
RECHECK_SECONDS have passed. The expiry and the rest of the record are checked
|
|
16
|
+
before every operation on the target. A proof that has been taken down, or an
|
|
17
|
+
authorization that has expired, stops the scan, which still reports what it found.
|
|
18
|
+
|
|
19
|
+
A target on this machine ("loopback") needs the record in point 1 but no proof of
|
|
20
|
+
control: there is no domain to prove. It still needs a named person, a scope and
|
|
21
|
+
an expiry, because a local server can forward to anything.
|
|
22
|
+
|
|
23
|
+
A target that runs inside this Python process ("in-process", like the practice
|
|
24
|
+
bots) needs nothing here: its code is right in front of the person running it. Such
|
|
25
|
+
a target may still call a language model served on this machine (Ollama); it may
|
|
26
|
+
not call a model anywhere else.
|
|
27
|
+
|
|
28
|
+
What this does not do
|
|
29
|
+
---------------------
|
|
30
|
+
This shows control of what an origin *serves*. It does not show that the person who
|
|
31
|
+
placed the token owns every system behind it, or that the bot's data and tools are
|
|
32
|
+
theirs to test; the named authorizer and the scope text are how a person takes
|
|
33
|
+
responsibility for that. Where a target says it runs and what tools it has are the
|
|
34
|
+
target adapter's declarations: this module checks them, it does not watch the
|
|
35
|
+
network. In open-source code anyone can delete this check; it is on by default.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import asyncio
|
|
41
|
+
import json
|
|
42
|
+
import os
|
|
43
|
+
import secrets
|
|
44
|
+
import tempfile
|
|
45
|
+
import time
|
|
46
|
+
from collections.abc import Iterable
|
|
47
|
+
from dataclasses import asdict, dataclass, fields, replace
|
|
48
|
+
from datetime import UTC, datetime, timedelta
|
|
49
|
+
from ipaddress import ip_address
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
from typing import Literal
|
|
52
|
+
from urllib.parse import urlsplit
|
|
53
|
+
|
|
54
|
+
import httpx
|
|
55
|
+
|
|
56
|
+
CHALLENGE_PATH = "/.well-known/botsting-challenge.txt"
|
|
57
|
+
TOKEN_PREFIX = "botsting-challenge="
|
|
58
|
+
MAX_DAYS = 90
|
|
59
|
+
RECHECK_SECONDS = 600.0
|
|
60
|
+
_MIN_TOKEN_LENGTH = 32
|
|
61
|
+
_CLOCK_SKEW = timedelta(minutes=5) # allowance for clocks that disagree a little
|
|
62
|
+
_MAX_PROOF_BYTES = 4096
|
|
63
|
+
_FETCH_SECONDS = 10.0 # for the whole fetch, connection to last byte
|
|
64
|
+
_USER_AGENT = "botsting-authorization-check"
|
|
65
|
+
|
|
66
|
+
Reach = Literal["in-process", "loopback", "network"]
|
|
67
|
+
Environment = Literal["staging", "test", "production"]
|
|
68
|
+
REACHES: tuple[str, ...] = ("in-process", "loopback", "network")
|
|
69
|
+
ENVIRONMENTS: tuple[str, ...] = ("staging", "test", "production")
|
|
70
|
+
|
|
71
|
+
# Tests replace this with an httpx.MockTransport. Nothing else should.
|
|
72
|
+
_transport: httpx.AsyncBaseTransport | None = None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AuthorizationError(PermissionError):
|
|
76
|
+
"""There is no valid authorization to send anything to this target."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class Authorization:
|
|
81
|
+
origin: str # normalized: scheme://host[:port], lowercase, punycode, default ports dropped
|
|
82
|
+
authorized_by: str # the person taking responsibility, as they gave their name
|
|
83
|
+
scope: str # what may be tested, in their words
|
|
84
|
+
environment: str # one of ENVIRONMENTS
|
|
85
|
+
created_at: str # ISO 8601 with a time zone
|
|
86
|
+
expires_at: str # ISO 8601 with a time zone
|
|
87
|
+
token: str # random; published by the origin to show control
|
|
88
|
+
verified_at: str = "" # when the proof was last seen in place; empty until then
|
|
89
|
+
# Narrower scope. Control of a site is not permission to fire every tool behind it,
|
|
90
|
+
# or to test every bot and customer account it serves.
|
|
91
|
+
allowed_tools: tuple[str, ...] = () # every tool the target declares must be named here
|
|
92
|
+
# Tools that may be carried out FOR REAL during a test, inside the caps written in the bot's
|
|
93
|
+
# own code (botsting.harness.Cap). Empty, the default, means every tool is only recorded.
|
|
94
|
+
live_tools: tuple[str, ...] = ()
|
|
95
|
+
agent_id: str = "" # if set, the target must name this agent
|
|
96
|
+
tenant: str = "" # if set, the target must name this tenant or account
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def needs_proof(self) -> bool:
|
|
100
|
+
return not is_loopback_origin(self.origin)
|
|
101
|
+
|
|
102
|
+
def expired(self, now: datetime) -> bool:
|
|
103
|
+
return now >= _aware(self.expires_at, "expires_at")
|
|
104
|
+
|
|
105
|
+
def challenge_url(self) -> str:
|
|
106
|
+
return self.origin + CHALLENGE_PATH
|
|
107
|
+
|
|
108
|
+
def challenge_line(self) -> str:
|
|
109
|
+
return TOKEN_PREFIX + self.token
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _aware(value: object, name: str) -> datetime:
|
|
113
|
+
if not isinstance(value, str) or not value:
|
|
114
|
+
raise AuthorizationError(f"{name} must be a date and time, got {value!r}")
|
|
115
|
+
try:
|
|
116
|
+
parsed = datetime.fromisoformat(value)
|
|
117
|
+
except ValueError as exc:
|
|
118
|
+
raise AuthorizationError(f"{name} is not a date and time: {value!r}") from exc
|
|
119
|
+
if parsed.tzinfo is None:
|
|
120
|
+
raise AuthorizationError(f"{name} must include a time zone, got {value!r}")
|
|
121
|
+
return parsed
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def normalize_origin(url: str) -> str:
|
|
125
|
+
"""scheme://host[:port] for a URL, or ValueError if it has no usable origin.
|
|
126
|
+
|
|
127
|
+
Exact matching on this string is the whole point, so it is strict and canonical:
|
|
128
|
+
no user info (not even an empty one), no path beyond "/", no query or fragment,
|
|
129
|
+
only http or https, no port 0, international names in punycode, IPv6 compressed.
|
|
130
|
+
"""
|
|
131
|
+
raw = url.strip()
|
|
132
|
+
parts = urlsplit(raw)
|
|
133
|
+
if parts.scheme not in ("http", "https"):
|
|
134
|
+
raise ValueError(f"an origin must start with http:// or https://, got {url!r}")
|
|
135
|
+
if "@" in parts.netloc:
|
|
136
|
+
raise ValueError("an origin must not contain a user name or password")
|
|
137
|
+
if parts.path not in ("", "/") or parts.query or parts.fragment or raw.endswith(("?", "#")):
|
|
138
|
+
raise ValueError("give only the origin, such as https://staging.example.com, with no path, query or fragment")
|
|
139
|
+
host = (parts.hostname or "").rstrip(".")
|
|
140
|
+
if not host:
|
|
141
|
+
raise ValueError(f"no host in {url!r}")
|
|
142
|
+
try:
|
|
143
|
+
port = parts.port
|
|
144
|
+
except ValueError as exc:
|
|
145
|
+
raise ValueError(f"bad port in {url!r}") from exc
|
|
146
|
+
if port == 0:
|
|
147
|
+
raise ValueError("port 0 is not a usable port")
|
|
148
|
+
try:
|
|
149
|
+
host = ip_address(host).compressed
|
|
150
|
+
except ValueError:
|
|
151
|
+
try:
|
|
152
|
+
host = host.encode("idna").decode("ascii").lower()
|
|
153
|
+
except UnicodeError as exc:
|
|
154
|
+
raise ValueError(f"the host name in {url!r} is not a valid domain name") from exc
|
|
155
|
+
default = {"http": 80, "https": 443}[parts.scheme]
|
|
156
|
+
shown_host = f"[{host}]" if ":" in host else host
|
|
157
|
+
return f"{parts.scheme}://{shown_host}" + (f":{port}" if port is not None and port != default else "")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _resolves_here(host: str) -> bool:
|
|
161
|
+
"""Whether every address this name resolves to is on this machine. False if it does not resolve."""
|
|
162
|
+
import socket
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
found = {info[4][0] for info in socket.getaddrinfo(host, None)}
|
|
166
|
+
except (OSError, UnicodeError):
|
|
167
|
+
return False
|
|
168
|
+
try:
|
|
169
|
+
return bool(found) and all(ip_address(address.split("%")[0]).is_loopback for address in found)
|
|
170
|
+
except ValueError:
|
|
171
|
+
return False
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def is_loopback_origin(origin: str) -> bool:
|
|
175
|
+
"""Whether a bot at this origin is on this machine, so that no proof of control is asked for.
|
|
176
|
+
|
|
177
|
+
`localhost` and loopback addresses are. A name under `.localhost` is meant to be, but some
|
|
178
|
+
resolvers pass such names on to DNS, where anyone could answer; it counts only if every
|
|
179
|
+
address it resolves to is a loopback one, and not at all if it does not resolve."""
|
|
180
|
+
host = (urlsplit(origin).hostname or "").lower()
|
|
181
|
+
if host == "localhost":
|
|
182
|
+
return True
|
|
183
|
+
if host.endswith(".localhost"):
|
|
184
|
+
return _resolves_here(host)
|
|
185
|
+
try:
|
|
186
|
+
return ip_address(host).is_loopback
|
|
187
|
+
except ValueError:
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def validate(authorization: Authorization) -> Authorization:
|
|
192
|
+
"""Check a record however it was obtained: made here, or read back from a file someone could edit.
|
|
193
|
+
|
|
194
|
+
Raises AuthorizationError naming the first problem.
|
|
195
|
+
"""
|
|
196
|
+
a = authorization
|
|
197
|
+
for item in fields(Authorization):
|
|
198
|
+
value = getattr(a, item.name)
|
|
199
|
+
if item.name in ("allowed_tools", "live_tools"):
|
|
200
|
+
if not isinstance(value, tuple) or not all(isinstance(t, str) and t.strip() for t in value):
|
|
201
|
+
raise AuthorizationError(f"{item.name} must be a list of tool names")
|
|
202
|
+
elif not isinstance(value, str):
|
|
203
|
+
raise AuthorizationError(f"{item.name} must be text, got {value!r}")
|
|
204
|
+
try:
|
|
205
|
+
canonical = normalize_origin(a.origin)
|
|
206
|
+
except ValueError as exc:
|
|
207
|
+
raise AuthorizationError(f"origin is not usable: {exc}") from exc
|
|
208
|
+
if canonical != a.origin:
|
|
209
|
+
raise AuthorizationError(f"origin {a.origin!r} is not written the canonical way ({canonical!r})")
|
|
210
|
+
if not a.authorized_by.strip():
|
|
211
|
+
raise AuthorizationError("the record does not name the person who authorized the test")
|
|
212
|
+
if not a.scope.strip():
|
|
213
|
+
raise AuthorizationError("the record does not say what may be tested")
|
|
214
|
+
if a.environment not in ENVIRONMENTS:
|
|
215
|
+
raise AuthorizationError(f"environment must be one of {', '.join(ENVIRONMENTS)}, got {a.environment!r}")
|
|
216
|
+
not_allowed = sorted(set(a.live_tools) - set(a.allowed_tools))
|
|
217
|
+
if not_allowed:
|
|
218
|
+
raise AuthorizationError(f"live tool(s) {', '.join(not_allowed)} must also be named as allowed tools")
|
|
219
|
+
if a.needs_proof and not a.origin.startswith("https://"):
|
|
220
|
+
raise AuthorizationError("a target across a network must be reached over https://")
|
|
221
|
+
if len(a.token) < _MIN_TOKEN_LENGTH:
|
|
222
|
+
raise AuthorizationError("the token is too short to be one this tool generated")
|
|
223
|
+
created = _aware(a.created_at, "created_at")
|
|
224
|
+
expires = _aware(a.expires_at, "expires_at")
|
|
225
|
+
if not created < expires:
|
|
226
|
+
raise AuthorizationError("the record expires before it was created")
|
|
227
|
+
if expires - created > timedelta(days=MAX_DAYS):
|
|
228
|
+
raise AuthorizationError(f"an authorization lasts at most {MAX_DAYS} days")
|
|
229
|
+
if a.verified_at:
|
|
230
|
+
_aware(a.verified_at, "verified_at")
|
|
231
|
+
return a
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def new_authorization(
|
|
235
|
+
origin: str,
|
|
236
|
+
authorized_by: str,
|
|
237
|
+
scope: str,
|
|
238
|
+
environment: str,
|
|
239
|
+
days: int,
|
|
240
|
+
now: datetime | None = None,
|
|
241
|
+
allowed_tools: Iterable[str] = (),
|
|
242
|
+
agent_id: str = "",
|
|
243
|
+
tenant: str = "",
|
|
244
|
+
live_tools: Iterable[str] = (),
|
|
245
|
+
) -> Authorization:
|
|
246
|
+
now = now or datetime.now(UTC)
|
|
247
|
+
normalized = normalize_origin(origin)
|
|
248
|
+
if not 1 <= days <= MAX_DAYS:
|
|
249
|
+
raise ValueError(f"an authorization lasts between 1 and {MAX_DAYS} days")
|
|
250
|
+
if environment not in ENVIRONMENTS:
|
|
251
|
+
raise ValueError(f"environment must be one of {', '.join(ENVIRONMENTS)}")
|
|
252
|
+
if not authorized_by.strip():
|
|
253
|
+
raise ValueError("name the person who authorizes this scan")
|
|
254
|
+
if not scope.strip():
|
|
255
|
+
raise ValueError("state what may be tested, for example 'the support bot on this staging site'")
|
|
256
|
+
if not is_loopback_origin(normalized) and not normalized.startswith("https://"):
|
|
257
|
+
raise ValueError("a target across a network must be reached over https:// so its proof of control can be trusted")
|
|
258
|
+
record = Authorization(
|
|
259
|
+
origin=normalized,
|
|
260
|
+
authorized_by=" ".join(authorized_by.split()),
|
|
261
|
+
scope=" ".join(scope.split()),
|
|
262
|
+
environment=environment,
|
|
263
|
+
created_at=now.isoformat(timespec="seconds"),
|
|
264
|
+
expires_at=(now + timedelta(days=days)).isoformat(timespec="seconds"),
|
|
265
|
+
token=secrets.token_urlsafe(32),
|
|
266
|
+
allowed_tools=tuple(dict.fromkeys(t.strip() for t in allowed_tools if t.strip())),
|
|
267
|
+
live_tools=tuple(dict.fromkeys(t.strip() for t in live_tools if t.strip())),
|
|
268
|
+
agent_id=agent_id.strip(),
|
|
269
|
+
tenant=tenant.strip(),
|
|
270
|
+
)
|
|
271
|
+
try:
|
|
272
|
+
return validate(record)
|
|
273
|
+
except AuthorizationError as exc:
|
|
274
|
+
raise ValueError(str(exc)) from exc
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# -- proof of control --------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@dataclass(frozen=True)
|
|
281
|
+
class ProofResult:
|
|
282
|
+
ok: bool
|
|
283
|
+
detail: str
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
async def check_proof_async(
|
|
287
|
+
authorization: Authorization, transport: httpx.AsyncBaseTransport | None = None
|
|
288
|
+
) -> ProofResult:
|
|
289
|
+
"""Fetch the challenge file from the origin and look for this authorization's token.
|
|
290
|
+
|
|
291
|
+
HTTPS only; no redirects (a redirect could point at a host someone else controls);
|
|
292
|
+
asks caches not to answer; accepts only plain text; reads at most a small number of
|
|
293
|
+
bytes; gives up after _FETCH_SECONDS for the whole fetch. Never raises, except that
|
|
294
|
+
a caller's cancellation is passed on.
|
|
295
|
+
"""
|
|
296
|
+
if not authorization.needs_proof:
|
|
297
|
+
return ProofResult(True, "a loopback origin needs no proof of control")
|
|
298
|
+
url = authorization.challenge_url()
|
|
299
|
+
if not url.startswith("https://"):
|
|
300
|
+
return ProofResult(False, "proof of control is only accepted over https://")
|
|
301
|
+
|
|
302
|
+
async def fetch() -> ProofResult:
|
|
303
|
+
async with httpx.AsyncClient(
|
|
304
|
+
transport=transport if transport is not None else _transport,
|
|
305
|
+
timeout=_FETCH_SECONDS,
|
|
306
|
+
follow_redirects=False,
|
|
307
|
+
trust_env=False, # like the scan's own traffic: a proxy from the environment must not answer for the origin
|
|
308
|
+
headers={"User-Agent": _USER_AGENT, "Cache-Control": "no-cache", "Pragma": "no-cache"},
|
|
309
|
+
) as client:
|
|
310
|
+
async with client.stream("GET", url) as response:
|
|
311
|
+
if response.is_redirect:
|
|
312
|
+
return ProofResult(False, f"{url} answered with a redirect; redirects are not followed")
|
|
313
|
+
if response.status_code != 200:
|
|
314
|
+
return ProofResult(False, f"{url} answered HTTP {response.status_code}")
|
|
315
|
+
age = response.headers.get("age", "0").strip()
|
|
316
|
+
if not age.isdigit() or int(age) > 0:
|
|
317
|
+
# A cache answered, so the token may already have been taken down at the origin.
|
|
318
|
+
return ProofResult(False, f"{url} was answered from a cache (Age: {age}); serve it uncached")
|
|
319
|
+
kind = response.headers.get("content-type", "").split(";")[0].strip().lower()
|
|
320
|
+
if kind != "text/plain":
|
|
321
|
+
return ProofResult(False, f"{url} must be served as text/plain, not {kind or 'no content type'}")
|
|
322
|
+
body = b""
|
|
323
|
+
async for chunk in response.aiter_bytes():
|
|
324
|
+
body += chunk
|
|
325
|
+
if len(body) > _MAX_PROOF_BYTES:
|
|
326
|
+
return ProofResult(False, f"{url} is larger than {_MAX_PROOF_BYTES} bytes")
|
|
327
|
+
lines = {line.strip() for line in body.decode("utf-8", "replace").splitlines()}
|
|
328
|
+
if authorization.challenge_line() in lines:
|
|
329
|
+
return ProofResult(True, f"token found at {url}")
|
|
330
|
+
return ProofResult(False, f"{url} does not contain this authorization's token")
|
|
331
|
+
|
|
332
|
+
try:
|
|
333
|
+
return await asyncio.wait_for(fetch(), timeout=_FETCH_SECONDS)
|
|
334
|
+
except TimeoutError:
|
|
335
|
+
return ProofResult(False, f"no complete answer from {url} within {_FETCH_SECONDS:g} seconds")
|
|
336
|
+
except httpx.HTTPError as exc:
|
|
337
|
+
return ProofResult(False, f"could not fetch {url}: {type(exc).__name__}")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def check_proof(authorization: Authorization, transport: httpx.AsyncBaseTransport | None = None) -> ProofResult:
|
|
341
|
+
"""check_proof_async, for callers outside an event loop (the `authorize --verify` command)."""
|
|
342
|
+
return asyncio.run(check_proof_async(authorization, transport))
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# -- the store ---------------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
DEFAULT_STORE = Path("botsting.authorizations.json")
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class AuthorizationStore:
|
|
352
|
+
"""Authorizations kept in one JSON file next to where scans are run.
|
|
353
|
+
|
|
354
|
+
The file holds names and scope text that people typed. It stays on this machine;
|
|
355
|
+
nothing here sends it anywhere. Every record is validated when it is read back,
|
|
356
|
+
because the file can be edited by hand.
|
|
357
|
+
"""
|
|
358
|
+
|
|
359
|
+
def __init__(self, path: Path = DEFAULT_STORE) -> None:
|
|
360
|
+
self.path = Path(path)
|
|
361
|
+
|
|
362
|
+
def load(self) -> list[Authorization]:
|
|
363
|
+
if not self.path.exists():
|
|
364
|
+
return []
|
|
365
|
+
try:
|
|
366
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
367
|
+
items = data["authorizations"]
|
|
368
|
+
if not isinstance(items, list):
|
|
369
|
+
raise TypeError("'authorizations' must be a list")
|
|
370
|
+
records = []
|
|
371
|
+
for item in items:
|
|
372
|
+
tools, live = item.get("allowed_tools", []), item.get("live_tools", [])
|
|
373
|
+
if not isinstance(tools, list) or not isinstance(live, list):
|
|
374
|
+
raise TypeError("allowed_tools must be a list, and so must live_tools")
|
|
375
|
+
records.append(Authorization(**{**item, "allowed_tools": tuple(tools), "live_tools": tuple(live)}))
|
|
376
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
377
|
+
raise AuthorizationError(f"could not read {self.path}: {exc}") from exc
|
|
378
|
+
for record in records:
|
|
379
|
+
try:
|
|
380
|
+
validate(record)
|
|
381
|
+
except AuthorizationError as exc:
|
|
382
|
+
raise AuthorizationError(f"{self.path} holds an unusable authorization for {record.origin!r}: {exc}") from exc
|
|
383
|
+
return records
|
|
384
|
+
|
|
385
|
+
def save(self, authorizations: Iterable[Authorization]) -> None:
|
|
386
|
+
payload = json.dumps({"authorizations": [asdict(a) for a in authorizations]}, indent=2)
|
|
387
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
388
|
+
# Written to a temporary file and renamed, so a crash cannot leave half a file.
|
|
389
|
+
handle, temporary = tempfile.mkstemp(dir=self.path.parent, prefix=".botsting-auth-", suffix=".json")
|
|
390
|
+
try:
|
|
391
|
+
with os.fdopen(handle, "w", encoding="utf-8") as file:
|
|
392
|
+
file.write(payload)
|
|
393
|
+
os.replace(temporary, self.path)
|
|
394
|
+
except BaseException:
|
|
395
|
+
Path(temporary).unlink(missing_ok=True)
|
|
396
|
+
raise
|
|
397
|
+
|
|
398
|
+
def add(self, authorization: Authorization) -> None:
|
|
399
|
+
validate(authorization)
|
|
400
|
+
# One live authorization per origin: a new one replaces the old.
|
|
401
|
+
kept = [a for a in self.load() if a.origin != authorization.origin]
|
|
402
|
+
self.save([*kept, authorization])
|
|
403
|
+
|
|
404
|
+
def find(self, origin: str) -> Authorization | None:
|
|
405
|
+
normalized = normalize_origin(origin)
|
|
406
|
+
return next((a for a in self.load() if a.origin == normalized), None)
|
|
407
|
+
|
|
408
|
+
def mark_verified(self, origin: str, when: datetime) -> Authorization:
|
|
409
|
+
found = self.find(origin)
|
|
410
|
+
if found is None:
|
|
411
|
+
raise AuthorizationError(f"no authorization for {origin}; create one with `botsting authorize`")
|
|
412
|
+
updated = replace(found, verified_at=when.isoformat(timespec="seconds"))
|
|
413
|
+
self.add(updated)
|
|
414
|
+
return updated
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def authorization_summary(target: object) -> dict[str, str]:
|
|
418
|
+
"""What a report records about the permission a scan ran under. Never includes the token."""
|
|
419
|
+
reach = getattr(target, "reach", "")
|
|
420
|
+
authorization = getattr(target, "authorization", None)
|
|
421
|
+
if reach == "in-process" or not isinstance(authorization, Authorization):
|
|
422
|
+
return {"reach": str(reach)} if reach else {}
|
|
423
|
+
return {
|
|
424
|
+
"reach": str(reach),
|
|
425
|
+
"origin": authorization.origin,
|
|
426
|
+
"authorized_by": authorization.authorized_by,
|
|
427
|
+
"scope": authorization.scope,
|
|
428
|
+
"environment": authorization.environment,
|
|
429
|
+
"expires_at": authorization.expires_at,
|
|
430
|
+
"proof": "token served by the origin, checked during the scan" if authorization.needs_proof else "none needed on this machine",
|
|
431
|
+
"verified_at": authorization.verified_at or "not needed",
|
|
432
|
+
"allowed_tools": ", ".join(authorization.allowed_tools) or "none",
|
|
433
|
+
"live_tools": ", ".join(authorization.live_tools) or "none (tools were recorded, never carried out)",
|
|
434
|
+
"agent_id": authorization.agent_id or "any",
|
|
435
|
+
"tenant": authorization.tenant or "any",
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# -- the gate ------------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
# (origin, token) -> monotonic time the proof was last seen in place during this process.
|
|
442
|
+
_seen: dict[tuple[str, str], float] = {}
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def forget_checks() -> None:
|
|
446
|
+
"""Drop every remembered proof check, so the next check fetches again. For tests."""
|
|
447
|
+
_seen.clear()
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _require_in_scope(target: object, authorization: Authorization) -> None:
|
|
451
|
+
"""The target must not reach beyond what the authorization names."""
|
|
452
|
+
rules = getattr(target, "tool_rules", None)
|
|
453
|
+
points = getattr(target, "injection_points", None)
|
|
454
|
+
tools = {rule.tool for rule in (rules() if callable(rules) else ())}
|
|
455
|
+
tools |= {tool for point in (points() if callable(points) else ()) for tool in point.forbidden_tools}
|
|
456
|
+
unnamed = sorted(tools - set(authorization.allowed_tools))
|
|
457
|
+
if unnamed:
|
|
458
|
+
raise AuthorizationError(
|
|
459
|
+
f"the authorization for {authorization.origin} does not name the tool(s) {', '.join(unnamed)}; "
|
|
460
|
+
"re-authorize with --tool for each tool that may be exercised"
|
|
461
|
+
)
|
|
462
|
+
asked = getattr(target, "live_actions", ())
|
|
463
|
+
not_live = sorted(set(asked) - set(authorization.live_tools))
|
|
464
|
+
if not_live:
|
|
465
|
+
raise AuthorizationError(
|
|
466
|
+
f"this target asks to carry out {', '.join(not_live)} for real, but the authorization for "
|
|
467
|
+
f"{authorization.origin} does not allow that; re-authorize with --live-tool for each, "
|
|
468
|
+
"or remove live_actions from the description"
|
|
469
|
+
)
|
|
470
|
+
for field_name, flag in (("agent_id", "--agent"), ("tenant", "--tenant")):
|
|
471
|
+
declared = str(getattr(target, field_name, "") or "")
|
|
472
|
+
allowed = getattr(authorization, field_name)
|
|
473
|
+
if allowed and not declared:
|
|
474
|
+
raise AuthorizationError(
|
|
475
|
+
f"the authorization is limited to {field_name} {allowed!r}, but this target does not say which "
|
|
476
|
+
f"{field_name} it is, so the limit cannot be checked"
|
|
477
|
+
)
|
|
478
|
+
if declared and declared != allowed:
|
|
479
|
+
raise AuthorizationError(
|
|
480
|
+
f"this target's {field_name} is {declared!r} but the authorization covers {allowed or 'nothing'!r}; "
|
|
481
|
+
f"re-authorize with {flag} {declared}"
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def require_authorized(target: object, now: datetime | None = None) -> Authorization | None:
|
|
486
|
+
"""Everything about permission that can be checked without the network. Raises AuthorizationError.
|
|
487
|
+
|
|
488
|
+
Returns the authorization whose proof of control still has to be confirmed (a
|
|
489
|
+
network target), or None when no proof is needed. Called before every operation
|
|
490
|
+
on a target, so it must stay cheap.
|
|
491
|
+
"""
|
|
492
|
+
reach = getattr(target, "reach", None)
|
|
493
|
+
if reach not in REACHES:
|
|
494
|
+
raise AuthorizationError(
|
|
495
|
+
"this target does not declare where it runs (in-process, loopback or network); refusing to send it anything"
|
|
496
|
+
)
|
|
497
|
+
if reach == "in-process":
|
|
498
|
+
return None
|
|
499
|
+
origin = getattr(target, "origin", None)
|
|
500
|
+
authorization = getattr(target, "authorization", None)
|
|
501
|
+
if not isinstance(origin, str) or not origin:
|
|
502
|
+
raise AuthorizationError("this target reaches beyond this process but does not say which origin it talks to")
|
|
503
|
+
try:
|
|
504
|
+
normalized = normalize_origin(origin)
|
|
505
|
+
except ValueError as exc:
|
|
506
|
+
raise AuthorizationError(f"this target's origin is not usable: {exc}") from exc
|
|
507
|
+
if reach == "loopback" and not is_loopback_origin(normalized):
|
|
508
|
+
raise AuthorizationError(f"this target says it is on this machine but its origin {normalized} is not")
|
|
509
|
+
if reach == "network" and is_loopback_origin(normalized):
|
|
510
|
+
raise AuthorizationError(f"this target says it is across a network but its origin {normalized} is on this machine")
|
|
511
|
+
if not isinstance(authorization, Authorization):
|
|
512
|
+
then = "" if is_loopback_origin(normalized) else ", publish its token, and verify it"
|
|
513
|
+
raise AuthorizationError(
|
|
514
|
+
f"no authorization to test {normalized}. Create one with `botsting authorize {normalized} ...`{then}"
|
|
515
|
+
)
|
|
516
|
+
validate(authorization)
|
|
517
|
+
if authorization.origin != normalized:
|
|
518
|
+
raise AuthorizationError(
|
|
519
|
+
f"the authorization is for {authorization.origin}, not {normalized}; each origin needs its own"
|
|
520
|
+
)
|
|
521
|
+
now = now or datetime.now(UTC)
|
|
522
|
+
if authorization.expired(now):
|
|
523
|
+
raise AuthorizationError(f"the authorization for {normalized} expired at {authorization.expires_at}")
|
|
524
|
+
if _aware(authorization.created_at, "created_at") > now + _CLOCK_SKEW:
|
|
525
|
+
raise AuthorizationError(f"the authorization for {normalized} is dated {authorization.created_at}, in the future")
|
|
526
|
+
_require_in_scope(target, authorization)
|
|
527
|
+
if not authorization.needs_proof:
|
|
528
|
+
return None
|
|
529
|
+
if not authorization.verified_at:
|
|
530
|
+
raise AuthorizationError(
|
|
531
|
+
f"the authorization for {normalized} has not been verified; run `botsting authorize --verify {normalized}`"
|
|
532
|
+
)
|
|
533
|
+
return authorization
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
async def confirm_proof(authorization: Authorization, fresh: bool = False) -> None:
|
|
537
|
+
"""Make sure the origin still serves the token. Raises AuthorizationError if it does not.
|
|
538
|
+
|
|
539
|
+
`fresh` ignores anything remembered: used at the start of every scan and replay.
|
|
540
|
+
Otherwise the proof is fetched again once RECHECK_SECONDS have passed.
|
|
541
|
+
"""
|
|
542
|
+
key = (authorization.origin, authorization.token)
|
|
543
|
+
last = _seen.get(key)
|
|
544
|
+
if not fresh and last is not None and time.monotonic() - last < RECHECK_SECONDS:
|
|
545
|
+
return
|
|
546
|
+
_seen.pop(key, None)
|
|
547
|
+
result = await check_proof_async(authorization)
|
|
548
|
+
if not result.ok:
|
|
549
|
+
raise AuthorizationError(f"proof of control for {authorization.origin} is no longer in place: {result.detail}")
|
|
550
|
+
_seen[key] = time.monotonic()
|