blindsight-security 1.0.0__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.
@@ -0,0 +1,86 @@
1
+ """Blindsight Runtime Security: official Python SDK.
2
+
3
+ Two integration surfaces, one client:
4
+
5
+ * **Scan API**: inspect prompts, responses, files and tool-calls inline::
6
+
7
+ from blindsight_security import RuntimeSecurity
8
+
9
+ rs = RuntimeSecurity(
10
+ base_url="https://platform.blindsight.io",
11
+ api_key="ak_…",
12
+ app_id="<App id>",
13
+ )
14
+
15
+ verdict = rs.scan_input(user_prompt)
16
+ if verdict.blocked:
17
+ raise PermissionError(verdict.blocked_reason)
18
+ safe_prompt = verdict.safe_text
19
+
20
+ When the prompt carries content the user did not write, say so::
21
+
22
+ verdict = rs.scan_input(
23
+ prompt,
24
+ untrusted=[UntrustedSpan.tool_result(tool_output, label="calendar")],
25
+ )
26
+ for i in verdict.flagged_span_indices:
27
+ logger.warning("dropping span %s", i)
28
+
29
+ * **Reverse proxy**: route your existing vendor SDK through the guardrail::
30
+
31
+ from openai import OpenAI
32
+ client = OpenAI(api_key=OPENAI_KEY, **rs.proxy.openai())
33
+ """
34
+
35
+ from .client import RuntimeSecurity
36
+ from .errors import (
37
+ BlindsightAPIError,
38
+ BlindsightAuthError,
39
+ BlindsightConnectionError,
40
+ BlindsightError,
41
+ BlindsightQuotaError,
42
+ ContentBlocked,
43
+ )
44
+ from .models import (
45
+ Coverage,
46
+ CoverageState,
47
+ MCPVerifyResult,
48
+ OcrFacts,
49
+ OcrPage,
50
+ restore_pseudonyms,
51
+ ScanFileResult,
52
+ ScanResult,
53
+ ToolCallResult,
54
+ UntrustedSpan,
55
+ Verdict,
56
+ )
57
+ from .proxy import Proxy
58
+
59
+ # Friendly alias.
60
+ Client = RuntimeSecurity
61
+
62
+ __version__ = "1.0.0"
63
+
64
+ __all__ = [
65
+ "RuntimeSecurity",
66
+ "Client",
67
+ "Proxy",
68
+ "Verdict",
69
+ "ScanResult",
70
+ "ScanFileResult",
71
+ "Coverage",
72
+ "CoverageState",
73
+ "OcrFacts",
74
+ "OcrPage",
75
+ "restore_pseudonyms",
76
+ "ToolCallResult",
77
+ "MCPVerifyResult",
78
+ "UntrustedSpan",
79
+ "BlindsightError",
80
+ "BlindsightAPIError",
81
+ "BlindsightAuthError",
82
+ "BlindsightQuotaError",
83
+ "BlindsightConnectionError",
84
+ "ContentBlocked",
85
+ "__version__",
86
+ ]
@@ -0,0 +1,489 @@
1
+ """Synchronous client for the Blindsight Runtime Security scan API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import math
7
+ import random
8
+ import time
9
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
10
+
11
+ import httpx
12
+
13
+ from .errors import (
14
+ BlindsightAPIError,
15
+ BlindsightAuthError,
16
+ BlindsightConnectionError,
17
+ BlindsightQuotaError,
18
+ )
19
+ from .models import (
20
+ MCPVerifyResult,
21
+ ScanFileResult,
22
+ ScanResult,
23
+ ToolCallResult,
24
+ UntrustedSpan,
25
+ coerce_untrusted,
26
+ )
27
+ from .proxy import Proxy
28
+
29
+ _API_PREFIX = "/api/runtime-security"
30
+
31
+ BatchItem = Mapping[str, Any]
32
+ # What `scan_input(untrusted=...)` accepts: spans as objects, dicts or bare
33
+ # strings, or a single one of any of those.
34
+ UntrustedSpans = Union[
35
+ UntrustedSpan,
36
+ str,
37
+ Mapping[str, Any],
38
+ Sequence[Union[UntrustedSpan, str, Mapping[str, Any]]],
39
+ ]
40
+
41
+
42
+ def _turn(turn: Optional[int]) -> Optional[int]:
43
+ """Checked where the call is written, like the other fields: a turn is a
44
+ whole number from 1."""
45
+ if turn is None:
46
+ return None
47
+ if isinstance(turn, bool) or not isinstance(turn, int) or turn < 1:
48
+ raise ValueError("turn must be a whole number from 1")
49
+ return turn
50
+
51
+
52
+ def _prune(d: Dict[str, Any]) -> Dict[str, Any]:
53
+ """Drop ``None`` values so we send a minimal body the API validates cleanly."""
54
+ return {k: v for k, v in d.items() if v is not None}
55
+
56
+
57
+ class RuntimeSecurity:
58
+ """Client for Blindsight Runtime Security.
59
+
60
+ Wraps both integration surfaces:
61
+
62
+ * the explicit **scan API** (:meth:`scan_input`, :meth:`scan_output`,
63
+ :meth:`scan_file`, :meth:`scan_tool_call`, :meth:`scan_batch`), and
64
+ * the **reverse proxy** config helpers, via the :attr:`proxy` property.
65
+
66
+ Args:
67
+ base_url: Root of your Blindsight deployment, e.g.
68
+ ``https://platform.blindsight.io`` (no trailing ``/api/...``).
69
+ api_key: Your Blindsight workspace API key (``ak_…``, created under
70
+ Settings > API keys). Sent as ``X-API-Key``.
71
+ app_id: Optional App id (a UUID, shown on the App's page) for per-App
72
+ policy and attribution. Sent as ``X-Blindsight-App-Id``. A key bound
73
+ to one App does not need it.
74
+ app_token: Optional App token, sent as ``X-Blindsight-App-Token``.
75
+ timeout: Per-request timeout in seconds (default 10).
76
+ transport: Optional ``httpx.BaseTransport`` (used in tests).
77
+ max_retries: Retries after a 429 or 503, or a connection that never
78
+ reached the server (default 2, at most 10). A read timeout is
79
+ never retried: the scan may already have been made.
80
+ max_retry_wait: The most seconds all retries of one call may wait
81
+ together (default 30). A ``Retry-After`` longer than what is left
82
+ is not waited for: the error is raised at once.
83
+
84
+ The client never answers for you when Blindsight cannot: every failure is
85
+ an exception, so nothing reaches your model unscanned unless your own code
86
+ decides to send it.
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ base_url: str,
92
+ api_key: str,
93
+ *,
94
+ app_id: Optional[str] = None,
95
+ app_token: Optional[str] = None,
96
+ timeout: float = 10.0,
97
+ transport: Optional[httpx.BaseTransport] = None,
98
+ max_retries: int = 2,
99
+ max_retry_wait: float = 30.0,
100
+ _sleep: Any = None,
101
+ ) -> None:
102
+ if not base_url:
103
+ raise ValueError("base_url is required (e.g. https://platform.blindsight.io)")
104
+ if not api_key:
105
+ raise ValueError("api_key is required (your Blindsight API key, ak_…)")
106
+
107
+ if not 0 <= int(max_retries) <= 10:
108
+ raise ValueError("max_retries must be between 0 and 10")
109
+ self._max_retries = int(max_retries)
110
+ self._max_retry_wait = max(0.0, float(max_retry_wait))
111
+ self._sleep = _sleep or time.sleep
112
+ _require_https(base_url)
113
+ self._base_url = base_url.rstrip("/")
114
+ self._api_key = api_key
115
+ self._app_id = app_id
116
+ self._app_token = app_token
117
+
118
+ headers: Dict[str, str] = {"X-API-Key": api_key, "Content-Type": "application/json"}
119
+ if app_id:
120
+ headers["X-Blindsight-App-Id"] = app_id
121
+ if app_token:
122
+ headers["X-Blindsight-App-Token"] = app_token
123
+
124
+ self._http = httpx.Client(
125
+ base_url=self._base_url,
126
+ headers=headers,
127
+ timeout=timeout,
128
+ transport=transport,
129
+ )
130
+
131
+ #: Reverse-proxy config helper: see :class:`~.proxy.Proxy`.
132
+ self.proxy = Proxy(
133
+ self._base_url, api_key, app_id=app_id, app_token=app_token
134
+ )
135
+
136
+ # -- lifecycle ----------------------------------------------------------
137
+ def close(self) -> None:
138
+ self._http.close()
139
+
140
+ def __enter__(self) -> "RuntimeSecurity":
141
+ return self
142
+
143
+ def __exit__(self, *exc: Any) -> None:
144
+ self.close()
145
+
146
+ # -- scan API -----------------------------------------------------------
147
+ def scan_input(
148
+ self,
149
+ text: str,
150
+ *,
151
+ untrusted: Optional[UntrustedSpans] = None,
152
+ source_app: Optional[str] = None,
153
+ provider: Optional[str] = None,
154
+ model: Optional[str] = None,
155
+ metadata: Optional[Dict[str, Any]] = None,
156
+ custom_params: Optional[Dict[str, Any]] = None,
157
+ session_id: Optional[str] = None,
158
+ turn: Optional[int] = None,
159
+ ) -> ScanResult:
160
+ """Scan a user prompt *before* sending it to your LLM.
161
+
162
+ ``untrusted`` is for prompts assembled from more than the user's own
163
+ words. Pass the retrieved documents, tool results, fetched pages or
164
+ email bodies and the firewall judges them as data: inside a declared
165
+ span an instruction aimed at the assistant is a finding however
166
+ ordinary it sounds, because the user never asked for it::
167
+
168
+ rs.scan_input(
169
+ prompt,
170
+ untrusted=[UntrustedSpan.tool_result(tool_output)],
171
+ )
172
+
173
+ A bare string is accepted and defaults to ``retrieval``. Findings come
174
+ back per span on ``result.untrusted`` and
175
+ ``result.flagged_span_indices``, so an offending document can be
176
+ dropped or re-fetched without failing the whole request. At most 32
177
+ spans, and this is the only scan that takes them: ``scan_output`` and
178
+ ``scan_batch`` have no such field on the API.
179
+
180
+ ``session_id`` is optional and turns on cross-turn detection: pass a
181
+ stable id for the conversation and the firewall correlates this call
182
+ with the rest of the session, so it can flag a tool call that arrives
183
+ just after a suspect prompt. Findings land on ``result.trace``. Omit it
184
+ and every call is judged on its own.
185
+
186
+ The same id names the conversation for an App with conversation
187
+ conditions ("mask a name only once a national ID has been part of the
188
+ conversation"); the outcome is on ``result.conversation``. ``turn`` is
189
+ this call's number in the conversation, from 1: optional, and it keeps
190
+ a retried call from counting as a new turn.
191
+ """
192
+ body = _prune(
193
+ {
194
+ "text": text,
195
+ "untrusted": coerce_untrusted(untrusted) or None,
196
+ "session_id": session_id,
197
+ "turn": _turn(turn),
198
+ "source_app": source_app,
199
+ "provider": provider,
200
+ "model": model,
201
+ "metadata": metadata,
202
+ "custom_params": custom_params,
203
+ }
204
+ )
205
+ return ScanResult.from_dict(self._post("/scan/input", body))
206
+
207
+ def scan_output(
208
+ self,
209
+ response: str,
210
+ *,
211
+ prompt: Optional[str] = None,
212
+ source_app: Optional[str] = None,
213
+ provider: Optional[str] = None,
214
+ model: Optional[str] = None,
215
+ metadata: Optional[Dict[str, Any]] = None,
216
+ custom_params: Optional[Dict[str, Any]] = None,
217
+ session_id: Optional[str] = None,
218
+ turn: Optional[int] = None,
219
+ ) -> ScanResult:
220
+ """Scan an LLM response *before* showing it to the user.
221
+
222
+ ``session_id`` and ``turn`` work as on :meth:`scan_input`."""
223
+ body = _prune(
224
+ {
225
+ "response": response,
226
+ "session_id": session_id,
227
+ "turn": _turn(turn),
228
+ "prompt": prompt,
229
+ "source_app": source_app,
230
+ "provider": provider,
231
+ "model": model,
232
+ "metadata": metadata,
233
+ "custom_params": custom_params,
234
+ }
235
+ )
236
+ return ScanResult.from_dict(self._post("/scan/output", body))
237
+
238
+ def scan_file(
239
+ self,
240
+ data: Union[bytes, str],
241
+ *,
242
+ filename: Optional[str] = None,
243
+ media_type: Optional[str] = None,
244
+ direction: str = "input",
245
+ source_app: Optional[str] = None,
246
+ provider: Optional[str] = None,
247
+ model: Optional[str] = None,
248
+ metadata: Optional[Dict[str, Any]] = None,
249
+ ocr_language: Optional[str] = None,
250
+ ) -> ScanFileResult:
251
+ """Scan an uploaded file (PDF, docx, xlsx, image, …).
252
+
253
+ ``data`` may be raw ``bytes`` (base64-encoded for you) or an
254
+ already-base64 ``str``. The response carries the possibly-redacted file
255
+ on :attr:`ScanFileResult.file_bytes`.
256
+
257
+ Check :attr:`ScanFileResult.coverage`: a file that could not be read
258
+ (a scan with no recognisable text, an archive, a file over the size
259
+ cap) comes back ``flag`` with ``coverage.state`` ``not_scanned``, never
260
+ ``allow``. ``ocr_language`` is an optional hint for scans and pictures,
261
+ tesseract codes joined with ``+`` (``"deu"``, ``"fra+eng"``)."""
262
+ if isinstance(data, bytes):
263
+ encoded = base64.b64encode(data).decode("ascii")
264
+ else:
265
+ encoded = data
266
+ body = _prune(
267
+ {
268
+ "data": encoded,
269
+ "filename": filename,
270
+ "media_type": media_type,
271
+ "direction": direction,
272
+ "source_app": source_app,
273
+ "provider": provider,
274
+ "model": model,
275
+ "metadata": metadata,
276
+ "ocr_language": ocr_language,
277
+ }
278
+ )
279
+ return ScanFileResult.from_dict(self._post("/scan/file", body))
280
+
281
+ def scan_tool_call(
282
+ self,
283
+ tool_name: str,
284
+ arguments: Any = None,
285
+ *,
286
+ source_app: Optional[str] = None,
287
+ provider: Optional[str] = None,
288
+ model: Optional[str] = None,
289
+ metadata: Optional[Dict[str, Any]] = None,
290
+ session_id: Optional[str] = None,
291
+ ) -> ToolCallResult:
292
+ """Gate an agent tool-call. ``arguments`` may be a dict/list/str/number."""
293
+ body = _prune(
294
+ {
295
+ "tool_name": tool_name,
296
+ "session_id": session_id,
297
+ "arguments": arguments if arguments is not None else {},
298
+ "source_app": source_app,
299
+ "provider": provider,
300
+ "model": model,
301
+ "metadata": metadata,
302
+ }
303
+ )
304
+ return ToolCallResult.from_dict(self._post("/scan/tool-call", body))
305
+
306
+ def verify_tool(
307
+ self,
308
+ server: str,
309
+ name: str,
310
+ *,
311
+ description: str = "",
312
+ schema: Any = None,
313
+ tool_result: Optional[str] = None,
314
+ session_labels: Optional[Sequence[str]] = None,
315
+ source_app: Optional[str] = None,
316
+ provider: Optional[str] = None,
317
+ model: Optional[str] = None,
318
+ metadata: Optional[Dict[str, Any]] = None,
319
+ ) -> MCPVerifyResult:
320
+ """Verify an MCP tool's integrity before trusting it.
321
+
322
+ Runs the full gate: description poisoning scan, trust-on-first-use hash
323
+ pinning (rug-pull / full-schema poisoning), cross-server shadowing,
324
+ optional tool-result injection scan, and optional dataflow. Call it when
325
+ the agent discovers a server's tools and again before a sensitive call;
326
+ pass ``tool_result`` to also scan a result the tool returned.
327
+
328
+ The verdict (``allow`` / ``flag`` / ``block``) reflects the App's
329
+ configured MCP enforcement mode. Use :meth:`MCPVerifyResult
330
+ .raise_for_block` to fail closed.
331
+ """
332
+ body = _prune(
333
+ {
334
+ "server": server,
335
+ "name": name,
336
+ "description": description,
337
+ "schema": schema,
338
+ "tool_result": tool_result,
339
+ "session_labels": list(session_labels) if session_labels else None,
340
+ "source_app": source_app,
341
+ "provider": provider,
342
+ "model": model,
343
+ "metadata": metadata,
344
+ }
345
+ )
346
+ return MCPVerifyResult.from_dict(self._post("/scan/tool", body))
347
+
348
+ def scan_batch(self, items: Sequence[BatchItem]) -> List[ScanResult]:
349
+ """Scan up to 32 texts in one round-trip.
350
+
351
+ Each item is a dict: ``{"text": ..., "direction": "input"|"output",
352
+ "source_app"?, "provider"?, "model"?, "metadata"?}``."""
353
+ payload = {"items": [_prune(dict(item)) for item in items]}
354
+ data = self._post("/scan/batch", payload)
355
+ results = data.get("results") if isinstance(data, dict) else None
356
+ return [ScanResult.from_dict(r) for r in (results or [])]
357
+
358
+ # -- transport ----------------------------------------------------------
359
+ def _post(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:
360
+ url = f"{_API_PREFIX}{path}"
361
+ attempt = 0
362
+ waited = 0.0
363
+ while True:
364
+ resp: Optional[httpx.Response] = None
365
+ try:
366
+ resp = self._http.post(url, json=body)
367
+ except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
368
+ # The request never reached the server, so sending it again
369
+ # cannot make the scan twice.
370
+ if attempt >= self._max_retries:
371
+ raise BlindsightConnectionError(f"Could not reach {url}") from exc
372
+ except httpx.TimeoutException as exc:
373
+ # Never retried: the server may already have made the scan.
374
+ raise BlindsightConnectionError(f"Request to {url} timed out") from exc
375
+ except httpx.HTTPError as exc:
376
+ raise BlindsightConnectionError(
377
+ f"Could not reach {url} ({type(exc).__name__})") from exc
378
+
379
+ if resp is not None:
380
+ if resp.status_code not in _RETRY_STATUSES or attempt >= self._max_retries:
381
+ return self._parse(resp)
382
+ try:
383
+ payload: Any = resp.json()
384
+ except ValueError:
385
+ payload = None
386
+ wait = _error_facts(resp, payload)[2]
387
+ delay = wait if wait is not None else _backoff(attempt)
388
+ else:
389
+ delay = _backoff(attempt)
390
+
391
+ if waited + delay > self._max_retry_wait:
392
+ # Not worth waiting for: give the caller the answer now.
393
+ if resp is not None:
394
+ return self._parse(resp)
395
+ raise BlindsightConnectionError(f"Could not reach {url}")
396
+ self._sleep(delay)
397
+ waited += delay
398
+ attempt += 1
399
+
400
+ def _parse(self, resp: httpx.Response) -> Dict[str, Any]:
401
+ if resp.is_success:
402
+ try:
403
+ return resp.json()
404
+ except ValueError as exc: # pragma: no cover - server contract
405
+ raise BlindsightAPIError(
406
+ "Runtime Security returned a non-JSON success body",
407
+ status_code=resp.status_code,
408
+ response_body=resp.text,
409
+ ) from exc
410
+
411
+ try:
412
+ payload: Any = resp.json()
413
+ except ValueError:
414
+ payload = resp.text
415
+ message, code, retry_after = _error_facts(resp, payload)
416
+ kwargs = dict(status_code=resp.status_code, code=code, response_body=payload,
417
+ retry_after=retry_after)
418
+
419
+ if resp.status_code in (401, 403):
420
+ raise BlindsightAuthError(message, **kwargs)
421
+ if resp.status_code in (402, 429):
422
+ raise BlindsightQuotaError(message, **kwargs)
423
+ raise BlindsightAPIError(message, **kwargs)
424
+
425
+
426
+ # A 502 or 504 can come from a gateway after the scan already ran: not retried,
427
+ # so a scan is never made (and counted) twice.
428
+ _RETRY_STATUSES = (429, 503)
429
+
430
+
431
+ def _require_https(base_url: str) -> None:
432
+ """The key travels in a header: only over https, except to this machine."""
433
+ from urllib.parse import urlsplit
434
+
435
+ parts = urlsplit(base_url)
436
+ local = (parts.hostname or "") in ("localhost", "127.0.0.1", "::1") or \
437
+ (parts.hostname or "").endswith(".localhost")
438
+ if parts.scheme != "https" and not (parts.scheme == "http" and local):
439
+ raise ValueError("base_url must start with https:// (http:// is accepted for localhost only)")
440
+
441
+
442
+ def _backoff(attempt: int) -> float:
443
+ """0.5 s, 1 s, 2 s ... up to 8 s, with jitter so clients do not retry in step."""
444
+ return min(0.5 * (2 ** attempt), 8.0) * random.uniform(0.5, 1.0)
445
+
446
+
447
+ def _error_facts(resp: httpx.Response, payload: Any) -> "tuple[str, Optional[str], Optional[float]]":
448
+ """A readable message, the machine code and the wait, from an error response.
449
+
450
+ The API answers ``{"detail": "..."}`` or ``{"detail": {"code", "message", ...}}``,
451
+ inside an ``{"error": {"code", "message", "details"}}`` envelope. The code is
452
+ the ``X-Blindsight-Error-Code`` header when set, else the one in the body.
453
+ """
454
+ detail = payload.get("detail") if isinstance(payload, dict) else payload
455
+ envelope = payload.get("error") if isinstance(payload, dict) else None
456
+ envelope = envelope if isinstance(envelope, dict) else {}
457
+ details = envelope.get("details") if isinstance(envelope.get("details"), dict) else {}
458
+
459
+ message: Optional[str] = None
460
+ if isinstance(detail, dict):
461
+ message = detail.get("message") if isinstance(detail.get("message"), str) else None
462
+ elif isinstance(detail, str) and detail:
463
+ message = detail
464
+ if not message and isinstance(envelope.get("message"), str):
465
+ message = envelope["message"]
466
+ if not message:
467
+ message = f"Runtime Security error (HTTP {resp.status_code})"
468
+
469
+ code = resp.headers.get("X-Blindsight-Error-Code")
470
+ if not code:
471
+ for source in (detail, details):
472
+ if isinstance(source, dict) and isinstance(source.get("code"), str):
473
+ code = source["code"]
474
+ break
475
+
476
+ retry_after: Optional[float] = None
477
+ raw = resp.headers.get("Retry-After")
478
+ if raw is not None:
479
+ try:
480
+ value = float(raw)
481
+ retry_after = value if math.isfinite(value) and value >= 0 else None
482
+ except ValueError:
483
+ retry_after = None # an HTTP date; the body says it in seconds
484
+ if retry_after is None and isinstance(detail, dict):
485
+ seconds = detail.get("retry_after_seconds")
486
+ if isinstance(seconds, (int, float)) and not isinstance(seconds, bool) \
487
+ and math.isfinite(seconds) and seconds >= 0:
488
+ retry_after = float(seconds)
489
+ return message, code, retry_after
@@ -0,0 +1,71 @@
1
+ """Exception hierarchy for the Blindsight Runtime Security SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class BlindsightError(Exception):
9
+ """Base class for every error raised by this SDK."""
10
+
11
+
12
+ class BlindsightAPIError(BlindsightError):
13
+ """The Runtime Security API returned a non-2xx response.
14
+
15
+ ``code`` mirrors the ``X-Blindsight-Error-Code`` response header when the
16
+ backend sets one (e.g. ``APP_DISABLED``, ``EGRESS_DENIED``).
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ *,
23
+ status_code: int,
24
+ code: Optional[str] = None,
25
+ response_body: Any = None,
26
+ retry_after: Optional[float] = None,
27
+ ) -> None:
28
+ super().__init__(message)
29
+ self.status_code = status_code
30
+ self.code = code
31
+ self.response_body = response_body
32
+ #: Seconds to wait before trying again, from ``Retry-After`` (set on a
33
+ #: paced call over the daily allowance, ``429 DAILY_ALLOWANCE_SOFT_LIMIT``).
34
+ self.retry_after = retry_after
35
+
36
+ def __str__(self) -> str: # pragma: no cover - trivial
37
+ message = self.args[0] if self.args else ""
38
+ suffix = f"HTTP {self.status_code}"
39
+ if self.code:
40
+ suffix += f", code={self.code}"
41
+ return f"{message} ({suffix})"
42
+
43
+
44
+ class BlindsightAuthError(BlindsightAPIError):
45
+ """Authentication/authorization failed (HTTP 401/403).
46
+
47
+ Usually a missing or wrong ``X-API-Key``, or an App the key can't access.
48
+ """
49
+
50
+
51
+ class BlindsightQuotaError(BlindsightAPIError):
52
+ """Runtime Security metering rejected the call (HTTP 402/429).
53
+
54
+ A ``429`` with ``code == "DAILY_ALLOWANCE_SOFT_LIMIT"`` is temporary: the
55
+ day's allowance and its grace margin are used and calls are paced. Wait
56
+ :attr:`retry_after` seconds and send the same call again.
57
+ """
58
+
59
+
60
+ class BlindsightConnectionError(BlindsightError):
61
+ """The request never reached the API (DNS, TLS, timeout, connection reset)."""
62
+
63
+
64
+ class ContentBlocked(BlindsightError):
65
+ """Raised by :meth:`ScanResult.raise_for_block` when a verdict is ``block``."""
66
+
67
+ def __init__(self, result: Any) -> None:
68
+ reason = getattr(result, "blocked_reason", None) or "policy"
69
+ uuid = getattr(result, "uuid", "") or ""
70
+ super().__init__(f"Runtime Security blocked the content: {reason} (event={uuid})")
71
+ self.result = result