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,279 @@
|
|
|
1
|
+
"""LangGraph state graph that runs the agent pipeline.
|
|
2
|
+
|
|
3
|
+
discover -> classify -> plan -> lockfiles -> sbom_generate -> sbom_validate -> pipeline (Docker/CI) -> sbom_quality
|
|
4
|
+
-> (conditional) sbom_second_pass -> sbom_metadata (fusion) -> graph
|
|
5
|
+
graph -> [ vulnerability -> verification -> investigator ] || [ typosquat -> lockfile_history -> package_risk ] (parallel branches)
|
|
6
|
+
-> risk (joins both) -> explain -> assemble -> summary -> export -> finalize
|
|
7
|
+
|
|
8
|
+
Design rules
|
|
9
|
+
* Agents stay deterministic and rule-based; the graph only decides order, branching and parallelism.
|
|
10
|
+
* The LangGraph state is thin (scan id + trail of executed nodes). Heavy objects (NetworkX graph, components, results) live in the
|
|
11
|
+
in-process ``ScanState`` registered under the scan id, so checkpoints stay small.
|
|
12
|
+
* Every node is wrapped: it never raises into the graph (an exception becomes a recorded step error) and it is skipped with a recorded
|
|
13
|
+
limitation when a step it depends on has failed.
|
|
14
|
+
* The graph runs in a worker thread; events are queued and delivered to the caller's ``on_event`` from the calling thread, so UI
|
|
15
|
+
frameworks that need their own thread (Streamlit) keep working while the Threat and Vulnerability agents run in parallel.
|
|
16
|
+
* Checkpoints (SQLite) record the trail per node for audit; they are not used to resume a half-finished scan.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import operator
|
|
21
|
+
import queue
|
|
22
|
+
import threading
|
|
23
|
+
import traceback
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Annotated, Any, Callable, Optional, TypedDict
|
|
26
|
+
|
|
27
|
+
from langgraph.checkpoint.sqlite import SqliteSaver
|
|
28
|
+
from langgraph.graph import END, START, StateGraph
|
|
29
|
+
|
|
30
|
+
from agents.runtime import Runtime
|
|
31
|
+
from agents.investigator import InvestigatorAgent
|
|
32
|
+
from agents.memory_agent import MemoryAgent
|
|
33
|
+
from agents.pipeline_agent import PipelineAgent
|
|
34
|
+
from agents.remediation_agent import RemediationAgent, ValidatorAgent
|
|
35
|
+
from agents.specialists import (AnalystAgent, GraphAgent, ReconAgent, RiskAgent, SBOMAgent, ScanState, ThreatAgent, VerificationAgent,
|
|
36
|
+
VulnerabilityAgent)
|
|
37
|
+
from core import git_manager as gm
|
|
38
|
+
from orchestration import supervisor as sup
|
|
39
|
+
from reporting import json_exporter
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GraphState(TypedDict):
|
|
43
|
+
scan_id: str
|
|
44
|
+
trail: Annotated[list[str], operator.add]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_REG: dict[str, tuple[ScanState, Runtime, Optional[Path]]] = {}
|
|
48
|
+
|
|
49
|
+
# node -> (callable(st, rt, workspace), runtime steps owned by the node, steps that must not have failed)
|
|
50
|
+
NODES: dict[str, tuple[Callable, tuple[str, ...], tuple[str, ...]]] = {}
|
|
51
|
+
|
|
52
|
+
memory = MemoryAgent()
|
|
53
|
+
investigator = InvestigatorAgent()
|
|
54
|
+
remediation_agent = RemediationAgent()
|
|
55
|
+
validator_agent = ValidatorAgent()
|
|
56
|
+
pipeline_agent = PipelineAgent()
|
|
57
|
+
recon, sbom, graph_agent, vuln, ver, threat, risk, analyst = (ReconAgent(), SBOMAgent(), GraphAgent(), VulnerabilityAgent(), VerificationAgent(),
|
|
58
|
+
ThreatAgent(), RiskAgent(), AnalystAgent())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _register(name: str, fn: Callable, steps: tuple[str, ...] = (), requires: tuple[str, ...] = ()) -> None:
|
|
62
|
+
NODES[name] = (fn, steps, requires)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _export(st: ScanState, rt: Runtime, ws: Optional[Path]) -> None:
|
|
66
|
+
sup.finalize(st, rt)
|
|
67
|
+
analyst.export(st, rt)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _finalize(st: ScanState, rt: Runtime, ws: Optional[Path]) -> None:
|
|
71
|
+
sup.cleanup(rt, ws, st.options.keep_workspace, st.result)
|
|
72
|
+
sup.finalize(st, rt, final=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_register("discover", lambda st, rt, ws: recon.discover(st, rt), ("discover",))
|
|
76
|
+
_register("classify", lambda st, rt, ws: recon.classify(st, rt), ("classify",))
|
|
77
|
+
_register("plan", lambda st, rt, ws: sup.plan(st, rt), ("plan",))
|
|
78
|
+
_register("lockfiles", lambda st, rt, ws: sbom.lockfiles(st, rt), ("lockfiles",))
|
|
79
|
+
_register("sbom_generate", lambda st, rt, ws: sbom.generate(st, rt), ("sbom_generate",))
|
|
80
|
+
_register("sbom_validate", lambda st, rt, ws: sbom.validate(st, rt), ("sbom_validate",))
|
|
81
|
+
_register("pipeline", lambda st, rt, ws: pipeline_agent.run(st, rt), ("pipeline",))
|
|
82
|
+
_register("sbom_quality", lambda st, rt, ws: sbom.quality(st, rt), ("quality",))
|
|
83
|
+
_register("sbom_second_pass", lambda st, rt, ws: sbom.second_pass(st, rt), ("quality",))
|
|
84
|
+
_register("sbom_metadata", lambda st, rt, ws: sbom.fuse_metadata(st, rt), ("metadata",))
|
|
85
|
+
_register("graph", lambda st, rt, ws: graph_agent.build(st, rt), ("graph",))
|
|
86
|
+
_register("vulnerability", lambda st, rt, ws: vuln.run(st, rt), ("osv", "enrich", "trace"))
|
|
87
|
+
_register("verification", lambda st, rt, ws: ver.run(st, rt), ("verify",))
|
|
88
|
+
_register("investigator", lambda st, rt, ws: investigator.run(st, rt), ("investigate",))
|
|
89
|
+
_register("typosquat", lambda st, rt, ws: threat.typosquat(st, rt), ("typosquat",), ("graph",))
|
|
90
|
+
_register("package_risk", lambda st, rt, ws: threat.package_risk(st, rt), ("package_risk",))
|
|
91
|
+
_register("lockfile_history", lambda st, rt, ws: threat.lockfile_history(st, rt), ("lockfile_history",))
|
|
92
|
+
_register("suspicious_changes", lambda st, rt, ws: threat.suspicious_changes(st, rt), ("suspicious_changes",))
|
|
93
|
+
_register("risk", lambda st, rt, ws: risk.score(st, rt), ("risk",))
|
|
94
|
+
_register("explain", lambda st, rt, ws: risk.explain(st, rt), ("explain",), ("risk",))
|
|
95
|
+
_register("remediate", lambda st, rt, ws: remediation_agent.run(st, rt), ("remediate",))
|
|
96
|
+
_register("validate_fix", lambda st, rt, ws: validator_agent.run(st, rt), ("validate_fix",), ("remediate",))
|
|
97
|
+
_register("memory", lambda st, rt, ws: memory.run(st, rt), ("memory",))
|
|
98
|
+
_register("assemble", lambda st, rt, ws: sup.assemble(st, rt, ws))
|
|
99
|
+
_register("summary", lambda st, rt, ws: analyst.summarize(st, rt), ("summary",), ("risk",))
|
|
100
|
+
_register("export", _export, ("export",))
|
|
101
|
+
_register("finalize", _finalize, ("cleanup",))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _wrap(name: str) -> Callable[[GraphState], dict]:
|
|
105
|
+
fn, steps, requires = NODES[name]
|
|
106
|
+
|
|
107
|
+
def run(state: GraphState) -> dict:
|
|
108
|
+
st, rt, ws = _REG[state["scan_id"]]
|
|
109
|
+
if st.options.cancelled and st.options.cancelled():
|
|
110
|
+
from concurrent.futures import CancelledError
|
|
111
|
+
raise CancelledError("Scan cancelled")
|
|
112
|
+
failed = [r for r in requires if rt.status.get(r) == "error"]
|
|
113
|
+
try:
|
|
114
|
+
if st.options.offline and name in {"vulnerability", "verification", "investigator"}:
|
|
115
|
+
for sid in steps:
|
|
116
|
+
rt.skip(sid, "network lookup disabled for offline scan")
|
|
117
|
+
elif failed:
|
|
118
|
+
for sid in steps:
|
|
119
|
+
if rt.status.get(sid) == "pending":
|
|
120
|
+
rt.skip(sid, f"skipped: required step '{failed[0]}' failed")
|
|
121
|
+
st.result.setdefault("limitations", []).append(f"'{name}' was skipped because '{failed[0]}' failed; related sections are empty.")
|
|
122
|
+
else:
|
|
123
|
+
fn(st, rt, ws)
|
|
124
|
+
except Exception as e: # a node must never take the pipeline down
|
|
125
|
+
sid = next((x for x in steps if rt.status.get(x) in ("running", "pending")), steps[0] if steps else None)
|
|
126
|
+
if sid:
|
|
127
|
+
rt.fail(sid, f"{type(e).__name__}: {str(e)[:300]}")
|
|
128
|
+
rt.errors[-1]["trace"] = traceback.format_exc()[-500:]
|
|
129
|
+
else:
|
|
130
|
+
rt.errors.append({"stage": name, "error": f"{type(e).__name__}: {str(e)[:300]}"})
|
|
131
|
+
st.result.setdefault("limitations", []).append(f"Stage '{name}' failed ({type(e).__name__}); its results are missing or partial.")
|
|
132
|
+
return {"trail": [name]}
|
|
133
|
+
|
|
134
|
+
run.__name__ = name
|
|
135
|
+
return run
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def build_graph() -> StateGraph:
|
|
139
|
+
g = StateGraph(GraphState)
|
|
140
|
+
for name in NODES:
|
|
141
|
+
g.add_node(name, _wrap(name))
|
|
142
|
+
chain = ["discover", "classify", "plan", "lockfiles", "sbom_generate", "sbom_validate", "pipeline", "sbom_quality"]
|
|
143
|
+
g.add_edge(START, chain[0])
|
|
144
|
+
for a, b in zip(chain, chain[1:]):
|
|
145
|
+
g.add_edge(a, b)
|
|
146
|
+
|
|
147
|
+
def route_quality(state: GraphState) -> str:
|
|
148
|
+
return "sbom_second_pass" if SBOMAgent.wants_second_pass(_REG[state["scan_id"]][0]) else "sbom_metadata"
|
|
149
|
+
|
|
150
|
+
g.add_conditional_edges("sbom_quality", route_quality, {"sbom_second_pass": "sbom_second_pass", "sbom_metadata": "sbom_metadata"})
|
|
151
|
+
g.add_edge("sbom_second_pass", "sbom_metadata")
|
|
152
|
+
g.add_edge("sbom_metadata", "graph")
|
|
153
|
+
g.add_edge("graph", "vulnerability") # parallel branch A
|
|
154
|
+
g.add_edge("graph", "typosquat") # parallel branch B
|
|
155
|
+
g.add_edge("vulnerability", "verification")
|
|
156
|
+
g.add_edge("verification", "investigator")
|
|
157
|
+
g.add_edge("typosquat", "lockfile_history")
|
|
158
|
+
g.add_edge("lockfile_history", "package_risk")
|
|
159
|
+
g.add_edge("package_risk", "suspicious_changes")
|
|
160
|
+
g.add_edge(["investigator", "suspicious_changes"], "risk") # join: waits for both branches
|
|
161
|
+
for a, b in (("risk", "explain"), ("explain", "remediate"), ("remediate", "validate_fix"), ("validate_fix", "memory"), ("memory", "assemble"), ("assemble", "summary"), ("summary", "export"), ("export", "finalize"), ("finalize", END)):
|
|
162
|
+
g.add_edge(a, b)
|
|
163
|
+
return g
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
PHASES = {"Discover": "#2563eb", "Inventory": "#0891b2", "Detect": "#d97706", "Analyze": "#7c3aed", "Remediate & Validate": "#059669", "Report": "#64748b"}
|
|
167
|
+
_PHASE_OF = {"Recon Agent": "Discover", "Supervisor": "Discover", "Pipeline Agent": "Discover", "SBOM Agent": "Inventory", "Graph Agent": "Inventory",
|
|
168
|
+
"Vulnerability Agent": "Detect", "Verification Agent": "Detect", "Threat Agent": "Detect", "Investigator Agent": "Analyze", "Risk Agent": "Analyze",
|
|
169
|
+
"Remediation Agent": "Remediate & Validate", "Validator Agent": "Remediate & Validate", "Memory Agent": "Report", "Analyst Agent": "Report"}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def workflow_payload() -> dict:
|
|
173
|
+
"""Agent-level view of the real compiled LangGraph: one box per agent, edges collapsed from the graph's node edges
|
|
174
|
+
(backward edges such as the second SBOM pass are dropped so the diagram stays a readable left-to-right flow)."""
|
|
175
|
+
from agents.runtime import AGENT_ROLES, STEPS
|
|
176
|
+
agent_of = {sid: ag for sid, ag, _ in STEPS}
|
|
177
|
+
label_of = {sid: lab for sid, _, lab in STEPS}
|
|
178
|
+
owner = {name: (agent_of.get(steps[0], "Supervisor") if steps else "Analyst Agent") for name, (_, steps, _) in NODES.items()}
|
|
179
|
+
order = list(dict.fromkeys(owner.values()))
|
|
180
|
+
edges: list[list] = []
|
|
181
|
+
for e in build_graph().compile().get_graph().edges:
|
|
182
|
+
if e.source in owner and e.target in owner:
|
|
183
|
+
a, b = owner[e.source], owner[e.target]
|
|
184
|
+
if a != b and order.index(a) < order.index(b) and [a, b] not in [x[:2] for x in edges]:
|
|
185
|
+
edges.append([a, b])
|
|
186
|
+
edges.append(["Pipeline Agent", "Risk Agent"]) # container/CI findings feed the risk model
|
|
187
|
+
nodes = [{"id": a, "label": a.replace(" Agent", ""), "phase": _PHASE_OF.get(a, "Report"), "role": AGENT_ROLES.get(a, ""),
|
|
188
|
+
"steps": [label_of[s] for _, (_, steps, _) in NODES.items() for s in steps if agent_of.get(s) == a and s in label_of] if a != "Analyst Agent" else
|
|
189
|
+
[label_of[s] for s in ("summary", "export")],
|
|
190
|
+
"ai": a in ("Investigator Agent", "Risk Agent"), "approval": a in ("Remediation Agent", "Validator Agent")} for a in order]
|
|
191
|
+
return {"nodes": nodes, "edges": edges, "colors": PHASES}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def mermaid() -> str:
|
|
195
|
+
try:
|
|
196
|
+
return build_graph().compile().get_graph().draw_mermaid()
|
|
197
|
+
except Exception:
|
|
198
|
+
return ""
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def run_pipeline(st: ScanState, rt: Runtime, workspace: Optional[Path]) -> dict[str, Any]:
|
|
202
|
+
"""Execute the graph for one scan and return the assembled result (always a full-schema dict)."""
|
|
203
|
+
s, db, info = st.ctx.s, st.ctx.db, st.info
|
|
204
|
+
_REG[info.scan_id] = (st, rt, workspace)
|
|
205
|
+
deliver = rt.on_event
|
|
206
|
+
q: "queue.Queue[Any]" = queue.Queue()
|
|
207
|
+
rt.on_event = q.put # worker-thread events are replayed to the caller's callback from the caller's thread
|
|
208
|
+
box: dict[str, Any] = {}
|
|
209
|
+
interrupted = threading.Event()
|
|
210
|
+
requested = st.options.cancelled
|
|
211
|
+
st.options.cancelled = lambda: interrupted.is_set() or bool(requested and requested())
|
|
212
|
+
|
|
213
|
+
def worker() -> None:
|
|
214
|
+
try:
|
|
215
|
+
with SqliteSaver.from_conn_string(str(s.data_dir / "checkpoints.db")) as cp:
|
|
216
|
+
app = build_graph().compile(checkpointer=cp)
|
|
217
|
+
out = app.invoke({"scan_id": info.scan_id, "trail": []}, {"configurable": {"thread_id": info.scan_id}})
|
|
218
|
+
box["trail"] = out.get("trail", [])
|
|
219
|
+
except BaseException as e: # noqa: BLE001 - surfaced to the caller below
|
|
220
|
+
box["error"] = e
|
|
221
|
+
finally:
|
|
222
|
+
q.put(None)
|
|
223
|
+
|
|
224
|
+
t = threading.Thread(target=worker, name=f"scan-{info.scan_id}", daemon=True)
|
|
225
|
+
t.start()
|
|
226
|
+
try:
|
|
227
|
+
while True:
|
|
228
|
+
try:
|
|
229
|
+
ev = q.get(timeout=0.2) # a bounded wait keeps Ctrl+C responsive on Windows
|
|
230
|
+
except queue.Empty:
|
|
231
|
+
continue
|
|
232
|
+
if ev is None:
|
|
233
|
+
break
|
|
234
|
+
if deliver:
|
|
235
|
+
try:
|
|
236
|
+
deliver(ev)
|
|
237
|
+
except Exception:
|
|
238
|
+
rt.callback_errors += 1
|
|
239
|
+
except KeyboardInterrupt:
|
|
240
|
+
interrupted.set() # the worker stops before its next stage; the caller removes any workspace
|
|
241
|
+
raise
|
|
242
|
+
finally:
|
|
243
|
+
rt.on_event = deliver
|
|
244
|
+
t.join(timeout=30 if interrupted.is_set() else None)
|
|
245
|
+
_REG.pop(info.scan_id, None)
|
|
246
|
+
st.options.cancelled = requested
|
|
247
|
+
res = st.result
|
|
248
|
+
from concurrent.futures import CancelledError
|
|
249
|
+
if isinstance(box.get("error"), CancelledError):
|
|
250
|
+
raise box["error"]
|
|
251
|
+
if "error" in box: # the graph machinery itself failed (not an agent): return what exists, flagged
|
|
252
|
+
rt.errors.append({"stage": "orchestration", "error": f"{type(box['error']).__name__}: {str(box['error'])[:300]}"})
|
|
253
|
+
res.setdefault("limitations", []).append("The orchestration engine failed; the result is partial.")
|
|
254
|
+
sup.assemble(st, rt, workspace)
|
|
255
|
+
sup.cleanup(rt, workspace, st.options.keep_workspace, res)
|
|
256
|
+
sup.finalize(st, rt, final=True)
|
|
257
|
+
res["orchestration"] = {"engine": "langgraph", "trail": box.get("trail", []), "checkpoint_thread": info.scan_id,
|
|
258
|
+
"callback_errors": rt.callback_errors, "graph": mermaid()}
|
|
259
|
+
try:
|
|
260
|
+
json_exporter.write_all(res, s.artifacts_dir / "scans", st.prefix)
|
|
261
|
+
except Exception as e:
|
|
262
|
+
res.setdefault("errors", []).append({"stage": "export", "error": f"{type(e).__name__}: {str(e)[:300]}"})
|
|
263
|
+
res["status"] = "completed_with_errors"
|
|
264
|
+
res["limitations"].append("Some JSON exports could not be written. Saved results can still be exported from StackParity.")
|
|
265
|
+
from reporting.view import coverage
|
|
266
|
+
res["coverage"] = coverage(res)
|
|
267
|
+
try:
|
|
268
|
+
db.save_scan(res)
|
|
269
|
+
except Exception as e: # never silent: the user must know the result was not persisted
|
|
270
|
+
res.setdefault("errors", []).append({"stage": "persist", "error": f"{type(e).__name__}: {str(e)[:300]}"})
|
|
271
|
+
res["status"] = "completed_with_errors"
|
|
272
|
+
res["limitations"].append("The result could not be saved to the database.")
|
|
273
|
+
else:
|
|
274
|
+
try:
|
|
275
|
+
for old in db.prune_repo(info.url, s.keep_scans_per_repo):
|
|
276
|
+
gm.remove_artifacts(s, old)
|
|
277
|
+
except Exception as e:
|
|
278
|
+
res["limitations"].append(f"Older scan cleanup failed: {type(e).__name__}: {str(e)[:300]}")
|
|
279
|
+
return res
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Supervisor helpers executed as graph nodes: analysis plan, result assembly, finalisation and workspace clean-up."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import platform
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import networkx as nx
|
|
10
|
+
|
|
11
|
+
from agents.runtime import AGENT_ROLES, AGENTS, STEPS, Runtime
|
|
12
|
+
from agents.specialists import ScanState
|
|
13
|
+
from core import git_manager as gm
|
|
14
|
+
from core.repository_inspector import headline_languages
|
|
15
|
+
from risk_analysis.risk_rules import RULES_VERSION
|
|
16
|
+
|
|
17
|
+
SCANNER_VERSION = "2.2.0" # bump whenever analysis output changes, so stored scans are not reused
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def plan(st: ScanState, rt: Runtime) -> None:
|
|
21
|
+
"""Supervisor: turn the Recon findings into an explicit analysis plan (recorded as decisions)."""
|
|
22
|
+
with rt.step("plan") as b:
|
|
23
|
+
insp, o = st.insp, st.options
|
|
24
|
+
plan: list[str] = []
|
|
25
|
+
|
|
26
|
+
def decide(msg: str, why: str) -> None:
|
|
27
|
+
plan.append(msg)
|
|
28
|
+
rt.decide("plan", msg, reason=why, agent="Supervisor")
|
|
29
|
+
|
|
30
|
+
by_eco: dict[str, list[str]] = {}
|
|
31
|
+
for m in insp.manifests:
|
|
32
|
+
by_eco.setdefault(m.ecosystem, []).append(m.name)
|
|
33
|
+
if not by_eco:
|
|
34
|
+
decide("Rely on the SBOM scanner alone for inventory", "No manifests or lockfiles were found, so lockfile parsing has nothing to cross-check.")
|
|
35
|
+
for eco, names in sorted(by_eco.items()):
|
|
36
|
+
has_lock = any(m.ecosystem == eco and m.kind == "lockfile" for m in insp.manifests)
|
|
37
|
+
decide(f"{eco}: " + ("parse lockfiles for an independent inventory and direct/transitive flags" if has_lock
|
|
38
|
+
else "manifest only - versions may be unresolved; rely on the SBOM scanner and report unpinned dependencies"),
|
|
39
|
+
f"Found {', '.join(sorted(set(names)))}")
|
|
40
|
+
if insp.unsupported:
|
|
41
|
+
decide("Report unsupported ecosystems instead of guessing", "; ".join(insp.unsupported))
|
|
42
|
+
if insp.dockerfiles or insp.container_files or insp.ci_files:
|
|
43
|
+
decide("Analyse Dockerfiles, compose files and CI/CD workflows statically (Pipeline Agent)", "Container and pipeline definitions are part of the supply chain: unpinned bases/actions, root containers, remote scripts, injectable workflows. Nothing is built or executed.")
|
|
44
|
+
if st.git_history:
|
|
45
|
+
decide(f"Compare lockfiles for the last {o.lockfile_commits} commit(s) against their parents" + (f" (explicit baseline {o.baseline})" if o.baseline else ""),
|
|
46
|
+
"Git history is available" + (" but shallow (depth-limited); missing parents are reported, not guessed" if st.info.shallow else ""))
|
|
47
|
+
else:
|
|
48
|
+
decide("Skip Git-history lockfile analysis", "The scanned path is not the top level of a Git repository.")
|
|
49
|
+
if o.offline:
|
|
50
|
+
decide("Skip remote advisory lookups", "Offline scan requested.")
|
|
51
|
+
else:
|
|
52
|
+
decide("Query OSV.dev (ground truth), validate ranges locally, then re-verify by PURL" + (", enrich with NVD" if o.use_nvd else "") + (" and CISA KEV" if o.use_kev else ""),
|
|
53
|
+
"Matching uses ecosystem + name + version, never name alone.")
|
|
54
|
+
st.result["plan"] = plan
|
|
55
|
+
b["message"] = f"{len(plan)} planning decisions"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def assemble(st: ScanState, rt: Runtime, workspace: Optional[Path]) -> None:
|
|
59
|
+
res = st.result
|
|
60
|
+
res["inspection"] = {**st.insp.model_dump(), "headline_languages": headline_languages(st.insp)}
|
|
61
|
+
from ecosystems.registry import support_level, technology_support
|
|
62
|
+
from sbom.lockfile_analyzer import manifest_parser_for, parser_for
|
|
63
|
+
support = {}
|
|
64
|
+
for eco in st.insp.ecosystems:
|
|
65
|
+
names = {m.name for m in st.insp.manifests if m.ecosystem == eco}
|
|
66
|
+
parsed = sorted(name for name in names if parser_for(name) or manifest_parser_for(name))
|
|
67
|
+
support[eco] = {"builtin_parser_support": support_level(sorted(names)), "recognized_inputs": parsed,
|
|
68
|
+
"unhandled_inputs": sorted(names - set(parsed))}
|
|
69
|
+
res["inspection"]["inventory_capabilities"] = support
|
|
70
|
+
res["inspection"]["technologies"] = technology_support(st.insp)
|
|
71
|
+
res["lockfile_dependencies"] = [d.model_dump() for d in st.lock_deps]
|
|
72
|
+
res["lockfile_errors"] = st.lock_errors
|
|
73
|
+
res["sbom_tool"] = st.sbom_tool
|
|
74
|
+
res["metadata_fusion"] = st.fusion or None
|
|
75
|
+
res["sbom_files"] = st.sbom_files or ([{"label": f"{st.inventory_source} (raw scanner output)", "path": st.sbom_path}] if st.sbom_path else [])
|
|
76
|
+
res["syft"] = st.syft.to_dict() if (st.syft is not None and st.inventory_source == "syft") else None # kept for stored scans / API compatibility
|
|
77
|
+
res["inventory_source"], res["sbom_path"] = st.inventory_source, st.sbom_path
|
|
78
|
+
res.setdefault("sbom", {"path": st.sbom_path, "validation": {"valid": False, "errors": ["SBOM not generated"], "warnings": [], "stats": {}}})
|
|
79
|
+
res.setdefault("enrichment", None)
|
|
80
|
+
res["components"] = [c.model_dump() for c in st.components]
|
|
81
|
+
res["quality"] = st.quality
|
|
82
|
+
res.setdefault("graph", {"nodes": [], "edges": [], "roots": [], "validation": {}, "relationships": {}})
|
|
83
|
+
res.setdefault("vuln_coverage", {})
|
|
84
|
+
res.setdefault("source_status", {})
|
|
85
|
+
res["vulnerabilities"] = st.vulns
|
|
86
|
+
res["typosquatting_meta"] = {"suppressed": st.typo["suppressed"], "stats": st.typo["stats"]}
|
|
87
|
+
res["lockfile_analysis"] = {k: v for k, v in st.lres.items() if k != "findings"}
|
|
88
|
+
res["lockfile_changes"] = st.lres["findings"]
|
|
89
|
+
res["limitations"].extend(st.lres.get("limitations", []))
|
|
90
|
+
res["risk_rules_version"] = RULES_VERSION
|
|
91
|
+
res["workspace"] = {"location": str(workspace) if workspace else None, "clone_path": str(st.repo_dir), "kept": bool(st.options.keep_workspace),
|
|
92
|
+
"removed": False, "note": "Temporary, isolated, git-ignored; deleted after the scan unless 'keep clone' is ticked."}
|
|
93
|
+
res["tool_versions"] = {"scanner": SCANNER_VERSION, "sbom_scanner": st.inventory_source if st.inventory_source != "none" else "unavailable",
|
|
94
|
+
"sbom_scanner_version": (st.syft.version if st.syft else None) or ("rule engine 1.0" if st.inventory_source == "builtin" else "n/a"),
|
|
95
|
+
"python": platform.python_version(), "networkx": nx.__version__}
|
|
96
|
+
res["limitations"] = list(dict.fromkeys(res["limitations"] + (st.quality.get("limitations", []) if st.quality else [])))
|
|
97
|
+
# full-schema defaults: a failed or skipped stage must never leave a key missing for the UI/reports
|
|
98
|
+
from agents.specialists import _summary, source_package_view
|
|
99
|
+
res.setdefault("summary", _summary(st, res))
|
|
100
|
+
res.setdefault("analyst", {"headline": "Analysis incomplete - see limitations and errors.", "paragraphs": [], "priorities": []})
|
|
101
|
+
res.setdefault("risk_assessments", st.risk.get("assessments", []))
|
|
102
|
+
res.setdefault("correlations", st.risk.get("correlations", []))
|
|
103
|
+
res.setdefault("risk_by_root", [])
|
|
104
|
+
res.setdefault("explanations", {})
|
|
105
|
+
res.setdefault("evidence", {})
|
|
106
|
+
res.setdefault("typosquatting", [f.model_dump() for f in st.typo["findings"]])
|
|
107
|
+
res.setdefault("source_package_view", [])
|
|
108
|
+
res.setdefault("memory", {"diff": None, "fingerprints": {}, "titles": {}})
|
|
109
|
+
res["pipeline"] = st.pipe
|
|
110
|
+
res.setdefault("investigations", {})
|
|
111
|
+
res["package_risk"] = st.pkgrisk
|
|
112
|
+
res["suspicious_changes"] = st.suspicious_changes or {"findings": [], "correlated_scenarios": [], "ai_investigations": [], "metrics": {}}
|
|
113
|
+
res["supply_chain_anomalies"] = st.supply_chain_anomalies
|
|
114
|
+
res["sast_findings"] = st.sast_findings
|
|
115
|
+
res["iac_findings"] = st.iac_findings
|
|
116
|
+
from core.finding_schema import normalize_all_findings
|
|
117
|
+
res["standardized_findings"] = normalize_all_findings(res)
|
|
118
|
+
res["remediation"] = st.remediation or {"items": [], "manifests": {}, "groups_total": 0, "groups_not_planned": 0}
|
|
119
|
+
res["evidence_store"] = st.evidence.to_list()
|
|
120
|
+
if res["source_status"].get("OSV", {}).get("state") in ("unavailable", "partial", "failed"):
|
|
121
|
+
res["limitations"].append(f"OSV was {res['source_status']['OSV']['state']}: vulnerability results are incomplete (see coverage).")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def finalize(st: ScanState, rt: Runtime, final: bool = False) -> None:
|
|
125
|
+
res = st.result
|
|
126
|
+
res["errors"] = [{k: v for k, v in e.items() if k != "trace"} for e in rt.errors]
|
|
127
|
+
res["timings"] = dict(rt.timings)
|
|
128
|
+
res["status"] = "completed" if not rt.errors else "completed_with_errors"
|
|
129
|
+
if "components" in res:
|
|
130
|
+
from reporting.view import coverage
|
|
131
|
+
res["coverage"] = coverage(res)
|
|
132
|
+
if "summary" in res:
|
|
133
|
+
res["summary"]["vulnerability_assessment"] = res["coverage"]["vulnerability"]["state"]
|
|
134
|
+
res["agent_trace"] = rt.trace()
|
|
135
|
+
res["agents"] = _agent_summary(rt)
|
|
136
|
+
if final:
|
|
137
|
+
res["total_seconds"] = round(time.time() - rt.t0, 1)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _agent_summary(rt: Runtime) -> list[dict]:
|
|
141
|
+
out = []
|
|
142
|
+
for a in AGENTS:
|
|
143
|
+
steps = [{"id": sid, "label": lab, "status": rt.status[sid], "seconds": rt.timings.get(sid)} for sid, ag, lab in STEPS if ag == a]
|
|
144
|
+
evs = [e for e in rt.events if e.agent == a]
|
|
145
|
+
out.append({"agent": a, "role": AGENT_ROLES[a], "steps": steps, "decisions": sum(e.kind == "decision" for e in evs),
|
|
146
|
+
"observations": sum(e.kind == "observation" for e in evs), "warnings": sum(e.kind == "warning" for e in evs)})
|
|
147
|
+
return out
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def cleanup(rt: Runtime, ws: Optional[Path], keep: bool, result: dict) -> None:
|
|
151
|
+
if rt.status["cleanup"] != "pending":
|
|
152
|
+
return
|
|
153
|
+
if ws is None:
|
|
154
|
+
rt.skip("cleanup", "no temporary workspace")
|
|
155
|
+
return
|
|
156
|
+
if keep:
|
|
157
|
+
rt.skip("cleanup", f"clone kept for inspection at {ws}")
|
|
158
|
+
return
|
|
159
|
+
rt.begin("cleanup", f"Deleting the temporary clone {ws}")
|
|
160
|
+
gone = gm.cleanup(ws)
|
|
161
|
+
if gone:
|
|
162
|
+
rt.done("cleanup", "workspace removed")
|
|
163
|
+
else:
|
|
164
|
+
rt.warn("cleanup", f"Could not delete {ws} (files in use); it will be removed by the next scan's start-up sweep.")
|
|
165
|
+
rt.done("cleanup", "workspace NOT fully removed")
|
|
166
|
+
if isinstance(result, dict) and result.get("workspace"):
|
|
167
|
+
result["workspace"]["removed"] = gone
|
|
File without changes
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Pipeline Agent engine: analyse every Dockerfile, compose file and CI definition found by Recon.
|
|
2
|
+
|
|
3
|
+
Returns findings (with stable ids), the images and actions the repository depends on (to become SBOM components), and per-file coverage.
|
|
4
|
+
Only files already discovered by ``core.repository_inspector`` are read, through its path-confined, size-capped ``safe_read_text``.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from core.repository_inspector import safe_read_text
|
|
13
|
+
from pipeline_analysis.ci_adapters import analyze_ci_pipeline
|
|
14
|
+
from pipeline_analysis.dockerfile import analyze_compose, analyze_dockerfile
|
|
15
|
+
from pipeline_analysis.models import PipelineFinding
|
|
16
|
+
|
|
17
|
+
SEV_ORDER = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_github_workflow(path: str) -> bool:
|
|
21
|
+
return bool(re.match(r"^(.*/)?\.github/workflows/[^/]+\.ya?ml$", path))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def analyze_repository(root: Path, dockerfiles: list[str], container_files: list[str], ci_files: list[str], scan_timestamp: str = "") -> dict[str, Any]:
|
|
25
|
+
findings: list[PipelineFinding] = []
|
|
26
|
+
images: list[dict] = []
|
|
27
|
+
actions: list[dict] = []
|
|
28
|
+
files: list[dict] = []
|
|
29
|
+
seen_ci: set[str] = set()
|
|
30
|
+
for rel in dockerfiles:
|
|
31
|
+
text = safe_read_text(root, rel)
|
|
32
|
+
if text is None:
|
|
33
|
+
files.append({"file": rel, "type": "Dockerfile", "status": "unreadable"})
|
|
34
|
+
continue
|
|
35
|
+
f, im = analyze_dockerfile(text, rel)
|
|
36
|
+
findings += f
|
|
37
|
+
images += im
|
|
38
|
+
files.append({"file": rel, "type": "Dockerfile", "status": "analysed", "findings": len(f), "images": len(im)})
|
|
39
|
+
for rel in container_files:
|
|
40
|
+
name = rel.rsplit("/", 1)[-1]
|
|
41
|
+
if not name.lower().startswith(("docker-compose", "compose")):
|
|
42
|
+
continue
|
|
43
|
+
text = safe_read_text(root, rel)
|
|
44
|
+
if text is None:
|
|
45
|
+
files.append({"file": rel, "type": "compose", "status": "unreadable"})
|
|
46
|
+
continue
|
|
47
|
+
f, im = analyze_compose(text, rel)
|
|
48
|
+
findings += f
|
|
49
|
+
images += im
|
|
50
|
+
files.append({"file": rel, "type": "compose", "status": "analysed", "findings": len(f), "images": len(im)})
|
|
51
|
+
docker_builds: list[dict] = []
|
|
52
|
+
for rel in ci_files:
|
|
53
|
+
if rel in seen_ci:
|
|
54
|
+
continue
|
|
55
|
+
seen_ci.add(rel)
|
|
56
|
+
if rel.endswith("/") or not re.search(r"\.(ya?ml|groovy)$|Jenkinsfile", rel, re.IGNORECASE):
|
|
57
|
+
continue
|
|
58
|
+
text = safe_read_text(root, rel)
|
|
59
|
+
if text is None:
|
|
60
|
+
files.append({"file": rel, "type": "CI", "status": "unreadable"})
|
|
61
|
+
continue
|
|
62
|
+
pipe_obj = analyze_ci_pipeline(text, rel)
|
|
63
|
+
findings += pipe_obj.findings
|
|
64
|
+
images += pipe_obj.container_images
|
|
65
|
+
actions += pipe_obj.external_dependencies
|
|
66
|
+
for db in pipe_obj.docker_builds:
|
|
67
|
+
docker_builds.append(db.__dict__ if hasattr(db, "__dict__") else db)
|
|
68
|
+
files.append({
|
|
69
|
+
"file": rel,
|
|
70
|
+
"type": f"{pipe_obj.platform} workflow",
|
|
71
|
+
"status": "analysed" if pipe_obj.parse_success else "parse_error",
|
|
72
|
+
"findings": len(pipe_obj.findings),
|
|
73
|
+
"actions": len(pipe_obj.external_dependencies),
|
|
74
|
+
"docker_builds": len(pipe_obj.docker_builds),
|
|
75
|
+
})
|
|
76
|
+
# stable ids, de-duplicated by (rule, file, line, subject), worst first
|
|
77
|
+
uniq: dict[tuple, PipelineFinding] = {}
|
|
78
|
+
for f in findings:
|
|
79
|
+
uniq.setdefault((f.rule_id, f.file, f.line, f.subject), f)
|
|
80
|
+
ordered = sorted(uniq.values(), key=lambda f: (SEV_ORDER.get(f.severity, 9), f.file, f.line, f.rule_id))
|
|
81
|
+
for n, f in enumerate(ordered, 1):
|
|
82
|
+
f.finding_id = f"PIPE-{n:03d}"
|
|
83
|
+
f.scan_timestamp = scan_timestamp
|
|
84
|
+
by_sev: dict[str, int] = {}
|
|
85
|
+
for f in ordered:
|
|
86
|
+
by_sev[f.severity] = by_sev.get(f.severity, 0) + 1
|
|
87
|
+
unpinned_actions = [a for a in actions if a.get("kind") == "action" and not a.get("pinned")]
|
|
88
|
+
return {"findings": [f.model_dump() for f in ordered], "images": images, "actions": actions, "files": files, "docker_builds": docker_builds,
|
|
89
|
+
"summary": {"files_analysed": sum(1 for x in files if x["status"] == "analysed"), "findings": len(ordered), "by_severity": by_sev, "images": len(images), "actions": len(actions),
|
|
90
|
+
"actions_unpinned": len(unpinned_actions), "images_unpinned": sum(1 for i in images if not i.get("digest")), "docker_builds": len(docker_builds)}}
|