stackparity 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.
- stackparity/__init__.py +17 -0
- stackparity/_engine/agents/investigator.py +294 -0
- stackparity/_engine/agents/memory_agent.py +37 -0
- stackparity/_engine/agents/pipeline_agent.py +152 -0
- stackparity/_engine/agents/remediation_agent.py +248 -0
- stackparity/_engine/agents/runtime.py +177 -0
- stackparity/_engine/agents/specialists.py +709 -0
- stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
- stackparity/_engine/cli/__init__.py +2 -0
- stackparity/_engine/cli/main.py +1252 -0
- stackparity/_engine/cli/remediate.py +461 -0
- stackparity/_engine/cli/term.py +44 -0
- stackparity/_engine/config/__init__.py +0 -0
- stackparity/_engine/config/constants.py +88 -0
- stackparity/_engine/config/loader.py +155 -0
- stackparity/_engine/config/settings.py +108 -0
- stackparity/_engine/containers/__init__.py +12 -0
- stackparity/_engine/containers/discovery.py +143 -0
- stackparity/_engine/containers/models.py +72 -0
- stackparity/_engine/containers/trivy_image_scanner.py +165 -0
- stackparity/_engine/core/__init__.py +0 -0
- stackparity/_engine/core/capabilities.py +107 -0
- stackparity/_engine/core/finding_schema.py +305 -0
- stackparity/_engine/core/git_manager.py +206 -0
- stackparity/_engine/core/http.py +64 -0
- stackparity/_engine/core/models.py +109 -0
- stackparity/_engine/core/netpolicy.py +242 -0
- stackparity/_engine/core/plugins.py +43 -0
- stackparity/_engine/core/repository_inspector.py +243 -0
- stackparity/_engine/core/safe_env.py +48 -0
- stackparity/_engine/core/scan_orchestrator.py +289 -0
- stackparity/_engine/core/scan_state.py +58 -0
- stackparity/_engine/core/url_validator.py +135 -0
- stackparity/_engine/ecosystems/__init__.py +1 -0
- stackparity/_engine/ecosystems/registry.py +138 -0
- stackparity/_engine/evidence/__init__.py +1 -0
- stackparity/_engine/evidence/store.py +65 -0
- stackparity/_engine/explainability/__init__.py +0 -0
- stackparity/_engine/explainability/evidence_formatter.py +30 -0
- stackparity/_engine/explainability/explanation_engine.py +132 -0
- stackparity/_engine/explainability/explanation_validator.py +54 -0
- stackparity/_engine/explainability/prompt_templates.py +18 -0
- stackparity/_engine/graph/__init__.py +0 -0
- stackparity/_engine/graph/dependency_tracer.py +86 -0
- stackparity/_engine/graph/graph_builder.py +165 -0
- stackparity/_engine/graph/graph_diff.py +57 -0
- stackparity/_engine/graph/graph_exporter.py +194 -0
- stackparity/_engine/graph/graph_validator.py +46 -0
- stackparity/_engine/graph/impact_analyzer.py +23 -0
- stackparity/_engine/graph/tree_view.py +185 -0
- stackparity/_engine/intel/__init__.py +0 -0
- stackparity/_engine/intel/epss.py +53 -0
- stackparity/_engine/llm/__init__.py +1 -0
- stackparity/_engine/llm/client.py +138 -0
- stackparity/_engine/monitor/__init__.py +0 -0
- stackparity/_engine/monitor/watch.py +171 -0
- stackparity/_engine/non_cve/__init__.py +7 -0
- stackparity/_engine/non_cve/base.py +62 -0
- stackparity/_engine/non_cve/iac.py +144 -0
- stackparity/_engine/non_cve/sast.py +272 -0
- stackparity/_engine/non_cve/supply_chain.py +147 -0
- stackparity/_engine/orchestration/__init__.py +1 -0
- stackparity/_engine/orchestration/pipeline.py +279 -0
- stackparity/_engine/orchestration/supervisor.py +167 -0
- stackparity/_engine/pipeline_analysis/__init__.py +0 -0
- stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
- stackparity/_engine/pipeline_analysis/ci.py +189 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
- stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
- stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
- stackparity/_engine/pipeline_analysis/eol.py +62 -0
- stackparity/_engine/pipeline_analysis/models.py +37 -0
- stackparity/_engine/policy/__init__.py +0 -0
- stackparity/_engine/policy/engine.py +216 -0
- stackparity/_engine/policy/resources/default.yaml +56 -0
- stackparity/_engine/policy/resources/strict.yaml +35 -0
- stackparity/_engine/reachability/__init__.py +0 -0
- stackparity/_engine/reachability/app_reachability.py +186 -0
- stackparity/_engine/reachability/scanners.py +215 -0
- stackparity/_engine/remediation/__init__.py +0 -0
- stackparity/_engine/remediation/adapters.py +198 -0
- stackparity/_engine/remediation/apply_local.py +309 -0
- stackparity/_engine/remediation/code_fixes.py +383 -0
- stackparity/_engine/remediation/compat.py +156 -0
- stackparity/_engine/remediation/container_plan.py +127 -0
- stackparity/_engine/remediation/delivery.py +31 -0
- stackparity/_engine/remediation/export.py +44 -0
- stackparity/_engine/remediation/lifecycle.py +623 -0
- stackparity/_engine/remediation/local_trial.py +358 -0
- stackparity/_engine/remediation/patchers.py +215 -0
- stackparity/_engine/remediation/planner.py +285 -0
- stackparity/_engine/remediation/pr_template_engine.py +234 -0
- stackparity/_engine/remediation/reachability_impact.py +147 -0
- stackparity/_engine/remediation/versions.py +92 -0
- stackparity/_engine/remediation/whatif.py +64 -0
- stackparity/_engine/remediation/worktree_pr.py +434 -0
- stackparity/_engine/reporting/__init__.py +0 -0
- stackparity/_engine/reporting/counts.py +63 -0
- stackparity/_engine/reporting/fix_pdf.py +343 -0
- stackparity/_engine/reporting/fix_report.py +135 -0
- stackparity/_engine/reporting/json_exporter.py +61 -0
- stackparity/_engine/reporting/report_generator.py +200 -0
- stackparity/_engine/reporting/sarif.py +71 -0
- stackparity/_engine/reporting/vex.py +57 -0
- stackparity/_engine/reporting/view.py +166 -0
- stackparity/_engine/risk_analysis/__init__.py +0 -0
- stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
- stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
- stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
- stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
- stackparity/_engine/risk_analysis/function_impact.py +184 -0
- stackparity/_engine/risk_analysis/production_context.py +252 -0
- stackparity/_engine/risk_analysis/risk_rules.py +81 -0
- stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
- stackparity/_engine/sandbox/__init__.py +0 -0
- stackparity/_engine/sandbox/runner.py +142 -0
- stackparity/_engine/sbom/__init__.py +0 -0
- stackparity/_engine/sbom/adapters/__init__.py +19 -0
- stackparity/_engine/sbom/adapters/builtin.py +29 -0
- stackparity/_engine/sbom/adapters/syft.py +26 -0
- stackparity/_engine/sbom/adapters/trivy.py +76 -0
- stackparity/_engine/sbom/builtin_generator.py +227 -0
- stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
- stackparity/_engine/sbom/exporters.py +153 -0
- stackparity/_engine/sbom/fusion/__init__.py +5 -0
- stackparity/_engine/sbom/fusion/engine.py +315 -0
- stackparity/_engine/sbom/fusion/hashes.py +47 -0
- stackparity/_engine/sbom/fusion/ledger.py +96 -0
- stackparity/_engine/sbom/fusion/registries.py +271 -0
- stackparity/_engine/sbom/fusion/resolver.py +143 -0
- stackparity/_engine/sbom/fusion/writer.py +114 -0
- stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
- stackparity/_engine/sbom/merge.py +71 -0
- stackparity/_engine/sbom/package_extractors/common.py +104 -0
- stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
- stackparity/_engine/sbom/package_extractors/npm.py +206 -0
- stackparity/_engine/sbom/package_extractors/others.py +267 -0
- stackparity/_engine/sbom/package_extractors/python.py +143 -0
- stackparity/_engine/sbom/quality_analyzer.py +191 -0
- stackparity/_engine/sbom/scanner_engine.py +98 -0
- stackparity/_engine/sbom/syft_runner.py +100 -0
- stackparity/_engine/sbom/tool_locator.py +69 -0
- stackparity/_engine/sbom/trivy_runner.py +82 -0
- stackparity/_engine/storage/__init__.py +0 -0
- stackparity/_engine/storage/cache.py +56 -0
- stackparity/_engine/storage/database.py +295 -0
- stackparity/_engine/storage/memory.py +146 -0
- stackparity/_engine/suspicious_changes/__init__.py +12 -0
- stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
- stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
- stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
- stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
- stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
- stackparity/_engine/suspicious_changes/package_risk.py +78 -0
- stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
- stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
- stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
- stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
- stackparity/_engine/tools/__init__.py +1 -0
- stackparity/_engine/tools/builtin.py +93 -0
- stackparity/_engine/tools/registry.py +66 -0
- stackparity/_engine/ui/__init__.py +0 -0
- stackparity/_engine/ui/components/__init__.py +0 -0
- stackparity/_engine/ui/components/common.py +238 -0
- stackparity/_engine/ui/components/live_progress.py +157 -0
- stackparity/_engine/ui/components/memory_panel.py +82 -0
- stackparity/_engine/ui/pages/__init__.py +0 -0
- stackparity/_engine/ui/pages/agents_page.py +76 -0
- stackparity/_engine/ui/pages/architecture_page.py +44 -0
- stackparity/_engine/ui/pages/fixes_page.py +98 -0
- stackparity/_engine/ui/pages/graph_page.py +203 -0
- stackparity/_engine/ui/pages/health_page.py +117 -0
- stackparity/_engine/ui/pages/monitor_page.py +67 -0
- stackparity/_engine/ui/pages/pipeline_page.py +219 -0
- stackparity/_engine/ui/pages/remediation_page.py +409 -0
- stackparity/_engine/ui/pages/reports_page.py +54 -0
- stackparity/_engine/ui/pages/sbom_page.py +210 -0
- stackparity/_engine/ui/pages/scan_page.py +131 -0
- stackparity/_engine/ui/pages/suspicious_page.py +551 -0
- stackparity/_engine/ui/pages/vulns_page.py +201 -0
- stackparity/_engine/ui/state.py +116 -0
- stackparity/_engine/ui/theme.py +201 -0
- stackparity/_engine/ui/visualizations/__init__.py +0 -0
- stackparity/_engine/ui/visualizations/graphs.py +373 -0
- stackparity/_engine/vulnerability/__init__.py +0 -0
- stackparity/_engine/vulnerability/cvss.py +58 -0
- stackparity/_engine/vulnerability/kev_client.py +47 -0
- stackparity/_engine/vulnerability/nvd_client.py +74 -0
- stackparity/_engine/vulnerability/osv_client.py +139 -0
- stackparity/_engine/vulnerability/remediation_engine.py +50 -0
- stackparity/_engine/vulnerability/verification.py +94 -0
- stackparity/_engine/vulnerability/version_matcher.py +299 -0
- stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
- stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
- stackparity/cli.py +30 -0
- stackparity/dashboard_app.py +95 -0
- stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
- stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
- stackparity/web_dist/index.html +13 -0
- stackparity/web_server.py +533 -0
- stackparity-1.0.0.dist-info/METADATA +204 -0
- stackparity-1.0.0.dist-info/RECORD +212 -0
- stackparity-1.0.0.dist-info/WHEEL +4 -0
- stackparity-1.0.0.dist-info/entry_points.txt +2 -0
- stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Human-readable consolidated security report (Markdown and HTML)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import html
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _md_table(rows: list[list[str]], header: list[str]) -> str:
|
|
9
|
+
if not rows:
|
|
10
|
+
return "_None._\n"
|
|
11
|
+
out = ["| " + " | ".join(header) + " |", "|" + "|".join("---" for _ in header) + "|"]
|
|
12
|
+
for r in rows:
|
|
13
|
+
out.append("| " + " | ".join(str(c).replace("|", "\\|").replace("\n", " ") for c in r) + " |")
|
|
14
|
+
return "\n".join(out) + "\n"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _guardian_sections(result: dict, extras: dict) -> list[str]:
|
|
18
|
+
"""Sections required in the report: prioritised actions with evidence, pipeline, package risk, remediation + validation, policy, AI disclosure, remaining risk, audit trail."""
|
|
19
|
+
L: list[str] = []
|
|
20
|
+
risk = {a["finding_id"]: a for a in result.get("risk_assessments", [])}
|
|
21
|
+
inv = result.get("investigations") or {}
|
|
22
|
+
vulns = {f["finding_id"]: f for f in result.get("vulnerabilities", [])}
|
|
23
|
+
an = result.get("analyst") or {}
|
|
24
|
+
if an:
|
|
25
|
+
L.append("## Executive summary\n")
|
|
26
|
+
L.append(f"**{an.get('headline')}**\n")
|
|
27
|
+
for p_ in an.get("paragraphs", []):
|
|
28
|
+
L.append(f"- {p_}")
|
|
29
|
+
L.append("")
|
|
30
|
+
top = sorted(inv.values(), key=lambda i: (risk.get(i["finding_id"], {}).get("priority", "P9"), -risk.get(i["finding_id"], {}).get("score", 0)))
|
|
31
|
+
top = [i for i in top if risk.get(i["finding_id"], {}).get("priority") in ("P0", "P1")][:12]
|
|
32
|
+
L.append("## Prioritised findings (P0/P1) with evidence\n")
|
|
33
|
+
if top:
|
|
34
|
+
rows = []
|
|
35
|
+
for i in top:
|
|
36
|
+
f, a = vulns[i["finding_id"]], risk.get(i["finding_id"], {})
|
|
37
|
+
rows.append([a.get("priority"), f["finding_id"], f"{f['package_name']} {f['installed_version']}", f["primary_id"], f["severity"] or "n/a", i["verdict"].replace("_", " "), f"{i['confidence']['label']} ({i['confidence']['score']})",
|
|
38
|
+
f"{f['epss']:.1%}" if f.get("epss") is not None else "n/a", "KEV" if f["kev"] else "", " ".join(f"`{e}`" for e in i["evidence_ids"][:3])])
|
|
39
|
+
L.append(_md_table(rows, ["Priority", "ID", "Package", "Advisory", "CVSS", "Verdict", "Confidence", "EPSS", "KEV", "Evidence"]))
|
|
40
|
+
for i in top[:6]:
|
|
41
|
+
L.append(f"- **{i['finding_id']}** - {i['rationale']}" + (" _(AI-assisted, grounded)_" if i.get("ai_assisted") else ""))
|
|
42
|
+
L.append("")
|
|
43
|
+
else:
|
|
44
|
+
L.append("_No P0/P1 findings._\n")
|
|
45
|
+
cnt: dict[str, int] = {}
|
|
46
|
+
for i in inv.values():
|
|
47
|
+
cnt[i["verdict"]] = cnt.get(i["verdict"], 0) + 1
|
|
48
|
+
if cnt:
|
|
49
|
+
L.append("Verdicts across all findings: " + ", ".join(f"{k.replace('_', ' ')} {v}" for k, v in sorted(cnt.items(), key=lambda kv: -kv[1])) + ". Reachability is package-level import evidence, not a call graph; 'no import evidence' is not proof of safety.\n")
|
|
50
|
+
pl = result.get("pipeline") or {}
|
|
51
|
+
if pl.get("findings"):
|
|
52
|
+
L.append("## Pipeline and container findings\n")
|
|
53
|
+
L.append(_md_table([[f["finding_id"], f["severity"], f["rule_id"], f["title"], f"{f['file']}:{f['line']}" if f["line"] else f["file"], risk.get(f["finding_id"], {}).get("label", "")] for f in pl["findings"][:60]],
|
|
54
|
+
["ID", "Severity", "Rule", "Finding", "Where", "Risk"]))
|
|
55
|
+
pk = (result.get("package_risk") or {}).get("findings") or []
|
|
56
|
+
if pk:
|
|
57
|
+
L.append("## Package risk signals\n")
|
|
58
|
+
L.append(_md_table([[f["finding_id"], f["severity"], f["rule_id"], f["subject"], f["title"]] for f in pk[:40]], ["ID", "Severity", "Signal", "Package", "Finding"]))
|
|
59
|
+
rem = (result.get("remediation") or {}).get("items") or []
|
|
60
|
+
approvals = extras.get("approvals") or {}
|
|
61
|
+
if rem:
|
|
62
|
+
L.append("## Recommended actions and validation\n")
|
|
63
|
+
rows = []
|
|
64
|
+
for r_ in rem:
|
|
65
|
+
wi = r_.get("what_if") or {}
|
|
66
|
+
rows.append([r_["id"], r_["priority"], r_["action"], r_["title"], len(wi.get("fixed", [])) if wi else "n/a", len(wi.get("remaining", [])) if wi else "n/a", len(wi.get("newly_introduced", [])) if wi else "n/a",
|
|
67
|
+
(r_.get("compatibility") or {}).get("breaking_risk", ""), (r_.get("validation") or {}).get("patch_applies"), approvals.get(r_.get("fingerprint"), {}).get("state", "pending")])
|
|
68
|
+
L.append(_md_table(rows, ["ID", "Priority", "Action", "Proposal", "Fixed", "Remaining", "New", "Breaking risk", "Patch applies", "Approval"]))
|
|
69
|
+
L.append("Validation is a static what-if (registry-resolved dependency tree + OSV re-match + before/after SBOM diff). The repository's build and tests were **not** run unless a sandbox result is listed. Proposals are never applied automatically.\n")
|
|
70
|
+
if result.get("policy_result"):
|
|
71
|
+
pr = result["policy_result"]
|
|
72
|
+
L.append(f"## Policy gate: {'PASS' if pr['passed'] else 'FAIL'} (`{pr['policy']}`)\n")
|
|
73
|
+
L.append(f"{pr['blocking']} blocking, {pr['warnings']} warning(s), {pr['info']} info, {pr['waived']} waived.\n")
|
|
74
|
+
L.append(_md_table([[v["rule_id"], v["action"], v["subject"]] for v in pr["violations"][:30]], ["Rule", "Action", "Subject"]))
|
|
75
|
+
L.append("## Responsible AI and automation disclosure\n")
|
|
76
|
+
llm_calls = result.get("llm_calls") or []
|
|
77
|
+
ai = [i for i in inv.values() if i.get("ai_assisted")]
|
|
78
|
+
L.append(f"- Detection, matching, scoring, reachability, EPSS/KEV lookups, what-if simulation and policy evaluation are **deterministic and rule-based**.")
|
|
79
|
+
L.append(f"- LLM use in this scan: **{'yes (' + str(len(llm_calls)) + ' call(s), ' + str(len(ai)) + ' investigation(s) accepted after grounding checks)' if llm_calls else 'none'}**. Prompts never contain source code beyond short import snippets, and secrets are redacted before sending.")
|
|
80
|
+
L.append("- AI proposals are accepted only if they cite existing evidence ids, mention only facts present in the evidence, and do not contradict hard evidence; rejected proposals are recorded.")
|
|
81
|
+
L.append("- Every remediation requires explicit human approval; nothing is applied, pushed or merged by the tool.\n")
|
|
82
|
+
L.append("## Remaining and accepted risk\n")
|
|
83
|
+
dec = extras.get("decisions") or {}
|
|
84
|
+
open_p = [i for i in top if dec.get((result.get("memory") or {}).get("fingerprints", {}).get(i["finding_id"], "")) is None]
|
|
85
|
+
L.append(f"- Open P0/P1 findings: **{len(open_p)}**; analyst decisions on record: **{len(dec)}**.")
|
|
86
|
+
for fp, d in list(dec.items())[:15]:
|
|
87
|
+
L.append(f" - {d['decision'].replace('_', ' ')}: {d.get('title') or fp} - {d['reason']}" + (f" (expires {d['expires_at'][:10]})" if d.get("expires_at") else ""))
|
|
88
|
+
L.append("")
|
|
89
|
+
audit = extras.get("audit") or []
|
|
90
|
+
if audit:
|
|
91
|
+
L.append("## Audit trail\n")
|
|
92
|
+
L.append(_md_table([[a["at"], a["actor"], a["action"], a["subject"], a["detail"]] for a in audit[:25]], ["When", "Who", "Action", "Subject", "Detail"]))
|
|
93
|
+
return L
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def generate_markdown(result: dict, extras: dict | None = None) -> str:
|
|
97
|
+
r, s = result["repo"], result.get("summary", {})
|
|
98
|
+
risk = {a["finding_id"]: a for a in result.get("risk_assessments", [])}
|
|
99
|
+
expl = result.get("explanations", {})
|
|
100
|
+
L: list[str] = []
|
|
101
|
+
L.append(f"# Supply Chain Security Report - {r['name']}\n")
|
|
102
|
+
from reporting.view import coverage
|
|
103
|
+
cov = coverage(result)
|
|
104
|
+
if not cov["complete"]:
|
|
105
|
+
L.append("> **Incomplete coverage: the absence of a finding below is not proof of safety.**")
|
|
106
|
+
L.extend(f"> - {gap}" for gap in cov["gaps"])
|
|
107
|
+
L.append("")
|
|
108
|
+
L.append(f"- **Repository:** {r['url']}\n- **Branch/ref:** {r.get('branch') or r.get('ref') or 'default'}\n- **Commit:** `{r['commit_sha']}`\n"
|
|
109
|
+
f"- **Scan ID:** {r['scan_id']} | **Scanned:** {r['scan_timestamp']}\n- **Status:** {result.get('status')}\n"
|
|
110
|
+
f"- **Tools:** " + ", ".join(f"{k} {v}" for k, v in result.get("tool_versions", {}).items()) + "\n")
|
|
111
|
+
L.append("> This report lists findings with evidence. **An absence of findings is not proof that the repository is safe**; "
|
|
112
|
+
"see 'Coverage and limitations'.\n")
|
|
113
|
+
L.append("## Summary\n")
|
|
114
|
+
L.append(_md_table([[k, v] for k, v in [
|
|
115
|
+
("Components (packages)", s.get("components")), ("Vulnerability findings (confirmed)", s.get("vulnerabilities_confirmed")),
|
|
116
|
+
("Vulnerability findings (unconfirmed)", s.get("vulnerabilities_unknown")), ("Direct / transitive vulnerable", f"{s.get('vuln_direct')} / {s.get('vuln_transitive')}"),
|
|
117
|
+
("Known exploited (KEV)", s.get("kev")), ("With fix available", s.get("with_fix")),
|
|
118
|
+
("Typosquatting candidates", s.get("typosquatting")), ("Suspicious/unexplained lockfile changes", s.get("lockfile_findings")),
|
|
119
|
+
("Vulnerability risk: CRITICAL/HIGH/MEDIUM/LOW", " / ".join(str(s.get("by_risk", {}).get(l, 0)) for l in ("CRITICAL", "HIGH", "MEDIUM", "LOW")))]], ["Metric", "Value"]))
|
|
120
|
+
L += _guardian_sections(result, extras or {})
|
|
121
|
+
q = result.get("quality", {})
|
|
122
|
+
L.append("## SBOM and quality\n")
|
|
123
|
+
L.append(f"- Inventory source: **{result.get('inventory_source')}**; inventory status: **{q.get('inventory_status')}**; relationships: **{q.get('dependency_relationships')}**; metadata: **{q.get('metadata_status')}**")
|
|
124
|
+
L.append(f"- Missing metadata: {q.get('missing_metadata')}; unresolved components: {q.get('unresolved_components')}; lockfile entries not in SBOM: {q.get('lockfile_missing_from_sbom_count')}\n")
|
|
125
|
+
L.append("## Vulnerabilities\n")
|
|
126
|
+
rows = []
|
|
127
|
+
for f in result.get("vulnerabilities", []):
|
|
128
|
+
a = risk.get(f["finding_id"], {})
|
|
129
|
+
rows.append([f["finding_id"], f["primary_id"], f"{f['package_name']} {f['installed_version']}", f["severity"] or "n/a",
|
|
130
|
+
f["cvss_score"] if f["cvss_score"] is not None else "n/a", f["affected_status"], ", ".join(f["fixed_versions"][:2]) or "none recorded",
|
|
131
|
+
f["dependency_type"], a.get("label", "")])
|
|
132
|
+
L.append(_md_table(rows, ["ID", "Advisory", "Package", "CVSS sev.", "CVSS", "Status", "Fixed in", "Dependency", "Risk"]))
|
|
133
|
+
for f in result.get("vulnerabilities", [])[:40]:
|
|
134
|
+
e = expl.get(f["finding_id"])
|
|
135
|
+
a = risk.get(f["finding_id"], {})
|
|
136
|
+
L.append(f"### {f['finding_id']} - {f['primary_id']} in {f['package_name']} {f['installed_version']}\n")
|
|
137
|
+
if e:
|
|
138
|
+
L.append(f"**{e['headline']}**\n")
|
|
139
|
+
for k in ("what", "why", "how_entered", "direct_transitive", "impact", "remediation", "unknown"):
|
|
140
|
+
L.append(f"- *{k.replace('_', ' ')}*: {e['sections'][k]}".replace("\n", "\n "))
|
|
141
|
+
L.append("\nRisk factors: " + "; ".join(e["risk_factors"]) + "\n")
|
|
142
|
+
L.append("## Suspicious changes\n")
|
|
143
|
+
L.append("### Typosquatting (similarity is a signal, not proof)\n")
|
|
144
|
+
L.append(_md_table([[t["finding_id"], t["package_name"], t["similar_to"], f"{t['similarity_score']}%", t["evidence_strength"],
|
|
145
|
+
risk.get(t["finding_id"], {}).get("label", ""), "; ".join(t["evidence"][:2])] for t in result.get("typosquatting", [])],
|
|
146
|
+
["ID", "Package", "Similar to", "Similarity", "Evidence", "Risk", "Evidence detail"]))
|
|
147
|
+
L.append("### Modified lockfiles\n")
|
|
148
|
+
la = result.get("lockfile_analysis", {})
|
|
149
|
+
L.append(f"Comparison: {la.get('summary')}\n")
|
|
150
|
+
L.append(_md_table([[c["finding_id"], c["commit"][:10], c["file"], c["package_name"], c["change_type"],
|
|
151
|
+
f"{(c['previous'] or {}).get('version')} -> {(c['new'] or {}).get('version')}", c["classification"],
|
|
152
|
+
risk.get(c["finding_id"], {}).get("label", ""), " ".join(c["reasons"][:1])] for c in result.get("lockfile_changes", [])],
|
|
153
|
+
["ID", "Commit", "File", "Package", "Change", "Version", "Classification", "Risk", "Why"]))
|
|
154
|
+
L.append("## Coverage and limitations\n")
|
|
155
|
+
for lim in result.get("limitations", []):
|
|
156
|
+
L.append(f"- {lim}")
|
|
157
|
+
for k, v in result.get("source_status", {}).items():
|
|
158
|
+
L.append(f"- Source **{k}**: {v.get('state')}" + (f" - errors: {v.get('errors')[:2]}" if v.get("errors") else ""))
|
|
159
|
+
for e in result.get("errors", []):
|
|
160
|
+
L.append(f"- Stage error ({e['stage']}): {e['error']}")
|
|
161
|
+
return "\n".join(L) + "\n"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def generate_html(result: dict, extras: dict | None = None) -> str:
|
|
165
|
+
return markdown_to_html(generate_markdown(result, extras))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def markdown_to_html(md: str) -> str:
|
|
169
|
+
body = []
|
|
170
|
+
in_table = False
|
|
171
|
+
for line in md.splitlines():
|
|
172
|
+
if line.startswith("|"):
|
|
173
|
+
cells = [html.escape(c.strip()) for c in line.strip().strip("|").split("|")]
|
|
174
|
+
if set("".join(cells)) <= set("-: "):
|
|
175
|
+
continue
|
|
176
|
+
tag = "th" if not in_table else "td"
|
|
177
|
+
if not in_table:
|
|
178
|
+
body.append("<table>")
|
|
179
|
+
in_table = True
|
|
180
|
+
body.append("<tr>" + "".join(f"<{tag}>{c}</{tag}>" for c in cells) + "</tr>")
|
|
181
|
+
continue
|
|
182
|
+
if in_table:
|
|
183
|
+
body.append("</table>")
|
|
184
|
+
in_table = False
|
|
185
|
+
if line.startswith("### "):
|
|
186
|
+
body.append(f"<h3>{html.escape(line[4:])}</h3>")
|
|
187
|
+
elif line.startswith("## "):
|
|
188
|
+
body.append(f"<h2>{html.escape(line[3:])}</h2>")
|
|
189
|
+
elif line.startswith("# "):
|
|
190
|
+
body.append(f"<h1>{html.escape(line[2:])}</h1>")
|
|
191
|
+
elif line.startswith("> "):
|
|
192
|
+
body.append(f"<blockquote>{html.escape(line[2:])}</blockquote>")
|
|
193
|
+
elif line.strip():
|
|
194
|
+
body.append(f"<p>{html.escape(line.lstrip('- '))}</p>")
|
|
195
|
+
if in_table:
|
|
196
|
+
body.append("</table>")
|
|
197
|
+
css = ("body{font-family:system-ui,Segoe UI,sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem;color:#1b1f24}"
|
|
198
|
+
"table{border-collapse:collapse;width:100%;margin:.5rem 0 1rem;font-size:.85rem}th,td{border:1px solid #d0d7de;padding:4px 8px;text-align:left}"
|
|
199
|
+
"th{background:#f6f8fa}blockquote{border-left:4px solid #d4a72c;background:#fff8c5;margin:1rem 0;padding:.5rem 1rem}")
|
|
200
|
+
return f"<!doctype html><html><head><meta charset='utf-8'><title>Supply chain report</title><style>{css}</style></head><body>{''.join(body)}</body></html>"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""SARIF 2.1.0 export (GitHub code scanning, VS Code, Azure DevOps ...): vulnerabilities and every non-CVE finding."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from stackparity import __version__
|
|
7
|
+
|
|
8
|
+
LEVEL = {"CRITICAL": "error", "HIGH": "error", "MEDIUM": "warning", "LOW": "note", "INFO": "note", "INFORMATIONAL": "note", None: "warning"}
|
|
9
|
+
SECURITY_SEVERITY = {"CRITICAL": "9.5", "HIGH": "8.0", "MEDIUM": "5.5", "LOW": "3.0", "INFO": "1.0", "INFORMATIONAL": "1.0"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _loc(path: str, line: int = 1) -> dict:
|
|
13
|
+
return {"physicalLocation": {"artifactLocation": {"uri": (path or "unknown").replace("\\", "/")}, "region": {"startLine": max(int(line or 1), 1)}}}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def to_sarif(r: dict, version: str = __version__) -> dict[str, Any]:
|
|
17
|
+
risks = {a["finding_id"]: a for a in r.get("risk_assessments", [])}
|
|
18
|
+
inv = r.get("investigations") or {}
|
|
19
|
+
rules: dict[str, dict] = {}
|
|
20
|
+
results: list[dict] = []
|
|
21
|
+
install_hook_metadata: list[dict] = []
|
|
22
|
+
|
|
23
|
+
def rule(rid: str, name: str, desc: str, help_: str, sev: str | None, uri: str | None = None) -> None:
|
|
24
|
+
if rid not in rules:
|
|
25
|
+
rules[rid] = {"id": rid, "name": name[:120], "shortDescription": {"text": name[:200]}, "fullDescription": {"text": desc[:1000] or name}, "help": {"text": help_[:1500] or name},
|
|
26
|
+
"defaultConfiguration": {"level": LEVEL.get(sev, "warning")}, "properties": {"security-severity": SECURITY_SEVERITY.get(sev or "MEDIUM", "5.5"), "tags": ["security", "supply-chain"]},
|
|
27
|
+
**({"helpUri": uri} if uri else {})}
|
|
28
|
+
|
|
29
|
+
for f in r.get("vulnerabilities", []):
|
|
30
|
+
a = risks.get(f["finding_id"], {})
|
|
31
|
+
rule(f["primary_id"], f"{f['primary_id']} in {f['package_name']}", f.get("summary") or f["primary_id"], f.get("remediation") or "", f["severity"], (f.get("advisory_urls") or [None])[0])
|
|
32
|
+
i = inv.get(f["finding_id"]) or {}
|
|
33
|
+
lock = f.get("lockfile") or "package manifest"
|
|
34
|
+
text = f"{f['package_name']}@{f['installed_version']} is affected by {f['primary_id']}" + (f" (fixed in {', '.join(f['fixed_versions'][:2])})" if f["fixed_versions"] else " (no fixed version recorded)") + "."
|
|
35
|
+
if i:
|
|
36
|
+
text += f" Verdict: {i['verdict'].replace('_', ' ')} ({i['confidence']['label']} confidence). {i['rationale']}"
|
|
37
|
+
results.append({"ruleId": f["primary_id"], "level": LEVEL.get(a.get("label") if a.get("label") in LEVEL else f["severity"], "warning"), "message": {"text": text[:1900]}, "locations": [_loc(lock)],
|
|
38
|
+
"partialFingerprints": {"guardianFinding": f"{f['ecosystem']}:{f['package_name']}@{f['installed_version']}:{f['primary_id']}"},
|
|
39
|
+
"properties": {"priority": a.get("priority"), "risk": a.get("label"), "cvss": f.get("cvss_score"), "epss": f.get("epss"), "kev": f["kev"], "verdict": f.get("verdict"),
|
|
40
|
+
"dependencyType": f["dependency_type"], "sourcePackages": f["source_packages"][:3], "evidence": (i.get("evidence_ids") or [])[:6]}})
|
|
41
|
+
for kind, lst in (("pipeline", (r.get("pipeline") or {}).get("findings", [])), ("package_risk", (r.get("package_risk") or {}).get("findings", []))):
|
|
42
|
+
for f in lst:
|
|
43
|
+
a = risks.get(f["finding_id"], {})
|
|
44
|
+
rule(f["rule_id"], f["title"], f["why"], f["remediation"], f["severity"], (f.get("references") or [None])[0])
|
|
45
|
+
results.append({"ruleId": f["rule_id"], "level": LEVEL.get(f["severity"], "warning"), "message": {"text": f"{f['title']}. {f['why']} Fix: {f['remediation']}"[:1900]}, "locations": [_loc(f["file"], f["line"])],
|
|
46
|
+
"partialFingerprints": {"guardianFinding": f"{f['rule_id']}:{f['file']}:{f.get('subject', '')[:60]}"},
|
|
47
|
+
"properties": {"priority": a.get("priority"), "risk": a.get("label"), "evidence": [f["evidence_id"]] if f.get("evidence_id") else [], "kind": kind}})
|
|
48
|
+
from core.finding_schema import normalize_all_findings
|
|
49
|
+
for f in normalize_all_findings(r):
|
|
50
|
+
if not f["non_cve"] or f["source_engine"] in ("pipeline_analysis", "package_risk"):
|
|
51
|
+
continue # vulnerabilities, pipeline and package-risk results were added above
|
|
52
|
+
ev = (f.get("evidence") or [{}])[0]
|
|
53
|
+
if f["source_engine"] == "suspicious_changes" and f["finding_id"].startswith("LOCK-INSTALL-SCRIPT-"):
|
|
54
|
+
# A lockfile flag records that a hook exists. Actual suspicious script behavior has its own SARIF result.
|
|
55
|
+
install_hook_metadata.append({"findingId": f["finding_id"], "description": f["title"],
|
|
56
|
+
"location": _loc(ev.get("file_path"), ev.get("line"))})
|
|
57
|
+
continue
|
|
58
|
+
rid = f.get("rule_id") or f"{f['source_engine']}/{f['category']}"
|
|
59
|
+
sev = None if f["severity"] == "UNKNOWN" else f["severity"]
|
|
60
|
+
fix = (f.get("remediation") or {}).get("summary") or ""
|
|
61
|
+
rule(rid, f["title"], f.get("description") or f["title"], fix, sev)
|
|
62
|
+
results.append({"ruleId": rid, "level": LEVEL.get(sev, "warning"), "message": {"text": f"{f['title']}. {f.get('description') or ''}"[:1900]},
|
|
63
|
+
"locations": [_loc(ev.get("file_path"), ev.get("line"))],
|
|
64
|
+
"partialFingerprints": {"stackparityFinding": f"{f['source_engine']}:{f['finding_id']}:{ev.get('file_path') or ''}"},
|
|
65
|
+
"properties": {"kind": f["category"], "classification": f["classification"], "confidence": f["confidence"]}})
|
|
66
|
+
repo = r.get("repo", {})
|
|
67
|
+
return {"$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
|
|
68
|
+
"runs": [{"tool": {"driver": {"name": "StackParity", "version": version, "informationUri": repo.get("url") or "", "rules": list(rules.values())}},
|
|
69
|
+
"results": results,
|
|
70
|
+
"properties": {"repository": repo.get("url"), "commit": repo.get("commit_sha"), "generatedBy": "evidence-gated agents; verdicts cite evidence ids",
|
|
71
|
+
"coverage": r.get("coverage"), "lockfileInstallMetadata": install_hook_metadata}}]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""CycloneDX 1.6 VEX (Vulnerability Exploitability eXchange) from the Investigator's evidence-backed verdicts and analyst decisions.
|
|
2
|
+
|
|
3
|
+
Mapping is deliberately conservative: StackParity never states ``not_affected`` from absence of an import alone (that is only "no static
|
|
4
|
+
evidence"); such findings stay ``in_triage`` with the detail spelled out. Only an explicit analyst decision can set ``false_positive``.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import Any, Optional
|
|
11
|
+
|
|
12
|
+
from stackparity import __version__
|
|
13
|
+
|
|
14
|
+
STATE = {"exploitable_likely": "exploitable", "reachable": "exploitable", "possibly_reachable": "in_triage", "test_only": "in_triage", "no_import_evidence": "in_triage", "needs_review": "in_triage"}
|
|
15
|
+
DETAIL = {"exploitable_likely": "The application imports the package and exploitation signals (KEV/EPSS/CVSS) are strong.", "reachable": "The application's own code imports the vulnerable package.",
|
|
16
|
+
"possibly_reachable": "A direct dependency that brings the package in is imported by the application; use of the vulnerable code is unknown.",
|
|
17
|
+
"test_only": "Imported only by test code in the analysed source; production use not evidenced.", "no_import_evidence": "No import found in the analysed source; may still be used through configuration, plugins or a CLI.",
|
|
18
|
+
"needs_review": "Insufficient evidence to judge automatically."}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def to_vex(r: dict, decisions: Optional[dict[str, dict]] = None) -> dict[str, Any]:
|
|
22
|
+
decisions = decisions or {}
|
|
23
|
+
fps = (r.get("memory") or {}).get("fingerprints") or {}
|
|
24
|
+
risks = {a["finding_id"]: a for a in r.get("risk_assessments", [])}
|
|
25
|
+
inv = r.get("investigations") or {}
|
|
26
|
+
comp_by_ref = {c["bom_ref"]: c for c in r.get("components", [])}
|
|
27
|
+
vulns = []
|
|
28
|
+
for f in r.get("vulnerabilities", []):
|
|
29
|
+
i = inv.get(f["finding_id"]) or {}
|
|
30
|
+
v = i.get("verdict") or "needs_review"
|
|
31
|
+
state, detail = STATE.get(v, "in_triage"), DETAIL.get(v, "")
|
|
32
|
+
d = decisions.get(fps.get(f["finding_id"]) or "")
|
|
33
|
+
response = []
|
|
34
|
+
analysis = {"state": state, "detail": (detail + " " + (i.get("rationale") or ""))[:1000].strip()}
|
|
35
|
+
if d:
|
|
36
|
+
if d["decision"] == "false_positive":
|
|
37
|
+
analysis.update(state="false_positive", detail=f"Analyst decision: {d['reason']}")
|
|
38
|
+
elif d["decision"] in ("accepted_risk", "suppress"):
|
|
39
|
+
response = ["will_not_fix"]
|
|
40
|
+
analysis["detail"] += f" Analyst decision ({d['decision']}): {d['reason']}"
|
|
41
|
+
if f["fixed_versions"] and not response:
|
|
42
|
+
response = ["update"]
|
|
43
|
+
if response:
|
|
44
|
+
analysis["response"] = response
|
|
45
|
+
ref = next((c["purl"] for c in (comp_by_ref.get(x) for x in (f.get("component_refs") or [f["component_ref"]])) if c and c.get("purl")), f["component_ref"])
|
|
46
|
+
a = risks.get(f["finding_id"], {})
|
|
47
|
+
vulns.append({"bom-ref": f"vuln-{f['finding_id']}", "id": f["primary_id"], "source": {"name": "OSV", "url": (f.get("advisory_urls") or ["https://osv.dev"])[0]},
|
|
48
|
+
"ratings": ([{"source": {"name": f.get("severity_source") or "OSV"}, "score": f["cvss_score"], "severity": (f["severity"] or "unknown").lower(), "vector": f.get("cvss_vector")}] if f["severity"] else []),
|
|
49
|
+
"description": f.get("summary") or "", "recommendation": f.get("remediation") or "", "analysis": analysis, "affects": [{"ref": ref}],
|
|
50
|
+
"properties": [{"name": "sc-guardian:priority", "value": str(a.get("priority"))}, {"name": "sc-guardian:confidence", "value": str((i.get("confidence") or {}).get("label"))},
|
|
51
|
+
{"name": "sc-guardian:epss", "value": str(f.get("epss"))}, {"name": "sc-guardian:kev", "value": str(f["kev"]).lower()},
|
|
52
|
+
{"name": "sc-guardian:evidence", "value": ",".join((i.get("evidence_ids") or [])[:8])}]})
|
|
53
|
+
repo = r.get("repo", {})
|
|
54
|
+
return {"bomFormat": "CycloneDX", "specVersion": "1.6", "serialNumber": f"urn:uuid:{uuid.uuid4()}", "version": 1,
|
|
55
|
+
"metadata": {"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "tools": {"components": [{"type": "application", "name": "stackparity", "version": __version__}]},
|
|
56
|
+
"component": {"type": "application", "name": repo.get("name", "repository"), "version": (repo.get("commit_sha") or "")[:12]}},
|
|
57
|
+
"vulnerabilities": vulns}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Authoritative read model over a scan result: assessment coverage and every derived number a client displays.
|
|
2
|
+
|
|
3
|
+
The CLI summary, the policy gate, the reports and the dashboard all read these functions, so none of them computes its
|
|
4
|
+
own security figures. Works on persisted results (including scans stored by earlier versions) and never invents values:
|
|
5
|
+
a stage that did not run is reported as ``not_assessed``, not as zero findings.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Optional
|
|
10
|
+
|
|
11
|
+
SEVERITIES = ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN")
|
|
12
|
+
_SEV_RANK = {s: len(SEVERITIES) - i for i, s in enumerate(SEVERITIES)}
|
|
13
|
+
_SEV_RANK["UNKNOWN"] = 0
|
|
14
|
+
NON_CVE_LABELS = {"supply_chain": "Supply chain", "suspicious_change": "Suspicious change", "sast": "SAST", "iac": "IaC",
|
|
15
|
+
"pipeline": "Pipeline & container", "typosquatting": "Typosquatting", "lockfile_history": "Lockfile history"}
|
|
16
|
+
_OSV_REASONS = {
|
|
17
|
+
"offline": "Offline scan: no advisory database was queried.",
|
|
18
|
+
"unavailable": "OSV could not be reached.",
|
|
19
|
+
"failed": "Vulnerability correlation failed.",
|
|
20
|
+
"not_queried": "No component had a known ecosystem and version to query.",
|
|
21
|
+
"partial": "OSV answered for only some packages.",
|
|
22
|
+
"stale_cache": "Some advisories came from an expired local cache.",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def coverage(result: dict) -> dict[str, Any]:
|
|
27
|
+
"""What this scan actually assessed. ``complete`` is True only when nothing material was skipped."""
|
|
28
|
+
gaps: list[str] = []
|
|
29
|
+
state = ((result.get("source_status") or {}).get("OSV") or {}).get("state") or "unrecorded"
|
|
30
|
+
unscanned = (result.get("vuln_coverage") or {}).get("unscanned_components") or 0
|
|
31
|
+
if state == "ok":
|
|
32
|
+
vuln = "partial" if unscanned else "assessed"
|
|
33
|
+
reason = f"{unscanned} component(s) could not be queried." if unscanned else ""
|
|
34
|
+
elif state in ("partial", "stale_cache"):
|
|
35
|
+
vuln, reason = "partial", _OSV_REASONS[state]
|
|
36
|
+
else:
|
|
37
|
+
vuln, reason = "not_assessed", _OSV_REASONS.get(state, "No advisory source status was recorded.")
|
|
38
|
+
if vuln != "assessed":
|
|
39
|
+
gaps.append(f"Known vulnerabilities {vuln.replace('_', ' ')}: {reason}")
|
|
40
|
+
|
|
41
|
+
source = result.get("inventory_source")
|
|
42
|
+
unresolved = sum(1 for c in result.get("components") or [] if c.get("type") not in ("file", "container") and not c.get("version") and not c.get("is_self"))
|
|
43
|
+
technologies = (result.get("inspection") or {}).get("technologies") or []
|
|
44
|
+
uncovered = [t["name"] for t in technologies if t.get("support") in ("detected-but-unsupported", "unknown")]
|
|
45
|
+
if source in (None, "", "none"):
|
|
46
|
+
inventory = "not_assessed"
|
|
47
|
+
gaps.append("Dependency inventory not assessed: no SBOM was generated.")
|
|
48
|
+
elif unresolved or uncovered:
|
|
49
|
+
inventory = "partial"
|
|
50
|
+
if unresolved:
|
|
51
|
+
gaps.append(f"{unresolved} dependency declaration(s) have no resolved version.")
|
|
52
|
+
if uncovered and source == "builtin":
|
|
53
|
+
gaps.append("Not inventoried by the built-in engine: " + ", ".join(uncovered) + ".")
|
|
54
|
+
else:
|
|
55
|
+
inventory = "assessed"
|
|
56
|
+
for e in result.get("errors") or []:
|
|
57
|
+
gaps.append(f"Stage '{e.get('stage')}' failed: {str(e.get('error'))[:200]}")
|
|
58
|
+
for name, meta in (result.get("scanner_status") or {}).items():
|
|
59
|
+
if meta.get("status") == "error":
|
|
60
|
+
gaps.append(f"Scanner '{name}' failed: {meta.get('error')}")
|
|
61
|
+
if (result.get("inspection") or {}).get("truncated"):
|
|
62
|
+
gaps.append("Repository file walk was truncated.")
|
|
63
|
+
return {"vulnerability": {"state": vuln, "source_state": state, "reason": reason, "unscanned_components": unscanned},
|
|
64
|
+
"inventory": {"state": inventory, "source": source or "unrecorded", "unresolved": unresolved},
|
|
65
|
+
"complete": not gaps, "gaps": gaps}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _sev(value: Any) -> str:
|
|
69
|
+
s = str(value or "UNKNOWN").upper()
|
|
70
|
+
s = {"MODERATE": "MEDIUM", "INFORMATIONAL": "INFO"}.get(s, s)
|
|
71
|
+
return s if s in SEVERITIES else "UNKNOWN"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _standardized(result: dict) -> list[dict]:
|
|
75
|
+
from core.finding_schema import normalize_all_findings
|
|
76
|
+
return normalize_all_findings(result)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def non_cve_findings(result: dict) -> list[dict]:
|
|
80
|
+
"""Every non-CVE finding from every engine, in one flat shape, highest severity first."""
|
|
81
|
+
risks = {a["finding_id"]: a for a in result.get("risk_assessments") or []}
|
|
82
|
+
out = []
|
|
83
|
+
for f in _standardized(result):
|
|
84
|
+
if not f.get("non_cve"):
|
|
85
|
+
continue
|
|
86
|
+
ev = (f.get("evidence") or [{}])[0]
|
|
87
|
+
target = f.get("affected_target") or {}
|
|
88
|
+
category = {"pipeline_analysis": "pipeline", "suspicious_changes": "suspicious_change", "package_risk": "supply_chain",
|
|
89
|
+
"sast_taint": "sast", "supply_chain_anomaly": "supply_chain", "iac_scanner": "iac"}.get(f["source_engine"], f["category"])
|
|
90
|
+
a = risks.get(f["finding_id"]) or {}
|
|
91
|
+
out.append({"uid": f"{f['source_engine']}:{f['finding_id']}", "finding_id": f["finding_id"], "category": category,
|
|
92
|
+
"category_label": NON_CVE_LABELS.get(category, category.replace("_", " ").title()), "engine": f["source_engine"],
|
|
93
|
+
"rule_id": f.get("rule_id") or "", "title": f.get("title") or "Finding", "description": f.get("description") or "",
|
|
94
|
+
"classification": f.get("classification"), "confidence": f.get("confidence"), "severity": _sev(f.get("severity")),
|
|
95
|
+
"file": ev.get("file_path") or target.get("file_path"), "line": ev.get("line") or target.get("line"),
|
|
96
|
+
"package": target.get("package_name"), "snippet": ev.get("snippet"),
|
|
97
|
+
"recommendation": (f.get("remediation") or {}).get("summary"), "risk": a.get("label"), "priority": a.get("priority")})
|
|
98
|
+
out.sort(key=lambda x: (-_SEV_RANK[x["severity"]], x["category"], x["uid"]))
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def dashboard_view(result: dict, approvals: Optional[dict] = None) -> dict[str, Any]:
|
|
103
|
+
vulns = result.get("vulnerabilities") or []
|
|
104
|
+
components = result.get("components") or []
|
|
105
|
+
approvals = approvals if approvals is not None else (result.get("approvals") or {})
|
|
106
|
+
by_sev = {s: 0 for s in SEVERITIES}
|
|
107
|
+
for v in vulns:
|
|
108
|
+
by_sev[_sev(v.get("severity"))] += 1
|
|
109
|
+
total = len(vulns)
|
|
110
|
+
|
|
111
|
+
from reporting.counts import package_components
|
|
112
|
+
packages = package_components(components)
|
|
113
|
+
ecosystems: dict[str, int] = {}
|
|
114
|
+
for c in packages:
|
|
115
|
+
name = c.get("ecosystem") or c.get("purl_type") or "unknown"
|
|
116
|
+
ecosystems[name] = ecosystems.get(name, 0) + 1
|
|
117
|
+
|
|
118
|
+
risks = {a["finding_id"]: a for a in result.get("risk_assessments") or []}
|
|
119
|
+
ranked = sorted(vulns, key=lambda v: (-((risks.get(v.get("finding_id")) or {}).get("score") or 0), -_SEV_RANK[_sev(v.get("severity"))], str(v.get("primary_id"))))
|
|
120
|
+
top = [{"finding_id": v.get("finding_id"), "primary_id": v.get("primary_id"), "package_name": v.get("package_name"),
|
|
121
|
+
"installed_version": v.get("installed_version"), "ecosystem": v.get("ecosystem"), "severity": _sev(v.get("severity")),
|
|
122
|
+
"cvss_score": v.get("cvss_score"), "fixed_version": (v.get("fixed_versions") or [None])[0],
|
|
123
|
+
"risk": (risks.get(v.get("finding_id")) or {}).get("label"), "priority": (risks.get(v.get("finding_id")) or {}).get("priority"),
|
|
124
|
+
"score": (risks.get(v.get("finding_id")) or {}).get("score")} for v in ranked[:8]]
|
|
125
|
+
|
|
126
|
+
other = non_cve_findings(result)
|
|
127
|
+
by_category: dict[str, int] = {}
|
|
128
|
+
for f in other:
|
|
129
|
+
by_category[f["category"]] = by_category.get(f["category"], 0) + 1
|
|
130
|
+
|
|
131
|
+
graph = result.get("graph") or {}
|
|
132
|
+
nodes = graph.get("nodes") or []
|
|
133
|
+
relationships = graph.get("relationships") or {}
|
|
134
|
+
tiers: dict[str, str] = {}
|
|
135
|
+
for n in nodes:
|
|
136
|
+
kinds = (relationships.get(n["id"]) or {}).values()
|
|
137
|
+
tiers[n["id"]] = "root" if n.get("kind") == "root" else "direct" if any(str(k).startswith("direct") for k in kinds) else "other"
|
|
138
|
+
vulnerable: dict[str, int] = {}
|
|
139
|
+
for v in vulns:
|
|
140
|
+
for ref in {*(v.get("component_refs") or []), v.get("component_ref")}:
|
|
141
|
+
if ref:
|
|
142
|
+
vulnerable[ref] = vulnerable.get(ref, 0) + 1
|
|
143
|
+
|
|
144
|
+
items = (result.get("remediation") or {}).get("items") or []
|
|
145
|
+
pipeline = result.get("pipeline") or {}
|
|
146
|
+
return {
|
|
147
|
+
"coverage": coverage(result),
|
|
148
|
+
"counts": {"components": len(packages), "vulnerabilities": total, "non_cve": len(other), "remediations": len(items),
|
|
149
|
+
"graph_nodes": len(nodes), "graph_edges": len(graph.get("edges") or []), "pipeline": len(pipeline.get("findings") or [])},
|
|
150
|
+
"severity": [{"severity": s, "count": by_sev[s], "percent": round(100 * by_sev[s] / total) if total else 0} for s in SEVERITIES],
|
|
151
|
+
"exposure": {"direct": sum(str(v.get("dependency_type", "")).startswith("direct") for v in vulns),
|
|
152
|
+
"transitive": sum(v.get("dependency_type") == "transitive" for v in vulns),
|
|
153
|
+
"fixable": sum(bool(v.get("fixed_versions")) for v in vulns), "kev": sum(bool(v.get("kev")) for v in vulns)},
|
|
154
|
+
"ecosystems": [{"name": k, "count": c, "percent": round(100 * c / len(packages))} for k, c in sorted(ecosystems.items(), key=lambda kv: (-kv[1], kv[0]))],
|
|
155
|
+
"top_findings": top,
|
|
156
|
+
"non_cve": {"findings": other, "by_category": [{"category": k, "label": NON_CVE_LABELS.get(k, k.replace("_", " ").title()), "count": c}
|
|
157
|
+
for k, c in sorted(by_category.items(), key=lambda kv: (-kv[1], kv[0]))]},
|
|
158
|
+
"graph": {"tiers": tiers, "vulnerable": vulnerable, "direct": sum(t == "direct" for t in tiers.values()),
|
|
159
|
+
"other": sum(t == "other" for t in tiers.values())},
|
|
160
|
+
"pipeline": {"files_analysed": (pipeline.get("summary") or {}).get("files_analysed", len(pipeline.get("files") or [])),
|
|
161
|
+
"critical_high": sum(_sev(f.get("severity")) in ("CRITICAL", "HIGH") for f in pipeline.get("findings") or []),
|
|
162
|
+
"container_assets": len(pipeline.get("container_assets") or [])},
|
|
163
|
+
"remediation": {"total": len(items), "high_priority": sum(i.get("priority") in ("P0", "P1") for i in items),
|
|
164
|
+
"approved": sum((approvals.get(i.get("fingerprint")) or {}).get("state") == "approved" for i in items),
|
|
165
|
+
"with_patch": sum(bool((i.get("patch") or {}).get("diff")) for i in items)},
|
|
166
|
+
}
|
|
File without changes
|