zerobom 0.1.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.
Files changed (50) hide show
  1. zerobom/__init__.py +71 -0
  2. zerobom/_version.py +14 -0
  3. zerobom/backends/__init__.py +58 -0
  4. zerobom/backends/_http.py +496 -0
  5. zerobom/backends/base.py +92 -0
  6. zerobom/backends/conformance.py +249 -0
  7. zerobom/backends/dependency_track.py +507 -0
  8. zerobom/backends/k8s_sbom.py +931 -0
  9. zerobom/backends/local_sbom.py +299 -0
  10. zerobom/backends/oci_sbom.py +1227 -0
  11. zerobom/backends/registry.py +283 -0
  12. zerobom/backends/sbom_parser.py +527 -0
  13. zerobom/cli.py +1338 -0
  14. zerobom/data/__init__.py +1 -0
  15. zerobom/data/demo_article.json +8 -0
  16. zerobom/data/demo_extracted.json +48 -0
  17. zerobom/data/demo_sbom.cdx.json +31 -0
  18. zerobom/extract/__init__.py +23 -0
  19. zerobom/extract/base.py +49 -0
  20. zerobom/extract/openai_compat.py +483 -0
  21. zerobom/extract/prompts.py +198 -0
  22. zerobom/ingest/__init__.py +59 -0
  23. zerobom/ingest/fetcher.py +510 -0
  24. zerobom/ingest/prefilter.py +207 -0
  25. zerobom/ingest/rss.py +793 -0
  26. zerobom/ingest/state.py +173 -0
  27. zerobom/models.py +1018 -0
  28. zerobom/outputs/__init__.py +67 -0
  29. zerobom/outputs/github_issue.py +725 -0
  30. zerobom/outputs/json_out.py +83 -0
  31. zerobom/outputs/sarif.py +260 -0
  32. zerobom/outputs/slack.py +487 -0
  33. zerobom/outputs/terminal.py +161 -0
  34. zerobom/outputs/webhook.py +558 -0
  35. zerobom/pipeline.py +396 -0
  36. zerobom/py.typed +0 -0
  37. zerobom/triage/__init__.py +43 -0
  38. zerobom/triage/actions.py +272 -0
  39. zerobom/triage/server.py +543 -0
  40. zerobom/triage/store.py +443 -0
  41. zerobom/verify/__init__.py +95 -0
  42. zerobom/verify/grounding.py +636 -0
  43. zerobom/verify/osv_compiler.py +1567 -0
  44. zerobom/verify/purl.py +1012 -0
  45. zerobom/verify/scorer.py +281 -0
  46. zerobom-0.1.0.dist-info/METADATA +223 -0
  47. zerobom-0.1.0.dist-info/RECORD +50 -0
  48. zerobom-0.1.0.dist-info/WHEEL +4 -0
  49. zerobom-0.1.0.dist-info/entry_points.txt +8 -0
  50. zerobom-0.1.0.dist-info/licenses/LICENSE +200 -0
