-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepomix-output.xml
More file actions
9800 lines (8673 loc) · 389 KB
/
Copy pathrepomix-output.xml
File metadata and controls
9800 lines (8673 loc) · 389 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
This file is a merged representation of a subset of the codebase, containing specifically included files and files not matching ignore patterns, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Only files matching these patterns are included: **/*
- Files matching these patterns are excluded: .git/**, .hg/**, .svn/**, **/node_modules/**, vendor/**, **/.bundle/**, **/.gradle/**, **/.npm/**, **/.yarn/**, **/target/**, dist/**, build/**, out/**, tmp/**, temp/**, coverage/**, .nyc_output/**, .pytest_cache/**, .mypy_cache/**, **/__pycache__/**, **/*.py[cod], **/.DS_Store, **/Thumbs.db, .idea/**, .vscode/**, **/*.swp, **/*.swo, **/*.bak, **/*.log, **/npm-debug.log*, **/yarn-debug.log*, **/yarn-error.log*, **/repomix-output.*, **/repopack-output.*, .env, .env.*
- Files matching patterns in .gitignore are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
references/
install-tools.md
package-intake.md
parser-contract.md
remediation-policy.md
report-schema.md
scanner-behavior.md
scripts/
vulnscan/
cli/
__init__.py
args.py
output.py
package.py
scan.py
parsers/
__init__.py
containers.py
dependencies.py
secrets.py
static.py
supply_chain.py
utils.py
workflows.py
__init__.py
ci.py
common.py
config.py
discovery.py
engines.py
hygiene.py
inventory.py
orchestration.py
remediation.py
reporting.py
sast.py
sbom.py
secrets.py
supply_chain.py
tracker.py
nightly-vuln-scan.py
validate-config.sh
validate-tools.sh
vuln-scan.py
templates/
config-starter.yaml
tests/
fixtures/
docker/
Dockerfile
github-actions/
.github/
workflows/
ci.yml
go/
go.mod
javascript-no-lock/
package.json
jvm/
pom.xml
monorepo/
apps/
web/
package-lock.json
package.json
packages/
api/
requirements.txt
no-manifest/
README.md
npm/
package-lock.json
package.json
pnpm/
package.json
pnpm-lock.yaml
python/
requirements.txt
rust/
Cargo.lock
Cargo.toml
terraform/
main.tf
vscode-extension/
package.json
yarn/
package.json
yarn.lock
test_cli.py
test_config_discovery_inventory.py
test_engine_dependencies.py
test_engine_external.py
test_parsers.py
test_scanner.py
test_tracker.py
.gitignore
AGENTS.md
INSTALL.md
LICENSE
README.md
repomix.config.json
SKILL.md
TODO.md
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="references/remediation-policy.md">
# Remediation Policy
Scanning is read-only by default. Remediation runs only when the user explicitly
requests it or the command includes `--auto-remediate`.
Use `remediation-prep` before editing when the user wants a fix plan:
```bash
python3 scripts/vuln-scan.py scan \
--root /path/to/repo \
--scan-mode remediation-prep \
--format text
```
Remediation prep groups findings into:
- direct dependency update candidates
- transitive override candidates
- manual major-upgrade candidates
- likely unfixable or design-limitation findings
- tracked secret rotation work
- CI workflow permission or pinning changes
- manual review
When remediation is explicitly enabled, Codex runs once per affected repo with a
bounded prompt and a repo-local working directory. It must not branch, commit,
push, delete unrelated files, rotate credentials, or rewrite history.
Tracker writes must be atomic and must happen only after same-engine
verification. If the tracker JSON is corrupt, create a backup and recover to an
empty tracker rather than failing the whole scan.
</file>
<file path="references/report-schema.md">
# Report Schema
JSON summaries are the source of truth. Text output is a rendering of the same
data.
Top-level fields:
- `generated_at`
- `artifact_dir`
- `scanned_projects`
- `affected_projects`
- `finding_count`
- `severity_counts`
- `engine_counts`
- `category_counts`
- `scanner_stats`
- `commands`
- `scope`
- `remediation`
- `setup_debt`
- `skipped_by_tracker`
- `skipped_targets`
- `coverage`
- `results`
Project results include:
- `label`
- `git_root`
- `ecosystems`
- `findings`
- `setup_debt`
- `coverage`
Coverage states are deliberately separate from finding counts:
- `verified_clean`
- `scanned`
- `not_requested`
- `not_applicable`
- `skipped`
- `unsupported`
- `scanner_missing`
- `scanner_failed`
- `timed_out`
Never infer that a category is clean from zero findings alone. Check the project
coverage state and setup-debt items.
</file>
<file path="references/scanner-behavior.md">
# Scanner Behavior
The scanner CLI is the primary entrypoint:
```bash
python3 scripts/vuln-scan.py scan \
--config templates/config-starter.yaml \
--root /path/to/workspace \
--scan-mode full \
--output /tmp/vuln-summary.json \
--artifact-dir /tmp/vuln-artifacts \
--format text
```
Normal scans are read-only. Remediation requires explicit opt-in:
```bash
python3 scripts/vuln-scan.py scan \
--root /path/to/repo \
--scan-mode dependencies \
--auto-remediate
```
Discovery creates separate project targets for package roots, workflows,
containers, IaC, and VS Code extensions. `package.json` without a supported
lockfile is still a target, but dependency coverage is reported as unsupported
setup debt instead of silently omitting the project.
Scope gates run before scanner execution. Use `--allowed-root`,
`--allowed-label-prefix`, `--forbidden-label-prefix`, and
`--fail-on-scope-violation` for unattended scans.
Clean unattended cron output may be exactly `[SILENT]` only when there are zero
findings, zero setup-debt items, zero scope violations, and no scanner timeout or
parser failure.
</file>
<file path="scripts/vulnscan/cli/__init__.py">
"""Command-line interface for the local vulnerability scanner."""
from __future__ import annotations
import sys
from .args import COMMANDS, build_parser, normalize_argv
from .output import (
SEVERITY_ORDER,
build_plan_summary,
build_scope_failure_summary,
filter_findings_by_severity,
render_package_intake_text,
render_report,
summary_can_be_silent,
write_and_print_summary,
)
from .package import package_intake
from .scan import run_scan
from ..config import load_config
from ..inventory import render_deep_tool_validation, render_engine_inventory, render_tool_validation
__all__ = [
"COMMANDS",
"SEVERITY_ORDER",
"build_parser",
"build_plan_summary",
"build_scope_failure_summary",
"filter_findings_by_severity",
"main",
"normalize_argv",
"package_intake",
"render_package_intake_text",
"render_report",
"run_scan",
"summary_can_be_silent",
"write_and_print_summary",
]
def main(argv: list[str] | None = None) -> int:
command, normalized = normalize_argv(list(sys.argv[1:] if argv is None else argv))
if command == "render-report":
return render_report(normalized)
if command == "package-intake":
return package_intake(normalized)
parser = build_parser()
args = parser.parse_args(normalized)
if args.list_engines:
config = load_config(args.config)
print(render_engine_inventory(args.format, config))
return 0
if args.validate_tools:
config = load_config(args.config)
if args.deep:
print(render_deep_tool_validation(args.format, config))
else:
print(render_tool_validation(args.format, config))
return 0
return run_scan(args)
</file>
<file path="scripts/vulnscan/cli/output.py">
"""CLI report rendering and summary helpers."""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
from typing import Any
from ..common import now_iso
from ..config import cfg_get
from ..inventory import MODE_IMPLEMENTATION
from ..reporting import render_summary_text
SEVERITY_ORDER = {"UNKNOWN": 1, "INFO": 1, "REVIEW": 1, "LOW": 1, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4}
def build_scope_failure_summary(
*,
artifact_dir: Path,
started: float,
scan_mode: str,
projects_count: int,
max_depth: int,
scope_report: dict[str, Any],
skipped_targets: list[dict[str, str]],
) -> dict[str, Any]:
return {
"generated_at": now_iso(),
"artifact_dir": str(artifact_dir),
"scanned_projects": 0,
"affected_projects": 0,
"finding_count": 0,
"severity_counts": {},
"engine_counts": {},
"scanner_stats": {
"duration_seconds": round(time.time() - started, 2),
"scan_mode": scan_mode,
"mode_status": MODE_IMPLEMENTATION[scan_mode],
"project_discovery": {"projects": projects_count, "git_roots": 0, "max_depth": max_depth},
},
"scope": scope_report,
"remediation": {"enabled": False},
"setup_debt": [{"repo": "__scope__", "item": "scope violation; scan not started"}],
"skipped_targets": skipped_targets,
"skipped_by_tracker": 0,
"top_affected": [],
"secret_findings": [],
"results": [],
}
def summary_can_be_silent(summary: dict[str, Any], config: dict[str, Any]) -> bool:
if not bool(cfg_get(config, "scan.silent_when_clean", False)):
return False
stats = summary.get("scanner_stats") or {}
return (
stats.get("command", "scan") == "scan"
and summary.get("finding_count", 0) == 0
and not summary.get("setup_debt")
and not summary.get("scope", {}).get("out_of_scope_count")
and not any((stats.get("osv") or {}).get(key, 0) for key in ("timeout", "parse_failed"))
and not any((stats.get("javascript") or {}).get(key, 0) for key in ("bun_parse_failed", "bun_error", "npm_parse_failed", "npm_error", "pnpm_parse_failed", "pnpm_error"))
and not (stats.get("mode_setup_debt") or [])
)
def write_and_print_summary(summary: dict[str, Any], args: argparse.Namespace, config: dict[str, Any] | None = None) -> None:
if getattr(args, "output", None):
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(summary, indent=2 if args.pretty else None, sort_keys=True), encoding="utf-8")
if config is not None and args.format == "text" and summary_can_be_silent(summary, config):
print("[SILENT]")
return
if args.format == "text":
print(render_summary_text(summary))
else:
print(json.dumps(summary, indent=2 if args.pretty else None, sort_keys=True))
def render_report(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description="Render a saved vulnerability scan JSON summary")
parser.add_argument("summary", type=Path, help="Path to a saved summary JSON file")
parser.add_argument("--format", choices=["json", "text"], default="text")
parser.add_argument("--pretty", action="store_true")
args = parser.parse_args(argv)
summary = json.loads(args.summary.read_text(encoding="utf-8"))
if args.format == "text":
print(render_summary_text(summary))
else:
print(json.dumps(summary, indent=2 if args.pretty else None, sort_keys=True))
return 0
def render_package_intake_text(report: dict[str, Any]) -> str:
lines = [
f"Package intake: {report.get('ecosystem')}:{report.get('package')}",
f"Decision: {report.get('decision')}",
f"Findings: {report.get('finding_count', 0)}",
]
setup_debt = (report.get("scanner_stats") or {}).get("setup_debt") or []
if setup_debt:
lines.append("Setup debt:")
for item in setup_debt[:20]:
lines.append(f"- {item.get('scanner')} {item.get('target')}: {item.get('reason')}")
for finding in report.get("findings", [])[:20]:
lines.append(f"- {finding.get('severity')} {finding.get('rule_id')}: {finding.get('title')}")
return "\n".join(lines)
def filter_findings_by_severity(findings: list[dict[str, Any]], threshold: str) -> tuple[list[dict[str, Any]], int]:
normalized = str(threshold or "none").upper()
if normalized == "NONE":
return findings, 0
minimum = SEVERITY_ORDER.get(normalized, SEVERITY_ORDER["LOW"])
kept = [finding for finding in findings if SEVERITY_ORDER.get(str(finding.get("severity") or "UNKNOWN").upper(), 0) >= minimum]
return kept, len(findings) - len(kept)
def build_plan_summary(
*,
artifact_dir: Path,
started: float,
scan_mode: str,
max_depth: int,
projects: list[Any],
git_roots: list[Path],
scope_report: dict[str, Any],
skipped_targets: list[dict[str, str]],
) -> dict[str, Any]:
return {
"generated_at": now_iso(),
"artifact_dir": str(artifact_dir),
"scanned_projects": 0,
"affected_projects": 0,
"finding_count": 0,
"severity_counts": {},
"engine_counts": {},
"scanner_stats": {
"duration_seconds": round(time.time() - started, 2),
"scan_mode": scan_mode,
"mode_status": MODE_IMPLEMENTATION[scan_mode],
"command": "plan",
"project_discovery": {"projects": len(projects), "git_roots": len(git_roots), "max_depth": max_depth},
},
"scope": scope_report,
"remediation": {"enabled": False},
"setup_debt": [],
"skipped_by_tracker": 0,
"skipped_targets": skipped_targets,
"planned_projects": [
{
"label": project.label,
"path": str(project.path),
"git_root": str(project.git_root) if project.git_root else None,
"ecosystems": sorted(project.ecosystems),
}
for project in projects
],
"top_affected": [],
"secret_findings": [],
"results": [],
}
</file>
<file path="scripts/vulnscan/cli/package.py">
"""Package intake CLI command."""
from __future__ import annotations
import argparse
import json
import tempfile
from pathlib import Path
from .output import render_package_intake_text
from ..config import load_config
from ..supply_chain import run_guarddog_package_intake
def package_intake(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description="Scan a named package before adding it to a repo")
parser.add_argument("ecosystem", choices=["npm", "pypi", "go", "rubygems", "github_action", "extension"])
parser.add_argument("package")
parser.add_argument("--version")
parser.add_argument("--config", type=Path)
parser.add_argument("--artifact-dir", type=Path)
parser.add_argument("--output", type=Path)
parser.add_argument("--format", choices=["json", "text"], default="text")
parser.add_argument("--pretty", action="store_true")
args = parser.parse_args(argv)
config = load_config(args.config)
artifact_dir = args.artifact_dir or Path(tempfile.mkdtemp(prefix="vuln-intake-"))
artifact_dir.mkdir(parents=True, exist_ok=True)
report, _stats = run_guarddog_package_intake(args.ecosystem, args.package, config, artifact_dir, version=args.version)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2 if args.pretty else None, sort_keys=True), encoding="utf-8")
if args.format == "json":
print(json.dumps(report, indent=2 if args.pretty else None, sort_keys=True))
else:
print(render_package_intake_text(report))
return 1 if report["decision"] in {"avoid", "blocked pending review"} else 0
</file>
<file path="scripts/vulnscan/parsers/__init__.py">
"""Scanner output parser compatibility exports."""
from __future__ import annotations
from .containers import parse_trivy
from .dependencies import parse_bun, parse_cargo_audit, parse_npm, parse_osv, parse_pip_audit, parse_pnpm, severity_from_osv
from .secrets import normalize_secret_finding, parse_gitleaks, parse_trufflehog_lines
from .static import parse_grype, parse_scorecard, parse_semgrep, parse_syft_metadata, scorecard_severity, semgrep_severity
from .supply_chain import guarddog_severity, parse_guarddog
from .utils import dedupe_findings, extract_json, first_reference_url, norm_severity, normalize_dependency_finding, normalize_finding, redact_sensitive_values
from .workflows import classify_workflow_issue, parse_actionlint_lines, parse_zizmor, workflow_severity
__all__ = [
"classify_workflow_issue",
"dedupe_findings",
"extract_json",
"first_reference_url",
"guarddog_severity",
"norm_severity",
"normalize_dependency_finding",
"normalize_finding",
"normalize_secret_finding",
"parse_actionlint_lines",
"parse_bun",
"parse_cargo_audit",
"parse_gitleaks",
"parse_grype",
"parse_guarddog",
"parse_npm",
"parse_osv",
"parse_pip_audit",
"parse_pnpm",
"parse_scorecard",
"parse_semgrep",
"parse_syft_metadata",
"parse_trivy",
"parse_trufflehog_lines",
"parse_zizmor",
"redact_sensitive_values",
"scorecard_severity",
"semgrep_severity",
"severity_from_osv",
"workflow_severity",
]
</file>
<file path="scripts/vulnscan/parsers/dependencies.py">
"""Dependency vulnerability parser adapters."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
from .utils import dedupe_findings, norm_severity, normalize_dependency_finding
def severity_from_osv(vuln: dict[str, Any]) -> str:
db = vuln.get("database_specific") or {}
sev = db.get("severity") or vuln.get("severity")
if isinstance(sev, str):
return norm_severity(sev)
if isinstance(sev, list):
for item in sev:
if not isinstance(item, dict):
continue
score = item.get("score")
if not isinstance(score, str):
continue
match = re.search(r"(\d+(?:\.\d+)?)", score)
if not match:
continue
numeric = float(match.group(1))
if numeric >= 9:
return "CRITICAL"
if numeric >= 7:
return "HIGH"
if numeric >= 4:
return "MEDIUM"
return "LOW"
return "UNKNOWN"
def parse_osv(path: Path, source_label: str) -> tuple[list[dict[str, Any]], str | None]:
if not path.exists() or path.stat().st_size == 0:
return [], "empty_output"
try:
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
except Exception as exc:
return [], f"parse_failed:{exc}"
findings: list[dict[str, Any]] = []
for result in data.get("results") or []:
for package in result.get("packages") or []:
pinfo = package.get("package") or {}
name = pinfo.get("name") or package.get("name") or "unknown"
ecosystem = pinfo.get("ecosystem") or package.get("ecosystem") or "unknown"
for vuln in package.get("vulnerabilities") or []:
refs = vuln.get("references") or []
url = None
if refs and isinstance(refs[0], dict):
url = refs[0].get("url")
findings.append(
normalize_dependency_finding(
{
"source_engine": "osv-scanner",
"source_label": source_label,
"package": name,
"ecosystem": ecosystem,
"severity": severity_from_osv(vuln),
"advisory_id": vuln.get("id"),
"title": vuln.get("summary") or vuln.get("details", "")[:160] or vuln.get("id"),
"url": url or f"https://osv.dev/vulnerability/{vuln.get('id')}",
}
)
)
return dedupe_findings(findings), None
def parse_bun(data: Any) -> tuple[list[dict[str, Any]], str | None]:
if data is None:
return [], "parse_failed"
if isinstance(data, dict) and "error" in data:
err = data.get("error") or {}
return [], f"bun_error:{err.get('code', 'unknown')}"
findings: list[dict[str, Any]] = []
for package, advisories in (data or {}).items():
if not isinstance(advisories, list):
continue
for advisory in advisories:
if not isinstance(advisory, dict):
continue
findings.append(
normalize_dependency_finding(
{
"source_engine": "bun-audit",
"package": package,
"ecosystem": "npm",
"severity": norm_severity(advisory.get("severity")),
"advisory_id": str(advisory.get("id")) if advisory.get("id") is not None else None,
"title": advisory.get("title") or "",
"url": advisory.get("url"),
"fixed_version": advisory.get("patched_versions") or advisory.get("patchedVersions"),
}
)
)
return findings, None
def parse_npm(data: Any) -> tuple[list[dict[str, Any]], str | None]:
if data is None:
return [], "parse_failed"
if isinstance(data, dict) and "error" in data and not data.get("vulnerabilities"):
err = data.get("error") or {}
return [], f"npm_error:{err.get('code', 'unknown')}"
findings: list[dict[str, Any]] = []
for package, info in (data.get("vulnerabilities") or {}).items():
if not isinstance(info, dict):
continue
via = info.get("via") or []
severity = norm_severity(info.get("severity"))
direct = [x for x in via if isinstance(x, dict)]
if direct:
for advisory in direct:
findings.append(
normalize_dependency_finding(
{
"source_engine": "npm-audit",
"package": package,
"ecosystem": "npm",
"severity": norm_severity(advisory.get("severity") or severity),
"advisory_id": str(advisory.get("source") or advisory.get("id")) if (advisory.get("source") or advisory.get("id")) is not None else None,
"title": advisory.get("title") or advisory.get("name") or "",
"url": advisory.get("url"),
}
)
)
else:
findings.append(
normalize_dependency_finding(
{
"source_engine": "npm-audit",
"package": package,
"ecosystem": "npm",
"severity": severity,
"advisory_id": None,
"title": f"npm audit vulnerability in {package}",
"url": None,
}
)
)
return findings, None
def parse_pnpm(data: Any) -> tuple[list[dict[str, Any]], str | None]:
if data is None:
return [], "parse_failed"
if isinstance(data, dict) and "error" in data and not data.get("advisories"):
err = data.get("error") or {}
return [], f"pnpm_error:{err.get('code', 'unknown')}"
findings: list[dict[str, Any]] = []
advisories = data.get("advisories") if isinstance(data, dict) else None
if not isinstance(advisories, dict):
return [], "parse_failed"
for advisory_id, advisory in advisories.items():
if not isinstance(advisory, dict):
continue
findings.append(
normalize_dependency_finding(
{
"source_engine": "pnpm-audit",
"package": advisory.get("module_name") or advisory.get("name") or "unknown",
"ecosystem": "npm",
"severity": norm_severity(advisory.get("severity")),
"advisory_id": str(advisory.get("id") or advisory_id) if (advisory.get("id") or advisory_id) is not None else None,
"title": advisory.get("title") or advisory.get("overview") or "",
"url": advisory.get("url"),
"fixed_version": advisory.get("patched_versions") or advisory.get("patchedVersions"),
}
)
)
return findings, None
def parse_pip_audit(data: Any) -> tuple[list[dict[str, Any]], str | None]:
if data is None:
return [], "parse_failed"
if isinstance(data, list):
dependencies = data
elif isinstance(data, dict):
if data.get("error") and not data.get("dependencies"):
return [], f"pip_audit_error:{data.get('error')}"
dependencies = data.get("dependencies") or data.get("results") or []
else:
return [], "parse_failed"
if not isinstance(dependencies, list):
return [], "parse_failed"
findings: list[dict[str, Any]] = []
for dependency in dependencies:
if not isinstance(dependency, dict):
continue
name = dependency.get("name") or dependency.get("package") or "unknown"
version = dependency.get("version")
vulns = dependency.get("vulns") or dependency.get("vulnerabilities") or []
if not isinstance(vulns, list):
continue
for vuln in vulns:
if not isinstance(vuln, dict):
continue
aliases = vuln.get("aliases") if isinstance(vuln.get("aliases"), list) else []
advisory_id = vuln.get("id") or vuln.get("advisory_id") or (aliases[0] if aliases else None)
fix_versions = vuln.get("fix_versions") or vuln.get("fix_versions_for_vulnerability") or vuln.get("fixed_versions")
findings.append(
normalize_dependency_finding(
{
"source_engine": "pip-audit",
"package": name,
"ecosystem": "python",
"installed_version": version,
"severity": vuln.get("severity") or vuln.get("cvss_severity") or "UNKNOWN",
"advisory_id": str(advisory_id) if advisory_id is not None else None,
"title": vuln.get("description") or vuln.get("summary") or str(advisory_id or ""),
"url": vuln.get("url") or (f"https://osv.dev/vulnerability/{advisory_id}" if advisory_id else None),
"fixed_version": fix_versions,
}
)
)
return dedupe_findings(findings), None
def parse_cargo_audit(data: Any) -> tuple[list[dict[str, Any]], str | None]:
if data is None or not isinstance(data, dict):
return [], "parse_failed"
vulnerabilities = data.get("vulnerabilities") or {}
if not isinstance(vulnerabilities, dict):
return [], "parse_failed"
vuln_list = vulnerabilities.get("list") or vulnerabilities.get("warnings") or []
if not isinstance(vuln_list, list):
return [], "parse_failed"
findings: list[dict[str, Any]] = []
for item in vuln_list:
if not isinstance(item, dict):
continue
advisory = item.get("advisory") or {}
package = item.get("package") or {}
versions = item.get("versions") or {}
if not isinstance(advisory, dict):
advisory = {}
if not isinstance(package, dict):
package = {}
if not isinstance(versions, dict):
versions = {}
package_name = package.get("name") or advisory.get("package") or item.get("package") or "unknown"
severity = advisory.get("severity") or advisory.get("cvss") or "UNKNOWN"
findings.append(
normalize_dependency_finding(
{
"source_engine": "cargo-audit",
"package": package_name,
"ecosystem": "rust",
"installed_version": package.get("version"),
"severity": severity,
"advisory_id": advisory.get("id"),
"title": advisory.get("title") or advisory.get("description") or advisory.get("id"),
"url": advisory.get("url") or (f"https://rustsec.org/advisories/{advisory.get('id')}" if advisory.get("id") else None),
"fixed_version": versions.get("patched"),
}
)
)
return dedupe_findings(findings), None
</file>
<file path="scripts/vulnscan/parsers/secrets.py">
"""Secret scanner parser adapters."""
from __future__ import annotations
import json
from typing import Any
from .utils import dedupe_findings, norm_severity
def normalize_secret_finding(finding: dict[str, Any]) -> dict[str, Any]:
out = dict(finding)
for key in ("value", "Value", "secret", "Secret", "match", "Match", "raw", "Raw", "rawV2", "RawV2"):
out.pop(key, None)
out.setdefault("category", "secret")
out.setdefault("confidence", "detected_pattern")
out.setdefault("verification_state", "unverified")
out.setdefault("git_tracked", None)
if "detector" not in out and out.get("type"):
out["detector"] = out["type"]
out["severity"] = norm_severity(out.get("severity"))
return out
def parse_gitleaks(data: Any, source_label: str) -> tuple[list[dict[str, Any]], str | None]:
if data is None:
return [], "parse_failed"
if isinstance(data, dict) and data.get("error"):
return [], f"gitleaks_error:{data.get('error')}"
if not isinstance(data, list):
return [], "parse_failed"
findings: list[dict[str, Any]] = []
for item in data:
if not isinstance(item, dict):
continue
findings.append(
normalize_secret_finding(
{
"source_engine": "gitleaks",
"source_label": source_label,
"type": item.get("RuleID") or item.get("ruleID") or item.get("Description") or "secret",
"severity": "HIGH",
"title": item.get("Description") or item.get("RuleID") or "Secret detected",
"file": item.get("File") or item.get("file"),
"line": item.get("StartLine") or item.get("startLine") or item.get("Line") or item.get("line"),
"commit": item.get("Commit") or item.get("commit"),
"git_tracked": True if (item.get("Commit") or item.get("commit")) else None,
"verification_state": "unverified",
"confidence": "detected_pattern",
"remediation_hint": "Rotate the credential if real, remove it from tracked files, and consider history cleanup.",
}
)
)
return dedupe_findings(findings), None
def parse_trufflehog_lines(text: str, source_label: str, include_unverified: bool = False) -> tuple[list[dict[str, Any]], str | None]:
findings: list[dict[str, Any]] = []
if not text.strip():
return findings, None
for raw_line in text.splitlines():
if not raw_line.strip():
continue
try:
item = json.loads(raw_line)
except json.JSONDecodeError:
return [], "parse_failed"
if not isinstance(item, dict):
continue
verified = bool(item.get("Verified") if "Verified" in item else item.get("verified"))
if not include_unverified and not verified:
continue
source_metadata = item.get("SourceMetadata") if isinstance(item.get("SourceMetadata"), dict) else {}
data = source_metadata.get("Data") if isinstance(source_metadata.get("Data"), dict) else {}
git_data = data.get("Git") if isinstance(data.get("Git"), dict) else {}
findings.append(
normalize_secret_finding(
{
"source_engine": "trufflehog",
"source_label": source_label,
"type": item.get("DetectorName") or item.get("detectorName") or item.get("DetectorType") or "secret",
"severity": "CRITICAL" if verified else "HIGH",
"title": item.get("DetectorName") or item.get("detectorName") or "Secret detected",
"file": git_data.get("file") or git_data.get("File") or item.get("SourceName") or item.get("sourceName"),
"line": git_data.get("line") or git_data.get("Line"),
"commit": git_data.get("commit") or git_data.get("Commit"),
"git_tracked": True,
"verification_state": "verified" if verified else "unverified",
"confidence": "verified" if verified else "detected_pattern",
"remediation_hint": "Rotate verified credentials immediately, remove them from tracked files, and evaluate history cleanup.",
}
)
)
return dedupe_findings(findings), None
</file>
<file path="scripts/vulnscan/parsers/static.py">
"""Static analysis, SBOM, and hygiene parser adapters."""
from __future__ import annotations
from typing import Any
from .utils import dedupe_findings, norm_severity, normalize_dependency_finding, normalize_finding
def semgrep_severity(value: Any) -> str:
text = str(value or "UNKNOWN").upper()
if text == "ERROR":
return "HIGH"
if text == "WARNING":
return "MEDIUM"
if text == "INFO":
return "LOW"
return norm_severity(text)
def parse_semgrep(data: Any, source_label: str) -> tuple[list[dict[str, Any]], str | None]:
if data is None or not isinstance(data, dict):
return [], "parse_failed"
if data.get("errors") and not isinstance(data.get("results"), list):
return [], f"semgrep_error:{data.get('errors')}"
results = data.get("results")
if not isinstance(results, list):
return [], "parse_failed"
findings: list[dict[str, Any]] = []
for item in results:
if not isinstance(item, dict):
continue
extra = item.get("extra") if isinstance(item.get("extra"), dict) else {}
start = item.get("start") if isinstance(item.get("start"), dict) else {}
metadata = extra.get("metadata") if isinstance(extra.get("metadata"), dict) else {}
rule_id = item.get("check_id") or item.get("rule_id") or "semgrep"
findings.append(
normalize_finding(
{
"source_engine": "semgrep",
"source_label": source_label,