secguard-cli 1.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.
secguard/config.py ADDED
@@ -0,0 +1,172 @@
1
+ from pathlib import Path
2
+ import json
3
+ import os
4
+ import warnings
5
+ import httpx
6
+
7
+ CONFIG_DIR = Path.home() / ".secguard"
8
+ CONFIG_FILE = CONFIG_DIR / "config.json"
9
+
10
+
11
+ NON_CHAT_MODEL_MARKERS = (
12
+ "whisper", "orpheus", "tts", "guard", "playai", "embed", "moderation",
13
+ "imagen", "veo", "allam", "safeguard",
14
+ )
15
+ PREFERRED_GROQ_MODELS = (
16
+ "llama-3.3-70b-versatile",
17
+ "qwen/qwen3-32b",
18
+ "moonshotai/kimi-k2-instruct",
19
+ )
20
+
21
+
22
+ def fetch_active_models(base_url: str, api_key: str) -> list[str]:
23
+ """Fetch available chat models and omit known non-chat models."""
24
+ try:
25
+ url = f"{base_url.rstrip('/')}/models"
26
+ headers = {"Authorization": f"Bearer {api_key}"}
27
+ resp = httpx.get(url, headers=headers, timeout=8.0)
28
+ if resp.status_code != 200:
29
+ return []
30
+
31
+ payload = resp.json()
32
+ entries = payload.get("data") if isinstance(payload, dict) else None
33
+ if not isinstance(entries, list):
34
+ return []
35
+
36
+ models = []
37
+ for entry in entries:
38
+ if not isinstance(entry, dict):
39
+ continue
40
+ model_id = entry.get("id")
41
+ if not isinstance(model_id, str) or not model_id:
42
+ continue
43
+ if any(marker in model_id.lower() for marker in NON_CHAT_MODEL_MARKERS):
44
+ continue
45
+ models.append(model_id)
46
+ return models
47
+ except (httpx.HTTPError, ValueError, TypeError, AttributeError):
48
+ return []
49
+
50
+
51
+ def order_active_models(models: list[str]) -> list[str]:
52
+ preferred_order = {
53
+ model: index for index, model in enumerate(PREFERRED_GROQ_MODELS)
54
+ }
55
+
56
+ def priority(item: tuple[int, str]) -> tuple[int, int]:
57
+ index, model = item
58
+ normalized = model.lower()
59
+ if "llama-4" in normalized or "llama-3" in normalized:
60
+ return 0, index
61
+ if "qwen3" in normalized or "gpt-oss" in normalized:
62
+ return len(preferred_order) + 2, index
63
+ if normalized in preferred_order:
64
+ return preferred_order[normalized] + 1, index
65
+ if "32b" in normalized or "versatile" in normalized:
66
+ return len(preferred_order) + 3, index
67
+ if "20b" in normalized:
68
+ return len(preferred_order) + 4, index
69
+ return len(preferred_order) + 5, index
70
+
71
+ return [
72
+ model
73
+ for _, model in sorted(enumerate(models), key=priority)
74
+ ]
75
+
76
+
77
+ def select_active_model(models: list[str]) -> str | None:
78
+ ordered_models = order_active_models(models)
79
+ return ordered_models[0] if ordered_models else None
80
+
81
+
82
+ def select_next_active_model(models: list[str], tried: set[str]) -> str | None:
83
+ return next(
84
+ (model for model in order_active_models(models) if model not in tried),
85
+ None,
86
+ )
87
+
88
+
89
+ def fetch_active_model(base_url: str, api_key: str, fallback: str) -> str:
90
+ """Fetch an active model or return the provider-specific fallback."""
91
+ return select_active_model(fetch_active_models(base_url, api_key)) or fallback
92
+
93
+
94
+ def detect_provider_from_key(raw_key: str) -> dict:
95
+ """Detect the provider and active model from the API key prefix."""
96
+ key = raw_key.strip()
97
+
98
+ if not key or key.lower() == "ollama":
99
+ return {
100
+ "provider": "ollama",
101
+ "base_url": "http://localhost:11434/v1",
102
+ "api_key": "ollama",
103
+ "model": "qwen2.5-coder:7b",
104
+ }
105
+
106
+ if key.startswith("gsk_"):
107
+ base_url = "https://api.groq.com/openai/v1"
108
+ models = fetch_active_models(base_url, key)
109
+ model = select_active_model(models)
110
+ if model is None:
111
+ raise ValueError(
112
+ "Could not fetch Groq chat models. Check the API key and access to /models."
113
+ )
114
+ return {
115
+ "provider": "groq",
116
+ "base_url": base_url,
117
+ "api_key": key,
118
+ "model": model,
119
+ "models": models,
120
+ }
121
+
122
+ if key.startswith("AIza"):
123
+ base_url = "https://generativelanguage.googleapis.com/v1beta/openai/"
124
+ return {
125
+ "provider": "gemini",
126
+ "base_url": base_url,
127
+ "api_key": key,
128
+ "model": fetch_active_model(base_url, key, "gemini-2.5-flash"),
129
+ }
130
+
131
+ if key.startswith("sk-or-"):
132
+ base_url = "https://openrouter.ai/api/v1"
133
+ return {
134
+ "provider": "openrouter",
135
+ "base_url": base_url,
136
+ "api_key": key,
137
+ "model": fetch_active_model(base_url, key, "qwen/qwen-2.5-coder-32b-instruct:free"),
138
+ }
139
+
140
+ raise ValueError(
141
+ "Unrecognized API key. Enter a valid Groq (gsk_...), Gemini (AIza...), or OpenRouter (sk-or-...) key."
142
+ )
143
+
144
+
145
+ def save_config(provider_name: str, base_url: str, api_key: str, model: str) -> None:
146
+ """Save user settings to a local JSON file."""
147
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
148
+ data = {
149
+ "provider": provider_name,
150
+ "base_url": base_url,
151
+ "api_key": api_key,
152
+ "model": model,
153
+ }
154
+ CONFIG_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
155
+ try:
156
+ os.chmod(CONFIG_FILE, 0o600)
157
+ except OSError as error:
158
+ warnings.warn(
159
+ f"Could not set configuration file permissions to 0o600: {error}",
160
+ RuntimeWarning,
161
+ stacklevel=2,
162
+ )
163
+
164
+
165
+ def load_config() -> dict | None:
166
+ """Read saved settings, returning None if no settings have been saved."""
167
+ if not CONFIG_FILE.exists():
168
+ return None
169
+ try:
170
+ return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
171
+ except (json.JSONDecodeError, OSError):
172
+ return None
@@ -0,0 +1,513 @@
1
+ import json
2
+ import re
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import httpx
7
+
8
+ OSV_QUERY_BATCH_URL = "https://api.osv.dev/v1/querybatch"
9
+ OSV_TIMEOUT_SECONDS = 10.0
10
+ IGNORED_DIRECTORIES = {".git", ".venv", "venv", "node_modules", "__pycache__"}
11
+ REQUIREMENT_PATTERN = re.compile(
12
+ r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]+\])?\s*"
13
+ r"(?:(==|>=|~=|>)\s*([^\s,;#]+))?\s*$"
14
+ )
15
+ NPM_VERSION_PATTERN = re.compile(
16
+ r"^[~^]?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$"
17
+ )
18
+ NPM_LOCK_VERSION_PATTERN = re.compile(
19
+ r"^v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$"
20
+ )
21
+ CVE_OR_GHSA_PATTERN = re.compile(
22
+ r"^(?:CVE-\d{4}-\d+|GHSA-[A-Z0-9]{4}(?:-[A-Z0-9]{4}){2})$",
23
+ re.IGNORECASE,
24
+ )
25
+
26
+
27
+ def _warn(message: str) -> None:
28
+ print(f"Warning: {message}", file=sys.stderr)
29
+
30
+
31
+ def _manifest_paths(target: Path) -> list[Path]:
32
+ def supported(name: str) -> bool:
33
+ normalized = name.lower()
34
+ return (
35
+ normalized == "package.json"
36
+ or normalized == "package-lock.json"
37
+ or normalized.startswith("requirements") and normalized.endswith(".txt")
38
+ )
39
+
40
+ if target.is_file():
41
+ return [target] if supported(target.name) else []
42
+ return sorted(
43
+ path
44
+ for path in target.rglob("*")
45
+ if path.is_file()
46
+ and supported(path.name)
47
+ and not any(part in IGNORED_DIRECTORIES for part in path.relative_to(target).parts)
48
+ )
49
+
50
+
51
+ def _pypi_name(name: str) -> str:
52
+ return re.sub(r"[-_.]+", "-", name).lower()
53
+
54
+
55
+ def _append_record(records: list[dict], index: dict, record: dict) -> None:
56
+ key = (
57
+ record["ecosystem"],
58
+ record["name"].casefold(),
59
+ record["version"],
60
+ record["version_spec"],
61
+ )
62
+ if key not in index:
63
+ index[key] = len(records)
64
+ records.append({**record, "locations": [record["location"]]})
65
+ return
66
+
67
+ existing = records[index[key]]
68
+ if record["location"] not in existing["locations"]:
69
+ existing["locations"].append(record["location"])
70
+
71
+
72
+ def _requirements_records(path: Path, root: Path, records: list[dict], index: dict) -> None:
73
+ try:
74
+ lines = path.read_text(encoding="utf-8").splitlines()
75
+ except (OSError, UnicodeError) as error:
76
+ _warn(f"{path} could not be read: {error}")
77
+ return
78
+
79
+ relative_path = path.name if root.is_file() else path.relative_to(root).as_posix()
80
+ for line_number, raw_line in enumerate(lines, start=1):
81
+ requirement = raw_line.split("#", 1)[0].split(";", 1)[0].strip()
82
+ match = REQUIREMENT_PATTERN.fullmatch(requirement)
83
+ if not match:
84
+ continue
85
+ name, operator, requested_version = match.groups()
86
+ if operator == "==" and (
87
+ not requested_version
88
+ or requested_version.startswith("=")
89
+ or "*" in requested_version
90
+ ):
91
+ continue
92
+
93
+ is_pinned = operator == "=="
94
+ version = requested_version if operator else None
95
+ version_spec = (
96
+ requested_version
97
+ if is_pinned
98
+ else f"{operator}{requested_version}"
99
+ if operator
100
+ else "unspecified"
101
+ )
102
+ _append_record(records, index, {
103
+ "ecosystem": "PyPI",
104
+ "name": _pypi_name(name),
105
+ "version": version,
106
+ "version_spec": version_spec,
107
+ "version_pinned": is_pinned,
108
+ "location": {
109
+ "file": relative_path,
110
+ "line": line_number,
111
+ "vulnerable_code": requirement,
112
+ "fixed_code_prefix": f"{name}==",
113
+ "fixed_code_suffix": "",
114
+ },
115
+ })
116
+
117
+
118
+ def _package_json_records(path: Path, root: Path, records: list[dict], index: dict) -> None:
119
+ try:
120
+ source = path.read_text(encoding="utf-8")
121
+ manifest = json.loads(source)
122
+ except (OSError, UnicodeError) as error:
123
+ _warn(f"{path} could not be read: {error}")
124
+ return
125
+ except json.JSONDecodeError as error:
126
+ _warn(f"{path} is not valid JSON; dependencies were skipped ({error.msg}).")
127
+ return
128
+
129
+ if not isinstance(manifest, dict):
130
+ return
131
+
132
+ relative_path = path.name if root.is_file() else path.relative_to(root).as_posix()
133
+ lines = source.splitlines()
134
+ for section in ("dependencies", "devDependencies"):
135
+ dependencies = manifest.get(section)
136
+ if not isinstance(dependencies, dict):
137
+ continue
138
+ for name, version_spec in dependencies.items():
139
+ if not isinstance(name, str) or not isinstance(version_spec, str):
140
+ continue
141
+ version_spec = version_spec.strip()
142
+ match = NPM_VERSION_PATTERN.fullmatch(version_spec)
143
+ if match:
144
+ version = match.group(1)
145
+ elif version_spec.lower() in {"*", "latest"}:
146
+ version = None
147
+ else:
148
+ continue
149
+
150
+ property_pattern = re.compile(rf'"{re.escape(name)}"\s*:')
151
+ line_number = next(
152
+ (number for number, line in enumerate(lines, start=1) if property_pattern.search(line)),
153
+ 1,
154
+ )
155
+ vulnerable_code = f'"{name}": "{version_spec}"'
156
+ _append_record(records, index, {
157
+ "ecosystem": "npm",
158
+ "name": name,
159
+ "version": version,
160
+ "version_spec": version_spec,
161
+ "version_pinned": version is not None and version_spec == version,
162
+ "location": {
163
+ "file": relative_path,
164
+ "line": line_number,
165
+ "vulnerable_code": vulnerable_code,
166
+ "fixed_code_prefix": f'"{name}": "',
167
+ "fixed_code_suffix": '"',
168
+ },
169
+ })
170
+
171
+
172
+ def _lock_package_name(package_path: str) -> str:
173
+ if "node_modules/" not in package_path:
174
+ return ""
175
+ remainder = package_path.rsplit("node_modules/", 1)[1].strip("/")
176
+ parts = remainder.split("/")
177
+ if not parts or not parts[0]:
178
+ return ""
179
+ if parts[0].startswith("@"):
180
+ return "/".join(parts[:2]) if len(parts) > 1 else ""
181
+ return parts[0]
182
+
183
+
184
+ def _lock_entry_line(lines: list[str], key: str, version: str) -> int:
185
+ property_pattern = re.compile(rf'^\s*"{re.escape(key)}"\s*:')
186
+ version_pattern = re.compile(
187
+ rf'^\s*"version"\s*:\s*"{re.escape(version)}"\s*,?\s*$'
188
+ )
189
+ for index, line in enumerate(lines):
190
+ if not property_pattern.search(line):
191
+ continue
192
+ if any(version_pattern.search(candidate) for candidate in lines[index + 1:index + 24]):
193
+ return index + 1
194
+ return next(
195
+ (index for index, line in enumerate(lines, start=1) if property_pattern.search(line)),
196
+ 1,
197
+ )
198
+
199
+
200
+ def _append_npm_lock_record(
201
+ name: str,
202
+ version: str,
203
+ package_path: str,
204
+ relative_path: str,
205
+ lines: list[str],
206
+ records: list[dict],
207
+ index: dict,
208
+ ):
209
+ normalized_version = NPM_LOCK_VERSION_PATTERN.fullmatch(version)
210
+ if not normalized_version:
211
+ return
212
+ resolved_version = normalized_version.group(1)
213
+ _append_record(records, index, {
214
+ "ecosystem": "npm",
215
+ "name": name,
216
+ "version": resolved_version,
217
+ "version_spec": resolved_version,
218
+ "version_pinned": True,
219
+ "location": {
220
+ "file": relative_path,
221
+ "line": _lock_entry_line(lines, package_path, version),
222
+ "vulnerable_code": f"{name}@{resolved_version}",
223
+ "fixed_code_prefix": f"{name}@",
224
+ "fixed_code_suffix": "",
225
+ },
226
+ })
227
+
228
+
229
+ def _package_lock_records(path: Path, root: Path, records: list[dict], index: dict) -> None:
230
+ try:
231
+ source = path.read_text(encoding="utf-8")
232
+ manifest = json.loads(source)
233
+ except (OSError, UnicodeError) as error:
234
+ _warn(f"{path} could not be read: {error}")
235
+ return
236
+ except json.JSONDecodeError as error:
237
+ _warn(f"{path} is not valid JSON; dependencies were skipped ({error.msg}).")
238
+ return
239
+
240
+ if not isinstance(manifest, dict):
241
+ _warn(f"{path} is not a valid package-lock object; dependencies were skipped.")
242
+ return
243
+
244
+ relative_path = path.name if root.is_file() else path.relative_to(root).as_posix()
245
+ lines = source.splitlines()
246
+ packages = manifest.get("packages")
247
+ if isinstance(packages, dict) and packages:
248
+ for package_path, package in packages.items():
249
+ if not isinstance(package_path, str) or not isinstance(package, dict):
250
+ continue
251
+ name = _lock_package_name(package_path)
252
+ version = package.get("version")
253
+ if name and isinstance(version, str):
254
+ _append_npm_lock_record(
255
+ name, version, package_path, relative_path, lines, records, index
256
+ )
257
+ return
258
+
259
+ def visit_dependencies(dependencies: object):
260
+ if not isinstance(dependencies, dict):
261
+ return
262
+ for name, dependency in dependencies.items():
263
+ if not isinstance(name, str) or not isinstance(dependency, dict):
264
+ continue
265
+ version = dependency.get("version")
266
+ if isinstance(version, str):
267
+ _append_npm_lock_record(
268
+ name, version, name, relative_path, lines, records, index
269
+ )
270
+ visit_dependencies(dependency.get("dependencies"))
271
+
272
+ visit_dependencies(manifest.get("dependencies"))
273
+
274
+
275
+ def _fixed_version(vulnerability: dict, package: dict) -> str | None:
276
+ affected_packages = vulnerability.get("affected")
277
+ if not isinstance(affected_packages, list):
278
+ return None
279
+ for affected in affected_packages:
280
+ if not isinstance(affected, dict):
281
+ continue
282
+ affected_package = affected.get("package") or {}
283
+ if not isinstance(affected_package, dict):
284
+ continue
285
+ if (
286
+ affected_package.get("ecosystem") != package["ecosystem"]
287
+ or str(affected_package.get("name", "")).casefold() != package["name"].casefold()
288
+ ):
289
+ continue
290
+ ranges = affected.get("ranges")
291
+ if not isinstance(ranges, list):
292
+ continue
293
+ for version_range in ranges:
294
+ if not isinstance(version_range, dict):
295
+ continue
296
+ events = version_range.get("events")
297
+ if not isinstance(events, list):
298
+ continue
299
+ for event in events:
300
+ if not isinstance(event, dict):
301
+ continue
302
+ fixed = event.get("fixed")
303
+ if isinstance(fixed, str) and fixed:
304
+ return fixed
305
+ return None
306
+
307
+
308
+ def _severity(vulnerability: dict) -> str:
309
+ database_specific = vulnerability.get("database_specific") or {}
310
+ candidates = []
311
+
312
+ def add_name(value):
313
+ if not isinstance(value, str):
314
+ return
315
+ normalized = value.strip().upper()
316
+ if normalized == "MODERATE":
317
+ normalized = "MEDIUM"
318
+ if normalized in {"CRITICAL", "HIGH", "MEDIUM", "LOW"}:
319
+ candidates.append(normalized)
320
+
321
+ def add_score(value):
322
+ try:
323
+ score = float(value)
324
+ except (TypeError, ValueError, OverflowError):
325
+ return
326
+ if score >= 9:
327
+ candidates.append("CRITICAL")
328
+ elif score >= 7:
329
+ candidates.append("HIGH")
330
+ elif score >= 4:
331
+ candidates.append("MEDIUM")
332
+ elif score > 0:
333
+ candidates.append("LOW")
334
+
335
+ if isinstance(database_specific, dict):
336
+ add_name(database_specific.get("severity"))
337
+ for key in ("severity", "severities"):
338
+ entries = vulnerability.get(key)
339
+ if isinstance(entries, str):
340
+ add_name(entries)
341
+ elif isinstance(entries, dict):
342
+ entries = list(entries.values())
343
+ if isinstance(entries, list):
344
+ for entry in entries:
345
+ if isinstance(entry, str):
346
+ add_name(entry)
347
+ elif isinstance(entry, dict):
348
+ add_name(entry.get("severity") or entry.get("level"))
349
+ add_score(entry.get("score"))
350
+
351
+ if not candidates:
352
+ return "UNKNOWN"
353
+ rank = {"LOW": 1, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4}
354
+ return max(candidates, key=rank.__getitem__)
355
+
356
+
357
+ def _cwe(vulnerability: dict) -> str | None:
358
+ database_specific = vulnerability.get("database_specific") or {}
359
+ cwe_ids = database_specific.get("cwe_ids") if isinstance(database_specific, dict) else []
360
+ if not isinstance(cwe_ids, list):
361
+ return None
362
+ for cwe in cwe_ids:
363
+ if isinstance(cwe, str) and re.fullmatch(r"CWE-\d+", cwe, re.IGNORECASE):
364
+ return cwe.upper()
365
+ return None
366
+
367
+
368
+ def _vulnerability_ids(vulnerability: dict) -> list[str]:
369
+ aliases = vulnerability.get("aliases") or []
370
+ all_ids = [vulnerability.get("id"), *(aliases if isinstance(aliases, list) else [])]
371
+ matching = []
372
+ for identifier in all_ids:
373
+ if isinstance(identifier, str) and CVE_OR_GHSA_PATTERN.fullmatch(identifier):
374
+ if identifier.upper() not in matching:
375
+ matching.append(identifier.upper())
376
+ return matching or ([vulnerability["id"]] if isinstance(vulnerability.get("id"), str) else [])
377
+
378
+
379
+ def _findings_for_vulnerability(vulnerability: dict, package: dict) -> list[dict]:
380
+ identifiers = _vulnerability_ids(vulnerability)
381
+ if not identifiers:
382
+ return []
383
+
384
+ fixed_version = _fixed_version(vulnerability, package)
385
+ summary = str(
386
+ vulnerability.get("summary")
387
+ or vulnerability.get("details")
388
+ or "OSV.dev vulnerability advisory."
389
+ )
390
+ ids_text = ", ".join(identifiers)
391
+ issue = f"Dependency vulnerability: {ids_text}"
392
+ fixed_code = ""
393
+ if package["version"] is None:
394
+ summary = (
395
+ f"{summary} The manifest does not pin a version "
396
+ f"({package['version_spec']}); the OSV query used only package "
397
+ f"{package['name']} in the {package['ecosystem']} ecosystem."
398
+ )
399
+ elif not package.get(
400
+ "version_pinned",
401
+ package["version_spec"] == package["version"],
402
+ ):
403
+ summary = (
404
+ f"{summary} The manifest version is not fully pinned "
405
+ f"({package['version_spec']}); the OSV query used lower-bound "
406
+ f"version {package['version']}."
407
+ )
408
+ if fixed_version:
409
+ fixed_code = (
410
+ package["location"]["fixed_code_prefix"]
411
+ + fixed_version
412
+ + package["location"]["fixed_code_suffix"]
413
+ )
414
+ summary += f" Safe version recommendation: {fixed_version}."
415
+
416
+ findings = []
417
+ for location in package["locations"]:
418
+ findings.append({
419
+ "file": location["file"],
420
+ "line": location["line"],
421
+ "is_binary": False,
422
+ "is_vulnerable": True,
423
+ "is_dependency": True,
424
+ "package": package["name"],
425
+ "ecosystem": package["ecosystem"],
426
+ "version": package["version"] or "unspecified",
427
+ "version_spec": package["version_spec"],
428
+ "vulnerability_ids": identifiers,
429
+ "fixed_version": fixed_version,
430
+ "issue": issue,
431
+ "severity": _severity(vulnerability),
432
+ "cwe": _cwe(vulnerability) or "",
433
+ "explanation": summary,
434
+ "code": location["vulnerable_code"],
435
+ "context": location["vulnerable_code"],
436
+ "vulnerable_code": location["vulnerable_code"],
437
+ "fixed_code": fixed_code,
438
+ })
439
+ return findings
440
+
441
+
442
+ def scan_dependencies(target_path: str | Path) -> list[dict]:
443
+ """Scan supported manifests and query OSV.dev for resolved or ranged packages."""
444
+ root = Path(target_path).resolve()
445
+ if not root.exists():
446
+ raise FileNotFoundError(f"Target path not found: {root}")
447
+
448
+ records: list[dict] = []
449
+ record_indexes: dict[tuple[str, str, str | None, str], int] = {}
450
+ for path in _manifest_paths(root):
451
+ name = path.name.lower()
452
+ if name.startswith("requirements") and name.endswith(".txt"):
453
+ _requirements_records(path, root, records, record_indexes)
454
+ elif name == "package.json":
455
+ _package_json_records(path, root, records, record_indexes)
456
+ elif name == "package-lock.json":
457
+ _package_lock_records(path, root, records, record_indexes)
458
+
459
+ if not records:
460
+ return []
461
+
462
+ queries = []
463
+ for record in records:
464
+ query = {
465
+ "package": {"name": record["name"], "ecosystem": record["ecosystem"]},
466
+ }
467
+ if record["version"] is not None:
468
+ query["version"] = record["version"]
469
+ queries.append(query)
470
+ try:
471
+ response = httpx.post(
472
+ OSV_QUERY_BATCH_URL,
473
+ json={"queries": queries},
474
+ timeout=OSV_TIMEOUT_SECONDS,
475
+ )
476
+ response.raise_for_status()
477
+ payload = response.json()
478
+ results = payload.get("results") if isinstance(payload, dict) else None
479
+ except httpx.HTTPError as error:
480
+ _warn(f"OSV.dev connection failed; dependency scan was skipped ({error}).")
481
+ return []
482
+ except (AttributeError, TypeError, ValueError) as error:
483
+ _warn(f"Could not read OSV.dev response; dependency scan was skipped ({error}).")
484
+ return []
485
+
486
+ if not isinstance(results, list) or len(results) != len(records):
487
+ _warn(
488
+ "OSV.dev response is not in the expected batch format; "
489
+ "dependency scan was skipped."
490
+ )
491
+ return []
492
+
493
+ findings = []
494
+ for record, result in zip(records, results):
495
+ if not isinstance(result, dict):
496
+ _warn("A malformed package result in the OSV.dev batch response was skipped.")
497
+ continue
498
+ vulnerabilities = result.get("vulns")
499
+ if vulnerabilities is None:
500
+ vulnerabilities = []
501
+ if not isinstance(vulnerabilities, list):
502
+ _warn(f"Malformed vulnerability list for OSV.dev package {record['name']} was skipped.")
503
+ continue
504
+ for vulnerability in vulnerabilities:
505
+ if not isinstance(vulnerability, dict):
506
+ continue
507
+ if (
508
+ record["version"] is None
509
+ and _severity(vulnerability) not in {"CRITICAL", "HIGH"}
510
+ ):
511
+ continue
512
+ findings.extend(_findings_for_vulnerability(vulnerability, record))
513
+ return findings