zerobom/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """zerobom — Deterministic pre-CVE advisory verification engine."""
2
+
3
+ from zerobom._version import __version__
4
+ from zerobom.models import (
5
+ ArticleStateRecord,
6
+ AssetRef,
7
+ ClaimVerificationResult,
8
+ CredibilityReport,
9
+ ExtractedAdvisory,
10
+ ExtractedPackageClaim,
11
+ FeedEntry,
12
+ FeedKind,
13
+ GroundingMatchType,
14
+ GroundingResult,
15
+ GroundingStatus,
16
+ InventoryComponent,
17
+ MatchResult,
18
+ OsvAdvisory,
19
+ OsvAffected,
20
+ OsvPackage,
21
+ OsvRange,
22
+ OsvRangeEvent,
23
+ OsvReference,
24
+ PackageQuery,
25
+ PipelineOutcome,
26
+ PrefilterResult,
27
+ PurlResolutionResult,
28
+ RawArticle,
29
+ RegistryStatus,
30
+ RoutingDecision,
31
+ SourceFeedConfig,
32
+ SourcesConfig,
33
+ SourceTier,
34
+ VersionConstraint,
35
+ VulnerabilitySeverity,
36
+ )
37
+
38
+ __all__ = [
39
+ "ArticleStateRecord",
40
+ "AssetRef",
41
+ "ClaimVerificationResult",
42
+ "CredibilityReport",
43
+ "ExtractedAdvisory",
44
+ "ExtractedPackageClaim",
45
+ "FeedEntry",
46
+ "FeedKind",
47
+ "GroundingMatchType",
48
+ "GroundingResult",
49
+ "GroundingStatus",
50
+ "InventoryComponent",
51
+ "MatchResult",
52
+ "OsvAdvisory",
53
+ "OsvAffected",
54
+ "OsvPackage",
55
+ "OsvRange",
56
+ "OsvRangeEvent",
57
+ "OsvReference",
58
+ "PackageQuery",
59
+ "PipelineOutcome",
60
+ "PrefilterResult",
61
+ "PurlResolutionResult",
62
+ "RawArticle",
63
+ "RegistryStatus",
64
+ "RoutingDecision",
65
+ "SourceFeedConfig",
66
+ "SourceTier",
67
+ "SourcesConfig",
68
+ "VersionConstraint",
69
+ "VulnerabilitySeverity",
70
+ "__version__",
71
+ ]
zerobom/_version.py ADDED
@@ -0,0 +1,14 @@
1
+ """Shared package version and repository metadata constants for ``zerobom``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ try:
8
+ __version__: str = version("zerobom")
9
+ except PackageNotFoundError: # pragma: no cover - uninstalled source fallback
10
+ __version__ = "0.1.0"
11
+
12
+ REPOSITORY_URL: str = "https://github.com/zerobom-dev/zerobom"
13
+ HOMEPAGE_URL: str = "https://zerobom.dev/"
14
+ DEFAULT_USER_AGENT: str = f"zerobom/{__version__} (+{REPOSITORY_URL})"
@@ -0,0 +1,58 @@
1
+ """Cloud-agnostic inventory backend interfaces, plugin registry, parser, and conformance."""
2
+
3
+ from zerobom.backends.base import (
4
+ BackendConfigError,
5
+ BackendError,
6
+ BackendLoadError,
7
+ BackendQueryError,
8
+ InventoryBackend,
9
+ match_advisory_with_backend,
10
+ )
11
+ from zerobom.backends.conformance import (
12
+ BackendConformanceCase,
13
+ BackendConformanceError,
14
+ assert_backend_conformance,
15
+ build_default_conformance_case,
16
+ )
17
+ from zerobom.backends.dependency_track import DependencyTrackBackend
18
+ from zerobom.backends.k8s_sbom import K8sSbomBackend
19
+ from zerobom.backends.local_sbom import LocalSbomBackend, SbomParseError
20
+ from zerobom.backends.oci_sbom import OciSbomBackend
21
+ from zerobom.backends.registry import (
22
+ BACKEND_ENTRY_POINT_GROUP,
23
+ BackendRegistry,
24
+ parse_backend_options,
25
+ )
26
+ from zerobom.backends.sbom_parser import (
27
+ InMemoryComponentIndex,
28
+ derive_sbom_asset,
29
+ parse_cyclonedx_dict,
30
+ parse_sbom_bytes,
31
+ parse_spdx_dict,
32
+ )
33
+
34
+ __all__ = [
35
+ "BACKEND_ENTRY_POINT_GROUP",
36
+ "BackendConfigError",
37
+ "BackendConformanceCase",
38
+ "BackendConformanceError",
39
+ "BackendError",
40
+ "BackendLoadError",
41
+ "BackendQueryError",
42
+ "BackendRegistry",
43
+ "DependencyTrackBackend",
44
+ "InMemoryComponentIndex",
45
+ "InventoryBackend",
46
+ "K8sSbomBackend",
47
+ "LocalSbomBackend",
48
+ "OciSbomBackend",
49
+ "SbomParseError",
50
+ "assert_backend_conformance",
51
+ "build_default_conformance_case",
52
+ "derive_sbom_asset",
53
+ "match_advisory_with_backend",
54
+ "parse_backend_options",
55
+ "parse_cyclonedx_dict",
56
+ "parse_sbom_bytes",
57
+ "parse_spdx_dict",
58
+ ]
@@ -0,0 +1,496 @@
1
+ """Shared internal HTTP transport, TLS, URL, and option helpers for built-in backends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ import ssl
8
+ from collections.abc import Mapping, Sequence
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlsplit, urlunsplit
12
+
13
+ import httpx
14
+
15
+ from zerobom.backends.base import BackendConfigError, BackendQueryError
16
+
17
+ MAX_API_URL_LENGTH = 2048
18
+ DEFAULT_API_TIMEOUT_SECONDS = 15.0
19
+ MAX_API_TIMEOUT_SECONDS = 120.0
20
+ DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024
21
+ REDIRECT_STATUS_CODES: frozenset[int] = frozenset({301, 302, 303, 307, 308})
22
+
23
+
24
+ def validate_no_control_chars(
25
+ value: Any,
26
+ *,
27
+ field_name: str,
28
+ max_length: int = 2048,
29
+ allow_empty: bool = False,
30
+ ) -> str:
31
+ """Validate that an untrusted config value is a bounded string free of control characters.
32
+
33
+ Args:
34
+ value: Untrusted input value.
35
+ field_name: Field label used in diagnostic exceptions.
36
+ max_length: Maximum permitted string length after stripping.
37
+ allow_empty: When ``True``, permit empty strings after stripping.
38
+
39
+ Returns:
40
+ Validated and whitespace-trimmed string.
41
+
42
+ Raises:
43
+ BackendConfigError: If ``value`` is not a string, contains ASCII control characters,
44
+ exceeds ``max_length``, or is empty when ``allow_empty=False``.
45
+ """
46
+ if not isinstance(value, str):
47
+ raise BackendConfigError(f"Configuration option {field_name!r} must be a string.")
48
+ # Check control chars before stripping so trailing CR/LF/NUL are never silently dropped.
49
+ if any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
50
+ raise BackendConfigError(
51
+ f"Configuration option {field_name!r} must not contain control characters."
52
+ )
53
+ cleaned = value.strip()
54
+ if not allow_empty and not cleaned:
55
+ raise BackendConfigError(f"Configuration option {field_name!r} must not be empty.")
56
+ if len(cleaned) > max_length:
57
+ raise BackendConfigError(
58
+ f"Configuration option {field_name!r} exceeds maximum length of {max_length} chars."
59
+ )
60
+ return cleaned
61
+
62
+
63
+ def validate_api_base_url(
64
+ url: Any,
65
+ *,
66
+ allow_insecure_http: bool = False,
67
+ field_name: str = "base_url",
68
+ allow_query: bool = False,
69
+ ) -> str:
70
+ """Validate and normalize an HTTPS (or opted-in HTTP) API endpoint URL.
71
+
72
+ Args:
73
+ url: Candidate URL string.
74
+ allow_insecure_http: Permit ``http://`` URLs when explicitly opted in for local/dev use.
75
+ field_name: Configuration field name for clear diagnostics.
76
+ allow_query: Permit URL query components (used e.g. for OCI Bearer auth realm URLs).
77
+
78
+ Returns:
79
+ Normalized URL string without fragments (and without trailing ``/`` when
80
+ ``allow_query=False``).
81
+
82
+ Raises:
83
+ BackendConfigError: If the URL violates scheme, credential, length, or syntax rules.
84
+ """
85
+ cleaned = validate_no_control_chars(
86
+ url,
87
+ field_name=field_name,
88
+ max_length=MAX_API_URL_LENGTH,
89
+ )
90
+ if any(ch.isspace() for ch in cleaned):
91
+ raise BackendConfigError(
92
+ f"Configuration option {field_name!r} must not contain whitespace."
93
+ )
94
+
95
+ parsed = urlsplit(cleaned)
96
+ scheme = parsed.scheme.lower()
97
+ allowed_schemes = {"https", "http"} if allow_insecure_http else {"https"}
98
+ if scheme not in allowed_schemes:
99
+ if scheme == "http" and not allow_insecure_http:
100
+ raise BackendConfigError(
101
+ f"{field_name!r} requires https:// (set allow_insecure_http=true to permit http://)."
102
+ )
103
+ raise BackendConfigError(f"{field_name!r} must use scheme in {sorted(allowed_schemes)}.")
104
+
105
+ if not parsed.hostname:
106
+ raise BackendConfigError(f"{field_name!r} must include a valid hostname.")
107
+ if parsed.username is not None or parsed.password is not None:
108
+ raise BackendConfigError(f"{field_name!r} must not embed credentials in the URL.")
109
+ if parsed.fragment:
110
+ raise BackendConfigError(f"{field_name!r} must not contain a URL fragment.")
111
+ if parsed.query and not allow_query:
112
+ raise BackendConfigError(f"{field_name!r} must not contain query parameters.")
113
+ if "\\" in parsed.path:
114
+ raise BackendConfigError(f"{field_name!r} must not contain backslashes.")
115
+
116
+ path_segments = [seg for seg in parsed.path.split("/") if seg]
117
+ if any(seg in {".", ".."} for seg in path_segments):
118
+ raise BackendConfigError(f"{field_name!r} must not contain path traversal segments.")
119
+
120
+ normalized_path = parsed.path if allow_query else parsed.path.rstrip("/")
121
+ query = parsed.query if allow_query else ""
122
+ return urlunsplit((scheme, parsed.netloc, normalized_path, query, ""))
123
+
124
+
125
+ def _validate_existing_file(raw_path: str | Path, *, field_name: str) -> Path:
126
+ """Validate that a configured TLS certificate or key path refers to an existing file."""
127
+ path_str = validate_no_control_chars(
128
+ str(raw_path),
129
+ field_name=field_name,
130
+ max_length=2048,
131
+ )
132
+ path = Path(path_str)
133
+ if not path.is_file():
134
+ raise BackendConfigError(
135
+ f"Configured {field_name} path does not exist or is not a file: {path}"
136
+ )
137
+ return path
138
+
139
+
140
+ def resolve_tls_verify(
141
+ *,
142
+ verify_tls: bool = True,
143
+ ca_bundle: str | Path | None = None,
144
+ ca_pem_data: str | None = None,
145
+ client_cert: str | Path | None = None,
146
+ client_key: str | Path | None = None,
147
+ ) -> bool | ssl.SSLContext:
148
+ """Build an ``httpx``-compatible TLS verification setting from backend config.
149
+
150
+ Always returns either ``bool`` or an explicit ``ssl.SSLContext`` (never raw file path
151
+ strings, avoiding ``httpx`` 0.28+ deprecation warnings).
152
+
153
+ Args:
154
+ verify_tls: Whether server TLS certificates must be verified.
155
+ ca_bundle: Optional filesystem path to a PEM CA bundle file.
156
+ ca_pem_data: Optional inline PEM CA certificate text.
157
+ client_cert: Optional client certificate PEM file path for mutual TLS.
158
+ client_key: Optional client private key PEM file path for mutual TLS.
159
+
160
+ Returns:
161
+ ``bool`` or configured :class:`ssl.SSLContext`.
162
+
163
+ Raises:
164
+ BackendConfigError: If conflicting TLS options, missing files, or invalid PEMs occur.
165
+ """
166
+ if (client_cert is None) != (client_key is None):
167
+ raise BackendConfigError("Both client_cert and client_key must be provided together.")
168
+ if ca_bundle is not None and ca_pem_data is not None:
169
+ raise BackendConfigError("Specify either ca_bundle or ca_pem_data, not both.")
170
+ if not verify_tls and (ca_bundle is not None or ca_pem_data is not None):
171
+ raise BackendConfigError("Cannot combine verify_tls=False with a custom CA bundle.")
172
+ if not verify_tls and (client_cert is not None or client_key is not None):
173
+ raise BackendConfigError(
174
+ "Cannot combine verify_tls=False with client certificate authentication."
175
+ )
176
+
177
+ if not verify_tls:
178
+ return False
179
+
180
+ if ca_bundle is None and ca_pem_data is None and client_cert is None:
181
+ return True
182
+
183
+ try:
184
+ if ca_bundle is not None:
185
+ ca_path = _validate_existing_file(ca_bundle, field_name="ca_bundle")
186
+ ctx = ssl.create_default_context(cafile=str(ca_path))
187
+ elif ca_pem_data is not None:
188
+ if not isinstance(ca_pem_data, str) or "\x00" in ca_pem_data or not ca_pem_data.strip():
189
+ raise BackendConfigError("ca_pem_data must be valid non-empty PEM text.")
190
+ if len(ca_pem_data) > 1024 * 1024:
191
+ raise BackendConfigError("ca_pem_data exceeds maximum size of 1 MiB.")
192
+ ctx = ssl.create_default_context(cadata=ca_pem_data)
193
+ else:
194
+ ctx = ssl.create_default_context()
195
+
196
+ if client_cert is not None and client_key is not None:
197
+ cert_path = _validate_existing_file(client_cert, field_name="client_cert")
198
+ key_path = _validate_existing_file(client_key, field_name="client_key")
199
+ ctx.load_cert_chain(certfile=str(cert_path), keyfile=str(key_path))
200
+ except BackendConfigError:
201
+ raise
202
+ except (OSError, ssl.SSLError, ValueError) as exc:
203
+ raise BackendConfigError(f"Invalid TLS configuration: {exc}") from exc
204
+
205
+ return ctx
206
+
207
+
208
+ def redact_url_for_error(url: str, *, redact_path: bool = False) -> str:
209
+ """Return a sanitized URL safe for error messages and logs without secrets or queries.
210
+
211
+ Strips query parameters and URL fragments (which commonly hold Azure SAS tokens or
212
+ presigned URL credentials), and optionally redacts path segments (for webhook endpoints
213
+ whose secret bearer token is encoded in the path).
214
+ """
215
+ parsed = urlsplit(url)
216
+ scheme = parsed.scheme or "https"
217
+ netloc = parsed.netloc
218
+ if not netloc:
219
+ return "<redacted-url>"
220
+ path = "/..." if redact_path else parsed.path
221
+ return urlunsplit((scheme, netloc, path, "", ""))
222
+
223
+
224
+ def read_bounded_response(
225
+ client: httpx.Client,
226
+ method: str,
227
+ url: str,
228
+ *,
229
+ max_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
230
+ params: Mapping[str, Any] | None = None,
231
+ headers: Mapping[str, str] | None = None,
232
+ json_body: Any | None = None,
233
+ auth: httpx.Auth | tuple[str, str] | None = None,
234
+ backend_name: str = "backend",
235
+ redact_url_path: bool = False,
236
+ ) -> tuple[int, httpx.Headers, bytes]:
237
+ """Execute an HTTP request and read the response body with an explicit byte ceiling.
238
+
239
+ Args:
240
+ client: Pre-configured :class:`httpx.Client` (must disable auto-redirects).
241
+ method: HTTP verb (typically ``"GET"`` or ``"POST"``).
242
+ url: Validated target URL.
243
+ max_bytes: Maximum permitted response payload size in bytes.
244
+ params: Optional query string parameters.
245
+ headers: Optional request headers.
246
+ json_body: Optional JSON-serializable request payload.
247
+ auth: Optional per-request HTTP authentication tuple or ``httpx.Auth``.
248
+ backend_name: Backend label for clear error diagnostics.
249
+ redact_url_path: When ``True``, mask the URL path in diagnostic error messages
250
+ (e.g., for secret-bearing Slack/generic webhook paths).
251
+
252
+ Returns:
253
+ Tuple of ``(status_code, response_headers, body_bytes)``.
254
+
255
+ Raises:
256
+ ValueError: If ``max_bytes < 1``.
257
+ BackendQueryError: On transport failure, invalid Content-Length, or size overflow.
258
+ """
259
+ if max_bytes < 1:
260
+ raise ValueError("max_bytes must be >= 1")
261
+
262
+ safe_url = redact_url_for_error(url, redact_path=redact_url_path)
263
+
264
+ try:
265
+ stream_ctx = (
266
+ client.stream(method, url, params=params, headers=headers, json=json_body, auth=auth)
267
+ if auth is not None
268
+ else client.stream(method, url, params=params, headers=headers, json=json_body)
269
+ )
270
+ with stream_ctx as response:
271
+ raw_content_length = response.headers.get("content-length")
272
+ if raw_content_length is not None:
273
+ cl_str = raw_content_length.strip()
274
+ if cl_str.isdigit() and int(cl_str) > max_bytes:
275
+ raise BackendQueryError(
276
+ f"[{backend_name}] Response Content-Length ({cl_str} bytes) exceeds "
277
+ f"limit of {max_bytes} bytes for {safe_url}."
278
+ )
279
+
280
+ buf = bytearray()
281
+ for chunk in response.iter_bytes():
282
+ if len(buf) + len(chunk) > max_bytes:
283
+ raise BackendQueryError(
284
+ f"[{backend_name}] Response payload exceeds limit of "
285
+ f"{max_bytes} bytes for {safe_url}."
286
+ )
287
+ buf.extend(chunk)
288
+
289
+ return response.status_code, response.headers, bytes(buf)
290
+ except BackendQueryError:
291
+ raise
292
+ except httpx.HTTPError as exc:
293
+ # Omit raw exception message to prevent leaking query secrets (?sig=...) or webhook paths.
294
+ raise BackendQueryError(
295
+ f"[{backend_name}] HTTP request failed ({type(exc).__name__}) for {safe_url}."
296
+ ) from exc
297
+
298
+
299
+ def reject_unknown_config_keys(
300
+ config: Mapping[str, Any],
301
+ allowed_keys: frozenset[str],
302
+ *,
303
+ backend_name: str,
304
+ ) -> None:
305
+ """Fail closed when unrecognized keys are passed in backend configuration."""
306
+ unknown = sorted(set(config.keys()) - allowed_keys)
307
+ if unknown:
308
+ raise BackendConfigError(
309
+ f"Unsupported configuration option(s) for {backend_name!r}: {', '.join(unknown)}."
310
+ )
311
+
312
+
313
+ def parse_bool_opt(config: Mapping[str, Any], key: str, *, default: bool) -> bool:
314
+ """Parse a boolean option from native YAML/JSON types or CLI ``key=value`` strings."""
315
+ if key not in config or config[key] is None:
316
+ return default
317
+ raw = config[key]
318
+ if isinstance(raw, bool):
319
+ return raw
320
+ if isinstance(raw, str):
321
+ normalized = raw.strip().lower()
322
+ if normalized in {"1", "true", "yes", "on"}:
323
+ return True
324
+ if normalized in {"0", "false", "no", "off"}:
325
+ return False
326
+ raise BackendConfigError(f"Configuration option {key!r} must be a boolean.")
327
+
328
+
329
+ def parse_int_opt(
330
+ config: Mapping[str, Any],
331
+ key: str,
332
+ *,
333
+ default: int,
334
+ min_value: int,
335
+ max_value: int,
336
+ ) -> int:
337
+ """Parse a bounded integer option from native ints or decimal strings."""
338
+ if key not in config or config[key] is None:
339
+ return default
340
+ raw = config[key]
341
+ if isinstance(raw, bool):
342
+ raise BackendConfigError(f"Configuration option {key!r} must be an integer.")
343
+ try:
344
+ if isinstance(raw, int):
345
+ val = raw
346
+ elif isinstance(raw, str):
347
+ val = int(raw.strip())
348
+ else:
349
+ raise ValueError("non-integer type")
350
+ except ValueError as exc:
351
+ raise BackendConfigError(f"Configuration option {key!r} must be an integer.") from exc
352
+
353
+ if not math.isfinite(val) or val < min_value or val > max_value:
354
+ raise BackendConfigError(
355
+ f"Configuration option {key!r} must be between {min_value} and {max_value}."
356
+ )
357
+ return val
358
+
359
+
360
+ def parse_float_opt(
361
+ config: Mapping[str, Any],
362
+ key: str,
363
+ *,
364
+ default: float,
365
+ min_value: float,
366
+ max_value: float,
367
+ ) -> float:
368
+ """Parse a bounded numeric float option from numbers or strings."""
369
+ if key not in config or config[key] is None:
370
+ return default
371
+ raw = config[key]
372
+ if isinstance(raw, bool):
373
+ raise BackendConfigError(f"Configuration option {key!r} must be a number.")
374
+ try:
375
+ if isinstance(raw, (int, float)):
376
+ val = float(raw)
377
+ elif isinstance(raw, str):
378
+ val = float(raw.strip())
379
+ else:
380
+ raise ValueError("non-numeric type")
381
+ except ValueError as exc:
382
+ raise BackendConfigError(f"Configuration option {key!r} must be a number.") from exc
383
+
384
+ if not math.isfinite(val) or val < min_value or val > max_value:
385
+ raise BackendConfigError(
386
+ f"Configuration option {key!r} must be between {min_value} and {max_value}."
387
+ )
388
+ return val
389
+
390
+
391
+ def parse_optional_str_opt(
392
+ config: Mapping[str, Any],
393
+ key: str,
394
+ *,
395
+ env_var: str | None = None,
396
+ max_length: int = 2048,
397
+ allow_empty: bool = False,
398
+ ) -> str | None:
399
+ """Read an optional string config option with optional environment variable fallback."""
400
+ if key in config and config[key] is not None:
401
+ return validate_no_control_chars(
402
+ config[key],
403
+ field_name=key,
404
+ max_length=max_length,
405
+ allow_empty=allow_empty,
406
+ )
407
+ if env_var is not None:
408
+ env_val = os.environ.get(env_var)
409
+ if env_val is not None and env_val.strip():
410
+ return validate_no_control_chars(
411
+ env_val,
412
+ field_name=env_var,
413
+ max_length=max_length,
414
+ )
415
+ return None
416
+
417
+
418
+ def parse_str_list_opt(
419
+ config: Mapping[str, Any],
420
+ key: str,
421
+ *,
422
+ max_items: int = 100,
423
+ max_item_length: int = 512,
424
+ ) -> tuple[str, ...]:
425
+ """Parse a string list option from a YAML/JSON sequence or comma-separated string."""
426
+ if key not in config or config[key] is None:
427
+ return ()
428
+ raw = config[key]
429
+ items: list[str] = []
430
+ if isinstance(raw, str):
431
+ # Validate the unsplit string first so CR/LF around whitespace is never stripped silently.
432
+ checked_raw = validate_no_control_chars(
433
+ raw,
434
+ field_name=key,
435
+ max_length=max_items * (max_item_length + 2),
436
+ allow_empty=True,
437
+ )
438
+ for part in checked_raw.split(","):
439
+ stripped = part.strip()
440
+ if stripped:
441
+ items.append(
442
+ validate_no_control_chars(
443
+ stripped,
444
+ field_name=key,
445
+ max_length=max_item_length,
446
+ )
447
+ )
448
+ elif isinstance(raw, Sequence) and not isinstance(raw, (bytes, bytearray)):
449
+ for elem in raw:
450
+ items.append(
451
+ validate_no_control_chars(
452
+ elem,
453
+ field_name=key,
454
+ max_length=max_item_length,
455
+ )
456
+ )
457
+ else:
458
+ raise BackendConfigError(
459
+ f"Configuration option {key!r} must be a list of strings or comma-separated string."
460
+ )
461
+
462
+ if len(items) > max_items:
463
+ raise BackendConfigError(
464
+ f"Configuration option {key!r} exceeds maximum count of {max_items} items."
465
+ )
466
+ return tuple(items)
467
+
468
+
469
+ def validate_bounded_int(
470
+ value: Any,
471
+ *,
472
+ field_name: str,
473
+ min_value: int,
474
+ max_value: int,
475
+ ) -> int:
476
+ """Validate that ``value`` is a strict non-boolean integer within inclusive bounds."""
477
+ if isinstance(value, bool) or not isinstance(value, int) or not min_value <= value <= max_value:
478
+ raise BackendConfigError(
479
+ f"Configuration option {field_name!r} must be between {min_value} and {max_value}."
480
+ )
481
+ return value
482
+
483
+
484
+ def validate_timeout_seconds(value: Any) -> float:
485
+ """Validate an HTTP request timeout in ``0.5..MAX_API_TIMEOUT_SECONDS`` seconds."""
486
+ if (
487
+ isinstance(value, bool)
488
+ or not isinstance(value, (int, float))
489
+ or not math.isfinite(float(value))
490
+ or not 0.5 <= float(value) <= MAX_API_TIMEOUT_SECONDS
491
+ ):
492
+ raise BackendConfigError(
493
+ f"Configuration option 'timeout_seconds' must be between "
494
+ f"0.5 and {MAX_API_TIMEOUT_SECONDS}."
495
+ )
496
+ return float(value)