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,185 @@
|
|
|
1
|
+
"""Dependency tree and statistics for display (no Streamlit imports; the UI renders the returned structures).
|
|
2
|
+
|
|
3
|
+
Two readable shapes of the same graph:
|
|
4
|
+
|
|
5
|
+
* top-down "what does this service / package bring in" (like ``npm ls``): each package is expanded once, later occurrences are shown as
|
|
6
|
+
references ("shown above") so shared dependencies do not explode the tree
|
|
7
|
+
* bottom-up "who pulls this package in" : the reverse tree from a package up to every service root
|
|
8
|
+
|
|
9
|
+
Depth is the length of the *shortest* path from a root (direct dependency = 1), matching the direct/transitive classification used everywhere else.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import html
|
|
14
|
+
from collections import Counter, deque
|
|
15
|
+
from typing import Any, Optional
|
|
16
|
+
|
|
17
|
+
import networkx as nx
|
|
18
|
+
|
|
19
|
+
from graph.graph_builder import roots_of
|
|
20
|
+
|
|
21
|
+
SEV_COLOR = {"CRITICAL": "#b42318", "HIGH": "#e5601c", "MEDIUM": "#d4a72c", "LOW": "#4c8bf5", "UNKNOWN": "#8250df", "": "#7a8794"}
|
|
22
|
+
SEV_RANK = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, "UNKNOWN": 0, "": -1}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def depths_from(g: nx.DiGraph, root: str) -> dict[str, int]:
|
|
26
|
+
return dict(nx.single_source_shortest_path_length(g, root))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def vulnerable_ancestors(g: nx.DiGraph, vuln: dict[str, str]) -> set[str]:
|
|
30
|
+
keep: set[str] = set()
|
|
31
|
+
for n in vuln:
|
|
32
|
+
if n in g:
|
|
33
|
+
keep.add(n)
|
|
34
|
+
keep |= nx.ancestors(g, n)
|
|
35
|
+
return keep
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_tree(g: nx.DiGraph, root: str, vuln: dict[str, str], info: dict[str, dict], max_depth: int = 12, max_nodes: Optional[int] = None, only: Optional[set[str]] = None,
|
|
39
|
+
hide_dev: bool = False) -> dict[str, Any]:
|
|
40
|
+
"""Top-down tree from ``root``. Returns {node: {...}, truncated: bool, shown: int}."""
|
|
41
|
+
depth = depths_from(g, root)
|
|
42
|
+
seen: set[str] = {root}
|
|
43
|
+
counter = {"n": 0, "trunc": False}
|
|
44
|
+
|
|
45
|
+
def child_sort(n: str):
|
|
46
|
+
return (-SEV_RANK.get(vuln.get(n, ""), -1), g.nodes[n].get("label", n).lower())
|
|
47
|
+
|
|
48
|
+
def make(n: str, d: int, via: Optional[str]) -> dict:
|
|
49
|
+
counter["n"] += 1
|
|
50
|
+
a = g.nodes[n]
|
|
51
|
+
meta = info.get(n, {})
|
|
52
|
+
node = {"id": n, "label": a.get("label", n), "depth": d, "vuln": vuln.get(n, ""), "kind": a.get("kind"), "scope": meta.get("scope"), "license": meta.get("license"),
|
|
53
|
+
"install_script": bool(meta.get("install_script")), "resolution": meta.get("resolution"), "deprecated": bool(meta.get("deprecated")),
|
|
54
|
+
"integrity": meta.get("integrity"), "ref": False, "children": [], "descendants": 0, "vuln_below": 0}
|
|
55
|
+
kids = [k for k in g.successors(n) if (only is None or k in only) and not (hide_dev and info.get(k, {}).get("scope") == "dev")]
|
|
56
|
+
for k in sorted(kids, key=child_sort):
|
|
57
|
+
if max_nodes is not None and counter["n"] >= max_nodes:
|
|
58
|
+
counter["trunc"] = True
|
|
59
|
+
break
|
|
60
|
+
if k in seen:
|
|
61
|
+
a2 = g.nodes[k]
|
|
62
|
+
counter["n"] += 1
|
|
63
|
+
node["children"].append({"id": k, "label": a2.get("label", k), "depth": d + 1, "vuln": vuln.get(k, ""), "ref": True, "children": [], "descendants": 0, "vuln_below": 0,
|
|
64
|
+
"scope": info.get(k, {}).get("scope"), "license": None, "install_script": False, "resolution": None, "deprecated": False, "integrity": None, "kind": a2.get("kind")})
|
|
65
|
+
continue
|
|
66
|
+
if d + 1 > max_depth:
|
|
67
|
+
node["more"] = node.get("more", 0) + 1
|
|
68
|
+
continue
|
|
69
|
+
seen.add(k)
|
|
70
|
+
node["children"].append(make(k, d + 1, n))
|
|
71
|
+
node["descendants"] = sum(1 + c["descendants"] for c in node["children"] if not c["ref"])
|
|
72
|
+
node["vuln_below"] = sum((1 if c["vuln"] else 0) + c["vuln_below"] for c in node["children"] if not c["ref"])
|
|
73
|
+
return node
|
|
74
|
+
|
|
75
|
+
tree = make(root, 0, None)
|
|
76
|
+
return {"tree": tree, "truncated": counter["trunc"], "shown": counter["n"], "max_depth_reached": max(depth.values()) if depth else 0}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def build_reverse_tree(g: nx.DiGraph, target: str, vuln: dict[str, str], info: dict[str, dict], max_nodes: Optional[int] = None) -> dict[str, Any]:
|
|
80
|
+
"""Bottom-up: ``target`` and, below it, each parent chain up to the service roots (each package expanded once)."""
|
|
81
|
+
seen: set[str] = {target}
|
|
82
|
+
counter = {"n": 0}
|
|
83
|
+
|
|
84
|
+
def make(n: str, d: int) -> dict:
|
|
85
|
+
counter["n"] += 1
|
|
86
|
+
a = g.nodes[n]
|
|
87
|
+
node = {"id": n, "label": a.get("label", n), "depth": d, "vuln": vuln.get(n, ""), "kind": a.get("kind"), "scope": info.get(n, {}).get("scope"), "license": info.get(n, {}).get("license"),
|
|
88
|
+
"install_script": False, "resolution": info.get(n, {}).get("resolution"), "deprecated": False, "integrity": None, "ref": False, "children": [], "descendants": 0, "vuln_below": 0}
|
|
89
|
+
for p in sorted(g.predecessors(n), key=lambda x: (g.nodes[x].get("kind") != "root", g.nodes[x].get("label", x).lower())):
|
|
90
|
+
if max_nodes is not None and counter["n"] >= max_nodes:
|
|
91
|
+
break
|
|
92
|
+
if p in seen:
|
|
93
|
+
counter["n"] += 1
|
|
94
|
+
node["children"].append({"id": p, "label": g.nodes[p].get("label", p), "depth": d + 1, "vuln": vuln.get(p, ""), "ref": True, "children": [], "descendants": 0,
|
|
95
|
+
"vuln_below": 0, "scope": None, "license": None, "install_script": False, "resolution": None, "deprecated": False, "integrity": None, "kind": g.nodes[p].get("kind")})
|
|
96
|
+
continue
|
|
97
|
+
seen.add(p)
|
|
98
|
+
node["children"].append(make(p, d + 1))
|
|
99
|
+
node["descendants"] = sum(1 + c["descendants"] for c in node["children"] if not c["ref"])
|
|
100
|
+
return node
|
|
101
|
+
|
|
102
|
+
return {"tree": make(target, 0), "truncated": bool(max_nodes is not None and counter["n"] >= max_nodes), "shown": counter["n"]}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def tree_html(tree: dict, open_levels: int = 1, reverse: bool = False) -> str:
|
|
106
|
+
"""Nested <details> markup (collapsible, no scripts). All text is escaped."""
|
|
107
|
+
css = ("<style>.dt{font:13px/1.55 system-ui,Segoe UI,sans-serif}.dt details{margin-left:16px;border-left:1px solid rgba(128,128,128,.35);padding-left:8px}"
|
|
108
|
+
".dt summary{cursor:pointer;list-style:none;padding:1px 0}.dt summary::-webkit-details-marker{display:none}.dt summary:before{content:'\\25B8';display:inline-block;width:14px;opacity:.7}"
|
|
109
|
+
".dt details[open]>summary:before{content:'\\25BE'}.dt .leaf{margin-left:30px;padding:1px 0}.dt .b{font-size:11px;border-radius:9px;padding:0 6px;margin-left:5px;border:1px solid rgba(128,128,128,.5)}"
|
|
110
|
+
".dt .dot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:6px}.dt .ref{opacity:.55;font-style:italic}.dt .num{opacity:.65;font-size:11px;margin-left:6px}</style>")
|
|
111
|
+
|
|
112
|
+
def badges(n: dict) -> str:
|
|
113
|
+
out = []
|
|
114
|
+
if n.get("vuln"):
|
|
115
|
+
out.append(f'<span class="b" style="color:{SEV_COLOR.get(n["vuln"], "#8250df")};border-color:{SEV_COLOR.get(n["vuln"], "#8250df")}">{html.escape(n["vuln"].title())}</span>')
|
|
116
|
+
if n.get("scope") == "dev":
|
|
117
|
+
out.append('<span class="b">dev</span>')
|
|
118
|
+
elif n.get("scope") == "optional":
|
|
119
|
+
out.append('<span class="b">optional</span>')
|
|
120
|
+
if n.get("install_script"):
|
|
121
|
+
out.append('<span class="b" style="color:#d4a72c;border-color:#d4a72c">install script</span>')
|
|
122
|
+
if n.get("deprecated"):
|
|
123
|
+
out.append('<span class="b" style="color:#e5601c;border-color:#e5601c">deprecated</span>')
|
|
124
|
+
if n.get("integrity") == "mismatch":
|
|
125
|
+
out.append('<span class="b" style="color:#b42318;border-color:#b42318">digest mismatch</span>')
|
|
126
|
+
if n.get("resolution") == "registry-resolved":
|
|
127
|
+
out.append('<span class="b" title="resolved by the registry, not pinned by a lockfile">registry-resolved</span>')
|
|
128
|
+
if n.get("license"):
|
|
129
|
+
out.append(f'<span class="b">{html.escape(str(n["license"])[:28])}</span>')
|
|
130
|
+
return "".join(out)
|
|
131
|
+
|
|
132
|
+
def label(n: dict) -> str:
|
|
133
|
+
col = SEV_COLOR.get(n.get("vuln") or "", "#7a8794")
|
|
134
|
+
shape = "border-radius:2px" if n.get("kind") == "root" else ""
|
|
135
|
+
extra = ""
|
|
136
|
+
if n.get("descendants"):
|
|
137
|
+
extra += f'<span class="num">{n["descendants"]} below</span>'
|
|
138
|
+
if n.get("vuln_below"):
|
|
139
|
+
extra += f'<span class="num" style="color:#e5601c">{n["vuln_below"]} vulnerable below</span>'
|
|
140
|
+
if n.get("more"):
|
|
141
|
+
extra += f'<span class="num">+{n["more"]} deeper (depth limit)</span>'
|
|
142
|
+
return f'<span class="dot" style="background:{col};{shape}"></span>{html.escape(n["label"])}{badges(n)}{extra}'
|
|
143
|
+
|
|
144
|
+
def rec(n: dict, level: int) -> str:
|
|
145
|
+
if n.get("ref"):
|
|
146
|
+
return f'<div class="leaf ref"><span class="dot" style="background:{SEV_COLOR.get(n.get("vuln") or "", "#7a8794")}"></span>{html.escape(n["label"])} ↪ shown above</div>'
|
|
147
|
+
if not n["children"]:
|
|
148
|
+
return f'<div class="leaf">{label(n)}</div>'
|
|
149
|
+
op = " open" if level < open_levels else ""
|
|
150
|
+
return f'<details{op}><summary>{label(n)}</summary>' + "".join(rec(c, level + 1) for c in n["children"]) + "</details>"
|
|
151
|
+
|
|
152
|
+
return css + '<div class="dt">' + rec(tree, 0) + "</div>"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def graph_stats(g: nx.DiGraph, vuln: dict[str, str]) -> dict[str, Any]:
|
|
156
|
+
"""Shape of the transitive closure: depth histogram, longest chain, most shared packages, vulnerable depth."""
|
|
157
|
+
comps = [n for n, a in g.nodes(data=True) if a.get("kind") == "component"]
|
|
158
|
+
per_root = {}
|
|
159
|
+
hist: Counter = Counter()
|
|
160
|
+
best_depth: dict[str, int] = {}
|
|
161
|
+
for r in roots_of(g):
|
|
162
|
+
d = depths_from(g, r)
|
|
163
|
+
per_root[g.nodes[r].get("label", r)] = {"packages": len(d) - 1, "max_depth": max(d.values()) if d else 0}
|
|
164
|
+
for n, v in d.items():
|
|
165
|
+
if n != r and g.nodes[n].get("kind") == "component":
|
|
166
|
+
best_depth[n] = min(best_depth.get(n, 10**9), v)
|
|
167
|
+
for n, v in best_depth.items():
|
|
168
|
+
hist[v] += 1
|
|
169
|
+
longest: list[str] = []
|
|
170
|
+
try:
|
|
171
|
+
dag = nx.DiGraph(g)
|
|
172
|
+
if nx.is_directed_acyclic_graph(dag):
|
|
173
|
+
longest = nx.dag_longest_path(dag)
|
|
174
|
+
else: # cycles: fall back to the longest shortest-path chain
|
|
175
|
+
far = max(best_depth, key=best_depth.get) if best_depth else None
|
|
176
|
+
if far:
|
|
177
|
+
longest = min((nx.shortest_path(g, r, far) for r in roots_of(g) if nx.has_path(g, r, far)), key=len)
|
|
178
|
+
except Exception:
|
|
179
|
+
pass
|
|
180
|
+
fan_in = sorted(((g.nodes[n].get("label", n), g.in_degree(n)) for n in comps), key=lambda x: -x[1])[:10]
|
|
181
|
+
fan_out = sorted(((g.nodes[n].get("label", n), g.out_degree(n)) for n in comps), key=lambda x: -x[1])[:10]
|
|
182
|
+
vuln_depth: Counter = Counter(best_depth[n] for n in vuln if n in best_depth)
|
|
183
|
+
return {"components": len(comps), "edges": g.number_of_edges(), "depth_histogram": {int(k): v for k, v in sorted(hist.items())}, "max_depth": max(hist) if hist else 0,
|
|
184
|
+
"longest_chain": [g.nodes[n].get("label", n) for n in longest], "most_shared": [x for x in fan_in if x[1] > 1], "biggest_fan_out": [x for x in fan_out if x[1] > 0],
|
|
185
|
+
"vulnerable_by_depth": {int(k): v for k, v in sorted(vuln_depth.items())}, "per_root": per_root, "has_cycles": not nx.is_directed_acyclic_graph(nx.DiGraph(g))}
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""EPSS (Exploit Prediction Scoring System, FIRST.org): probability that a CVE will be exploited in the next 30 days. Public API, no key.
|
|
2
|
+
|
|
3
|
+
EPSS is a *probability estimate*, not a fact: it is shown as such and only nudges the risk score. Unavailability is reported, never defaulted to 0.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
from core.http import HttpClient, NotFound, SourceUnavailable
|
|
10
|
+
from storage.cache import Cache
|
|
11
|
+
|
|
12
|
+
URL = "https://api.first.org/data/v1/epss"
|
|
13
|
+
TTL = 24 * 3600
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EpssClient:
|
|
17
|
+
def __init__(self, http: HttpClient, cache: Optional[Cache] = None):
|
|
18
|
+
self.http, self.cache = http, cache
|
|
19
|
+
self.status: dict[str, Any] = {"source": "EPSS (FIRST.org)", "state": "not_queried", "requested": 0, "from_cache": 0, "unavailable": 0, "scored": 0}
|
|
20
|
+
|
|
21
|
+
def get_many(self, cves: list[str]) -> dict[str, dict]:
|
|
22
|
+
out: dict[str, dict] = {}
|
|
23
|
+
todo: list[str] = []
|
|
24
|
+
for c in sorted({x for x in cves if x and x.startswith("CVE-")}):
|
|
25
|
+
hit = self.cache.get("epss", c, ttl=TTL) if self.cache else None
|
|
26
|
+
if hit is not None:
|
|
27
|
+
self.status["from_cache"] += 1
|
|
28
|
+
if hit:
|
|
29
|
+
out[c] = hit
|
|
30
|
+
else:
|
|
31
|
+
todo.append(c)
|
|
32
|
+
for i in range(0, len(todo), 80):
|
|
33
|
+
batch = todo[i:i + 80]
|
|
34
|
+
self.status["requested"] += len(batch)
|
|
35
|
+
try:
|
|
36
|
+
data = self.http.get_json(f"{URL}?cve={','.join(batch)}&limit=100")
|
|
37
|
+
except (NotFound, SourceUnavailable):
|
|
38
|
+
self.status["unavailable"] += len(batch)
|
|
39
|
+
continue
|
|
40
|
+
got = {}
|
|
41
|
+
for r in data.get("data", []) or []:
|
|
42
|
+
try:
|
|
43
|
+
got[r["cve"]] = {"epss": float(r["epss"]), "percentile": float(r["percentile"]), "date": r.get("date")}
|
|
44
|
+
except (KeyError, ValueError, TypeError):
|
|
45
|
+
continue
|
|
46
|
+
for c in batch:
|
|
47
|
+
if self.cache:
|
|
48
|
+
self.cache.set("epss", c, got.get(c, {}))
|
|
49
|
+
if c in got:
|
|
50
|
+
out[c] = got[c]
|
|
51
|
+
self.status["scored"] = len(out)
|
|
52
|
+
self.status["state"] = "ok" if self.status["unavailable"] == 0 else ("partial" if out or self.status["from_cache"] else "unavailable")
|
|
53
|
+
return out
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""llm package."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Provider-agnostic LLM client over plain HTTPS (no SDKs). Entirely optional: with no key everything runs deterministically.
|
|
2
|
+
|
|
3
|
+
Configure in ``.env``: ``LLM_API_KEY=...`` (Groq ``gsk_``, Gemini ``AIza``, Anthropic ``sk-ant-``, OpenAI ``sk-``).
|
|
4
|
+
The provider is detected from the key prefix; override with ``LLM_PROVIDER`` (groq | gemini | anthropic | openai | openai_compatible),
|
|
5
|
+
``LLM_MODEL`` and, for compatible endpoints, ``LLM_BASE_URL``. The legacy ``ANTHROPIC_API_KEY`` is still honoured.
|
|
6
|
+
|
|
7
|
+
Safety: ``redact()`` strips secret-looking tokens from every outgoing prompt, and every call is recorded (size + hash, never content)
|
|
8
|
+
in ``CALL_LOG`` so the audit trail can show what left the machine.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
import requests
|
|
21
|
+
|
|
22
|
+
DEFAULT_MODELS = {"groq": "llama-3.3-70b-versatile", "gemini": "gemini-2.0-flash", "anthropic": "claude-sonnet-5-5", "openai": "gpt-4o-mini", "openai_compatible": "default"}
|
|
23
|
+
BASE_URLS = {"groq": "https://api.groq.com/openai/v1", "openai": "https://api.openai.com/v1"}
|
|
24
|
+
_SECRET = re.compile(r"(gsk_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_\-]{30,}|AQ\.[A-Za-z0-9_\-]{30,}|sk-ant-[A-Za-z0-9_\-]{20,}|sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|"
|
|
25
|
+
r"AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9\-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)")
|
|
26
|
+
CALL_LOG: list[dict] = []
|
|
27
|
+
_INFERENCE_CACHE: dict[str, str] = {}
|
|
28
|
+
_LOCK = threading.Lock()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LLMError(RuntimeError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def detect_provider(key: Optional[str], explicit: Optional[str] = None) -> Optional[str]:
|
|
36
|
+
if explicit:
|
|
37
|
+
return explicit.lower().replace("-", "_")
|
|
38
|
+
if not key:
|
|
39
|
+
return None
|
|
40
|
+
if key.startswith("gsk_"):
|
|
41
|
+
return "groq"
|
|
42
|
+
if key.startswith("AIza") or key.startswith("AQ."):
|
|
43
|
+
return "gemini"
|
|
44
|
+
if key.startswith("sk-ant-"):
|
|
45
|
+
return "anthropic"
|
|
46
|
+
if key.startswith("sk-"):
|
|
47
|
+
return "openai"
|
|
48
|
+
return "openai_compatible"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def redact(text: str) -> str:
|
|
52
|
+
return _SECRET.sub("[REDACTED]", text or "")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class LLM:
|
|
57
|
+
api_key: str
|
|
58
|
+
provider: str
|
|
59
|
+
model: str
|
|
60
|
+
base_url: Optional[str] = None
|
|
61
|
+
timeout: int = 60
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def label(self) -> str:
|
|
65
|
+
return f"{self.provider}:{self.model}"
|
|
66
|
+
|
|
67
|
+
def complete(self, system: str, user: str, max_tokens: int = 1200, json_mode: bool = False) -> str:
|
|
68
|
+
system, user = redact(system), redact(user)
|
|
69
|
+
cache_key = hashlib.sha256(f"{self.provider}:{self.model}:{system}:{user}:{json_mode}".encode()).hexdigest()
|
|
70
|
+
with _LOCK:
|
|
71
|
+
if cache_key in _INFERENCE_CACHE:
|
|
72
|
+
cached_out = _INFERENCE_CACHE[cache_key]
|
|
73
|
+
CALL_LOG.append({"provider": self.provider, "model": self.model, "prompt_chars": len(system) + len(user),
|
|
74
|
+
"prompt_sha256": cache_key[:16], "ok": True, "seconds": 0.0, "response_chars": len(cached_out),
|
|
75
|
+
"cached": True})
|
|
76
|
+
return cached_out
|
|
77
|
+
t0 = time.time()
|
|
78
|
+
try:
|
|
79
|
+
out = self._call(system, user, max_tokens, json_mode)
|
|
80
|
+
ok = True
|
|
81
|
+
except Exception as e: # noqa: BLE001
|
|
82
|
+
out, ok = "", False
|
|
83
|
+
err = f"{type(e).__name__}: {str(e)[:160]}"
|
|
84
|
+
with _LOCK:
|
|
85
|
+
CALL_LOG.append({"provider": self.provider, "model": self.model, "prompt_chars": len(system) + len(user), "prompt_sha256": cache_key[:16],
|
|
86
|
+
"ok": ok, "seconds": round(time.time() - t0, 2), "response_chars": len(out), **({} if ok else {"error": err})})
|
|
87
|
+
if ok:
|
|
88
|
+
_INFERENCE_CACHE[cache_key] = out
|
|
89
|
+
if not ok:
|
|
90
|
+
raise LLMError(err)
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
# ------------------------------------------------------------------ providers
|
|
94
|
+
def _call(self, system: str, user: str, max_tokens: int, json_mode: bool) -> str:
|
|
95
|
+
from core import netpolicy
|
|
96
|
+
netpolicy.current().require("ai", self.provider)
|
|
97
|
+
if self.provider == "anthropic":
|
|
98
|
+
r = requests.post("https://api.anthropic.com/v1/messages", timeout=self.timeout,
|
|
99
|
+
headers={"x-api-key": self.api_key, "anthropic-version": "2023-06-01", "content-type": "application/json"},
|
|
100
|
+
json={"model": self.model, "max_tokens": max_tokens, "system": system, "messages": [{"role": "user", "content": user}]})
|
|
101
|
+
r.raise_for_status()
|
|
102
|
+
return "".join(b.get("text", "") for b in r.json().get("content", []))
|
|
103
|
+
if self.provider == "gemini":
|
|
104
|
+
body = {"systemInstruction": {"parts": [{"text": system}]}, "contents": [{"role": "user", "parts": [{"text": user}]}],
|
|
105
|
+
"generationConfig": {"maxOutputTokens": max_tokens, **({"responseMimeType": "application/json"} if json_mode else {})}}
|
|
106
|
+
r = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent", timeout=self.timeout,
|
|
107
|
+
headers={"x-goog-api-key": self.api_key, "content-type": "application/json"}, json=body)
|
|
108
|
+
r.raise_for_status()
|
|
109
|
+
parts = (((r.json().get("candidates") or [{}])[0]).get("content") or {}).get("parts") or []
|
|
110
|
+
return "".join(p.get("text", "") for p in parts)
|
|
111
|
+
base = (self.base_url or BASE_URLS.get(self.provider) or "").rstrip("/")
|
|
112
|
+
if not base:
|
|
113
|
+
raise LLMError("LLM_BASE_URL is required for an OpenAI-compatible provider")
|
|
114
|
+
body = {"model": self.model, "max_tokens": max_tokens, "temperature": 0.1, "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
|
|
115
|
+
if json_mode and self.provider in ("groq", "openai"):
|
|
116
|
+
body["response_format"] = {"type": "json_object"}
|
|
117
|
+
r = requests.post(f"{base}/chat/completions", timeout=self.timeout, headers={"Authorization": f"Bearer {self.api_key}", "content-type": "application/json"}, json=body)
|
|
118
|
+
r.raise_for_status()
|
|
119
|
+
return ((r.json().get("choices") or [{}])[0].get("message") or {}).get("content", "")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def from_settings(s) -> Optional[LLM]:
|
|
123
|
+
"""Build the client from Settings, or None when no key is configured (deterministic mode)."""
|
|
124
|
+
key = getattr(s, "llm_api_key", None)
|
|
125
|
+
if not key:
|
|
126
|
+
return None
|
|
127
|
+
prov = detect_provider(key, getattr(s, "llm_provider", None))
|
|
128
|
+
model = getattr(s, "llm_model", None)
|
|
129
|
+
if not model or (prov != "anthropic" and model.startswith("claude")): # default model name belongs to another provider
|
|
130
|
+
model = DEFAULT_MODELS.get(prov, "default")
|
|
131
|
+
return LLM(api_key=key, provider=prov, model=model, base_url=getattr(s, "llm_base_url", None))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def extract_json(raw: str) -> dict:
|
|
135
|
+
a, b = raw.find("{"), raw.rfind("}")
|
|
136
|
+
if a < 0 or b <= a:
|
|
137
|
+
raise ValueError("no JSON object in the model reply")
|
|
138
|
+
return json.loads(raw[a:b + 1])
|
|
File without changes
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Continuous monitoring: re-assess *stored* inventories against newly disclosed vulnerabilities without re-cloning or re-scanning.
|
|
2
|
+
|
|
3
|
+
For each watched repository (or every repository that has a stored scan) the latest completed scan's component list is re-checked against OSV
|
|
4
|
+
(cache bypassed), the CISA KEV catalog and EPSS. Differences against what that scan recorded become alerts:
|
|
5
|
+
|
|
6
|
+
new_vulnerability an advisory now matches a component that had no finding for it when the scan ran
|
|
7
|
+
now_exploited a finding that was not in KEV when scanned is now listed as known exploited
|
|
8
|
+
epss_rise exploitation probability rose by >= 0.2 or crossed 0.5
|
|
9
|
+
|
|
10
|
+
Alerts are deduplicated per repository (a given alert is raised once), stored in ``monitor_events`` and shown in the Monitoring page.
|
|
11
|
+
Nothing is modified in the repository or the stored scan.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Optional
|
|
18
|
+
|
|
19
|
+
from config.settings import Settings
|
|
20
|
+
from core.http import HttpClient
|
|
21
|
+
from core.models import Component
|
|
22
|
+
from intel.epss import EpssClient
|
|
23
|
+
from storage.cache import Cache
|
|
24
|
+
from storage.database import Database
|
|
25
|
+
from vulnerability.kev_client import KevClient
|
|
26
|
+
from vulnerability.osv_client import OsvClient
|
|
27
|
+
from vulnerability.vulnerability_correlator import correlate
|
|
28
|
+
|
|
29
|
+
SCHEMA = """
|
|
30
|
+
CREATE TABLE IF NOT EXISTS watchlist (
|
|
31
|
+
repo_url TEXT PRIMARY KEY,
|
|
32
|
+
added_at TEXT NOT NULL,
|
|
33
|
+
interval_hours INTEGER NOT NULL DEFAULT 24,
|
|
34
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
35
|
+
last_run TEXT,
|
|
36
|
+
last_scan_id TEXT
|
|
37
|
+
);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS monitor_events (
|
|
39
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
+
repo_url TEXT NOT NULL,
|
|
41
|
+
at TEXT NOT NULL,
|
|
42
|
+
kind TEXT NOT NULL,
|
|
43
|
+
severity TEXT,
|
|
44
|
+
fingerprint TEXT NOT NULL,
|
|
45
|
+
title TEXT NOT NULL,
|
|
46
|
+
detail TEXT,
|
|
47
|
+
scan_id TEXT,
|
|
48
|
+
acknowledged INTEGER NOT NULL DEFAULT 0,
|
|
49
|
+
UNIQUE (repo_url, fingerprint)
|
|
50
|
+
);
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _now() -> str:
|
|
55
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def ensure(db: Database) -> None:
|
|
59
|
+
with db.connect() as c:
|
|
60
|
+
c.executescript(SCHEMA)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def add_watch(db: Database, repo_url: str, interval_hours: int = 24) -> None:
|
|
64
|
+
ensure(db)
|
|
65
|
+
with db.connect() as c:
|
|
66
|
+
c.execute("INSERT OR REPLACE INTO watchlist(repo_url, added_at, interval_hours, enabled) VALUES (?,?,?,1)", (repo_url, _now(), interval_hours))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def remove_watch(db: Database, repo_url: str) -> None:
|
|
70
|
+
ensure(db)
|
|
71
|
+
with db.connect() as c:
|
|
72
|
+
c.execute("DELETE FROM watchlist WHERE repo_url=?", (repo_url,))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def watchlist(db: Database) -> list[dict]:
|
|
76
|
+
ensure(db)
|
|
77
|
+
with db.connect() as c:
|
|
78
|
+
return [dict(r) for r in c.execute("SELECT * FROM watchlist ORDER BY added_at").fetchall()]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def events(db: Database, repo_url: Optional[str] = None, limit: int = 200) -> list[dict]:
|
|
82
|
+
ensure(db)
|
|
83
|
+
with db.connect() as c:
|
|
84
|
+
q, a = "SELECT * FROM monitor_events", []
|
|
85
|
+
if repo_url:
|
|
86
|
+
q += " WHERE repo_url=?"
|
|
87
|
+
a.append(repo_url)
|
|
88
|
+
return [dict(r) for r in c.execute(q + " ORDER BY id DESC LIMIT ?", (*a, limit)).fetchall()]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def acknowledge(db: Database, event_id: int) -> None:
|
|
92
|
+
with db.connect() as c:
|
|
93
|
+
c.execute("UPDATE monitor_events SET acknowledged=1 WHERE id=?", (event_id,))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _latest_scans(db: Database) -> dict[str, str]:
|
|
97
|
+
seen: dict[str, str] = {}
|
|
98
|
+
for s in db.list_scans(500):
|
|
99
|
+
if s["status"] != "failed" and not s["repo_url"].startswith(("local:", "local-fixture")) and s["repo_url"] not in seen:
|
|
100
|
+
seen[s["repo_url"]] = s["scan_id"]
|
|
101
|
+
return seen
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _record(db: Database, repo: str, scan_id: str, kind: str, severity: Optional[str], fp: str, title: str, detail: dict) -> Optional[dict]:
|
|
105
|
+
with db.connect() as c:
|
|
106
|
+
try:
|
|
107
|
+
c.execute("INSERT INTO monitor_events(repo_url, at, kind, severity, fingerprint, title, detail, scan_id) VALUES (?,?,?,?,?,?,?,?)", (repo, _now(), kind, severity, fp, title, json.dumps(detail, default=str), scan_id))
|
|
108
|
+
except Exception: # UNIQUE violation: already alerted
|
|
109
|
+
return None
|
|
110
|
+
return {"repo": repo, "kind": kind, "severity": severity or "UNKNOWN", "title": title, "detail": detail, "scan_id": scan_id}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def run_monitor(settings: Settings, db: Database, repo_url: Optional[str] = None, max_repos: int = 20, http: Optional[HttpClient] = None) -> dict[str, Any]:
|
|
114
|
+
ensure(db)
|
|
115
|
+
http = http or HttpClient(timeout=settings.http_timeout_s, retries=2)
|
|
116
|
+
latest = _latest_scans(db)
|
|
117
|
+
wl = [w["repo_url"] for w in watchlist(db) if w["enabled"]]
|
|
118
|
+
targets = [repo_url] if repo_url else (wl or list(latest))
|
|
119
|
+
targets = [t for t in targets if t in latest][:max_repos]
|
|
120
|
+
osv = OsvClient(http, None, settings.osv_batch_size, settings.osv_workers) # no cache: the point is to see *new* advisories
|
|
121
|
+
kev = KevClient(http, None)
|
|
122
|
+
epss = EpssClient(http, None)
|
|
123
|
+
out: dict[str, Any] = {"repos_checked": 0, "alerts": [], "errors": [], "checked_at": _now(), "sources": {}}
|
|
124
|
+
for repo in targets:
|
|
125
|
+
sid = latest[repo]
|
|
126
|
+
r = db.load_scan(sid)
|
|
127
|
+
if not r:
|
|
128
|
+
continue
|
|
129
|
+
try:
|
|
130
|
+
comps = [Component(**{k: v for k, v in c.items() if k in Component.model_fields}) for c in r.get("components", []) if not c.get("is_self") and c.get("ecosystem") and c.get("version") and c.get("type") != "file"]
|
|
131
|
+
res = correlate(comps, None, [], osv)
|
|
132
|
+
if res["source_status"]["OSV"]["state"] == "unavailable":
|
|
133
|
+
out["errors"].append(f"{repo}: OSV unavailable")
|
|
134
|
+
continue
|
|
135
|
+
old = {(f["package_name"], f["installed_version"], pid) for f in r.get("vulnerabilities", []) for pid in f["vulnerability_ids"]}
|
|
136
|
+
old_cves = {c for f in r.get("vulnerabilities", []) for c in f["cve_ids"]}
|
|
137
|
+
for f in res["findings"]:
|
|
138
|
+
if f.affected_status != "confirmed_affected":
|
|
139
|
+
continue
|
|
140
|
+
if any((f.package_name, f.installed_version, pid) in old for pid in f.vulnerability_ids):
|
|
141
|
+
continue
|
|
142
|
+
al = _record(db, repo, sid, "new_vulnerability", f.severity, f"new|{f.package_name}|{f.installed_version}|{f.primary_id}", f"{f.primary_id} now affects {f.package_name}@{f.installed_version}" + (f" (fixed in {', '.join(f.fixed_versions[:2])})" if f.fixed_versions else ""),
|
|
143
|
+
{"package": f.package_name, "version": f.installed_version, "id": f.primary_id, "severity": f.severity, "cves": f.cve_ids[:4], "fixed": f.fixed_versions[:3]})
|
|
144
|
+
if al:
|
|
145
|
+
out["alerts"].append(al)
|
|
146
|
+
cves = sorted(old_cves | {c for f in res["findings"] for c in f.cve_ids})
|
|
147
|
+
for f in r.get("vulnerabilities", []):
|
|
148
|
+
for c in f["cve_ids"]:
|
|
149
|
+
if not f.get("kev") and kev.lookup(c):
|
|
150
|
+
al = _record(db, repo, sid, "now_exploited", "CRITICAL", f"kev|{c}", f"{c} ({f['package_name']}@{f['installed_version']}) is now listed as actively exploited (CISA KEV)", {"cve": c, "package": f["package_name"], "kev": kev.lookup(c)})
|
|
151
|
+
if al:
|
|
152
|
+
out["alerts"].append(al)
|
|
153
|
+
scores = epss.get_many(sorted(old_cves))
|
|
154
|
+
for f in r.get("vulnerabilities", []):
|
|
155
|
+
before = f.get("epss")
|
|
156
|
+
for c in f["cve_ids"]:
|
|
157
|
+
now = (scores.get(c) or {}).get("epss")
|
|
158
|
+
if now is None:
|
|
159
|
+
continue
|
|
160
|
+
if (before is None and now >= 0.5) or (before is not None and (now - before >= 0.2 or (before < 0.5 <= now))):
|
|
161
|
+
al = _record(db, repo, sid, "epss_rise", "HIGH", f"epss|{c}|{round(now, 1)}", f"Exploitation probability of {c} ({f['package_name']}) rose to {now:.0%}" + (f" from {before:.0%}" if before is not None else ""),
|
|
162
|
+
{"cve": c, "before": before, "now": now})
|
|
163
|
+
if al:
|
|
164
|
+
out["alerts"].append(al)
|
|
165
|
+
out["repos_checked"] += 1
|
|
166
|
+
with db.connect() as cx:
|
|
167
|
+
cx.execute("UPDATE watchlist SET last_run=?, last_scan_id=? WHERE repo_url=?", (_now(), sid, repo))
|
|
168
|
+
except Exception as e: # noqa: BLE001 - one repository failing must not stop the rest
|
|
169
|
+
out["errors"].append(f"{repo}: {type(e).__name__}: {str(e)[:120]}")
|
|
170
|
+
out["sources"] = {"osv": osv.status.get("state"), "kev": kev.status.get("state"), "epss": epss.status.get("state")}
|
|
171
|
+
return out
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Modular Non-CVE scanner registry and built-in layers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from non_cve.base import NonCveScanner, ScanContext, register_scanner, registered_scanners, run_all_scanners
|
|
5
|
+
from non_cve import iac, sast, supply_chain # noqa: F401 (registers built-in scanners)
|
|
6
|
+
|
|
7
|
+
__all__ = ["NonCveScanner", "ScanContext", "register_scanner", "registered_scanners", "run_all_scanners"]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Modular Non-CVE detection framework (Supply-Chain Anomalies, SAST/Taint, IaC)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class ScanContext:
|
|
11
|
+
repo_dir: Path
|
|
12
|
+
components: list[Any] = field(default_factory=list)
|
|
13
|
+
lock_deps: list[Any] = field(default_factory=list)
|
|
14
|
+
inspection: Any = None
|
|
15
|
+
scan_timestamp: str = ""
|
|
16
|
+
http_client: Any = None
|
|
17
|
+
registry_checks: bool = True
|
|
18
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class NonCveScanner(Protocol):
|
|
22
|
+
name: str
|
|
23
|
+
category: str
|
|
24
|
+
|
|
25
|
+
def scan(self, ctx: ScanContext) -> dict[str, Any]:
|
|
26
|
+
"""Return {'findings': list[dict], 'limitations': list[str], 'meta': dict}."""
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_SCANNERS: list[NonCveScanner] = []
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def register_scanner(scanner: NonCveScanner) -> NonCveScanner:
|
|
34
|
+
if not any(s.name == scanner.name for s in _SCANNERS):
|
|
35
|
+
_SCANNERS.append(scanner)
|
|
36
|
+
return scanner
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def registered_scanners() -> list[NonCveScanner]:
|
|
40
|
+
return list(_SCANNERS)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run_all_scanners(ctx: ScanContext) -> dict[str, Any]:
|
|
44
|
+
"""Execute all registered Non-CVE scanners with per-scanner error isolation."""
|
|
45
|
+
by_category: dict[str, list[dict[str, Any]]] = {}
|
|
46
|
+
limitations: list[str] = []
|
|
47
|
+
meta: dict[str, Any] = {}
|
|
48
|
+
for sc in _SCANNERS:
|
|
49
|
+
try:
|
|
50
|
+
applicable = getattr(sc, "applicable", None)
|
|
51
|
+
if applicable and not applicable(ctx):
|
|
52
|
+
meta[sc.name] = {"status": "skipped", "reason": "No applicable repository inputs"}
|
|
53
|
+
continue
|
|
54
|
+
res = sc.scan(ctx)
|
|
55
|
+
findings = res.get("findings") or []
|
|
56
|
+
by_category.setdefault(sc.category, []).extend(findings)
|
|
57
|
+
limitations.extend(res.get("limitations") or [])
|
|
58
|
+
meta[sc.name] = {"findings": len(findings), "status": "ok", **(res.get("meta") or {})}
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
limitations.append(f"Non-CVE scanner '{sc.name}' failed ({type(exc).__name__}: {str(exc)[:160]}).")
|
|
61
|
+
meta[sc.name] = {"findings": 0, "status": "error", "error": str(exc)[:160]}
|
|
62
|
+
return {"by_category": by_category, "limitations": limitations, "meta": meta}
|