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.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,1022 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Software Supply Chain Guardian - Change Analyzer (Person 2: Suspicious Change Investigator)
4
+ Root-level deterministic orchestration engine and unified CLI.
5
+
6
+ Detects malicious, suspicious, and unauthorized software supply chain changes
7
+ that conventional vulnerability databases (NVD, CVE, OSV) do not identify:
8
+ 1. Git diff manifest and lockfile changes (added, removed, modified, floating versions).
9
+ 2. Manifest and lockfile inconsistencies.
10
+ 3. Security-sensitive source file modifications.
11
+ 4. Static lifecycle script threats (remote execution, eval/obfuscation, credential access, env exfiltration).
12
+ 5. Registry and dependency source anomalies (insecure HTTP, custom mirrors, disabled TLS, committed tokens).
13
+ 6. CI/CD workflow vulnerabilities and pipeline tampering (unpinned actions, script injection, untrusted triggers).
14
+ 7. Container build security (unpinned base images, build-time downloads, root user).
15
+ 8. Typosquatting and package masquerading heuristics.
16
+
17
+ Strictly distinguishes OBSERVED_CHANGE from HEURISTIC_FLAG.
18
+ Distinguishes INTRODUCED_IN_RANGE from PRE_EXISTING findings.
19
+ Never executes untrusted code.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ import re
27
+ import sys
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+ from typing import Any, Dict, List, Optional, Set, Tuple
31
+
32
+ # Ensure src is on sys.path
33
+ _ROOT = Path(__file__).resolve().parent
34
+ _SRC = _ROOT / "src"
35
+ if str(_SRC) not in sys.path:
36
+ sys.path.insert(0, str(_SRC))
37
+
38
+ from core import git_manager as gm
39
+ from suspicious_changes.manifest_diff_detector import inspect_git_diff_range
40
+ from suspicious_changes.registry_detector import (
41
+ inspect_registry_configurations,
42
+ inspect_manifest_dependency_sources,
43
+ inspect_lockfile_sources,
44
+ )
45
+ from suspicious_changes.lifecycle_script_detector import (
46
+ inspect_lifecycle_scripts_text,
47
+ inspect_lockfile_install_scripts,
48
+ )
49
+ from suspicious_changes.popular_packages import POPULAR
50
+ from suspicious_changes.typosquatting_detector import candidate_matches
51
+ from suspicious_changes.change_correlation import CITATIONS, correlate_suspicious_changes
52
+ from agents.suspicious_change_agent import SuspiciousChangeAgent
53
+ from pipeline_analysis.ci import analyze_github_workflow, analyze_generic_ci
54
+ from pipeline_analysis.dockerfile import analyze_dockerfile, analyze_compose
55
+
56
+
57
+ class CIWorkflowAdapter:
58
+ """Adapter for inspecting multi-ecosystem CI/CD pipelines statically."""
59
+
60
+ SUPPORTED_PIPELINES = {
61
+ ".github/workflows": "github_actions",
62
+ ".gitlab-ci.yml": "gitlab_ci",
63
+ "Jenkinsfile": "jenkins",
64
+ ".circleci/config.yml": "circleci",
65
+ "azure-pipelines.yml": "azure_pipelines",
66
+ }
67
+
68
+ @classmethod
69
+ def inspect(cls, file_path: Path, repo_root: Path) -> Tuple[List[Dict[str, Any]], str]:
70
+ rel_str = str(file_path.relative_to(repo_root)).replace("\\", "/")
71
+ try:
72
+ content = file_path.read_text(encoding="utf-8", errors="replace")
73
+ except OSError:
74
+ return [], ""
75
+
76
+ if ".github/workflows" in rel_str and (rel_str.endswith(".yml") or rel_str.endswith(".yaml")):
77
+ findings, _ = analyze_github_workflow(content, rel_str)
78
+ return [f.model_dump() for f in findings], "GitHub Actions"
79
+ elif any(sig in rel_str for sig in (".gitlab-ci.yml", "Jenkinsfile", ".circleci", "azure-pipelines")):
80
+ findings, _ = analyze_generic_ci(content, rel_str)
81
+ return [f.model_dump() for f in findings], "Generic CI"
82
+ return [], ""
83
+
84
+
85
+ class ChangeAnalyzer:
86
+ """
87
+ Deterministic detection engine coordinating Git diff investigation,
88
+ lifecycle script inspection, registry analysis, CI/CD audits, and typosquatting.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ repo_dir: Path,
94
+ base_commit: str = "HEAD~1",
95
+ head_commit: str = "HEAD",
96
+ target_dir: Optional[Path] = None,
97
+ enable_ai: bool = True,
98
+ ):
99
+ self.repo_dir = repo_dir.resolve()
100
+ self.base_commit = base_commit
101
+ self.head_commit = head_commit
102
+ self.target_dir = (target_dir or self.repo_dir).resolve()
103
+ self.enable_ai = enable_ai
104
+ self.scan_timestamp = datetime.now(timezone.utc).isoformat()
105
+
106
+ # Cache git metadata
107
+ self.is_git = (self.repo_dir / ".git").exists() or gm.commit_exists(self.repo_dir, "HEAD")
108
+ self.base_sha = None
109
+ self.head_sha = None
110
+ self.head_info = {}
111
+ self.changed_files: Set[str] = set()
112
+
113
+ if self.is_git:
114
+ try:
115
+ res = gm.run_git(["rev-parse", "--verify", f"{self.head_commit}^{{commit}}"], cwd=self.repo_dir, check=False)
116
+ if res.returncode == 0:
117
+ self.head_sha = res.stdout.strip()
118
+ self.head_info = gm.commit_info(self.repo_dir, self.head_sha)
119
+ except Exception:
120
+ self.head_sha = None
121
+
122
+ try:
123
+ res = gm.run_git(["rev-parse", "--verify", f"{self.base_commit}^{{commit}}"], cwd=self.repo_dir, check=False)
124
+ if res.returncode == 0:
125
+ self.base_sha = res.stdout.strip()
126
+ except Exception:
127
+ self.base_sha = None
128
+
129
+ if self.base_sha and self.head_sha:
130
+ try:
131
+ diff_pairs = gm.changed_files(self.repo_dir, self.base_sha, self.head_sha)
132
+ self.changed_files = {p for _, p in diff_pairs}
133
+ except Exception:
134
+ self.changed_files = set()
135
+
136
+ def _determine_origin(self, file_rel_path: str) -> str:
137
+ """Distinguish whether a finding was introduced in the commit range or was pre-existing."""
138
+ normalized = file_rel_path.replace("\\", "/")
139
+ if not self.changed_files:
140
+ return "PRE_EXISTING"
141
+ if normalized in self.changed_files or any(normalized.endswith(c) for c in self.changed_files):
142
+ return "INTRODUCED_IN_RANGE"
143
+ return "PRE_EXISTING"
144
+
145
+ def run_investigation(self) -> Dict[str, Any]:
146
+ """Execute full deterministic investigation pipeline."""
147
+ raw_findings: List[Dict[str, Any]] = []
148
+
149
+ # 1. Git Diff Investigation (Range: base -> head)
150
+ if self.base_sha and self.head_sha:
151
+ diff_findings = inspect_git_diff_range(self.repo_dir, self.base_sha, self.head_sha)
152
+ raw_findings.extend(diff_findings)
153
+
154
+ # 2. Registry & Source Configurations
155
+ reg_findings = inspect_registry_configurations(self.repo_dir)
156
+ for rf in reg_findings:
157
+ rf["change_origin"] = self._determine_origin(rf["affected_file"])
158
+ if self.head_info and rf["change_origin"] == "INTRODUCED_IN_RANGE":
159
+ rf["commit_reference"] = self.head_info
160
+ raw_findings.extend(reg_findings)
161
+
162
+ # 3. Target Manifests and Lockfiles (both in repo root and sub-targets like nodegoat)
163
+ manifest_files = list(self.repo_dir.glob("**/package.json"))
164
+ lockfiles = list(self.repo_dir.glob("**/package-lock.json"))
165
+
166
+ for m_file in manifest_files:
167
+ if "node_modules" in str(m_file) or ".venv" in str(m_file):
168
+ continue
169
+ rel_path = str(m_file.relative_to(self.repo_dir)).replace("\\", "/")
170
+ origin = self._determine_origin(rel_path)
171
+ commit_ref = self.head_info if origin == "INTRODUCED_IN_RANGE" else {}
172
+
173
+ try:
174
+ content = m_file.read_text(encoding="utf-8", errors="replace")
175
+ except OSError:
176
+ continue
177
+
178
+ try:
179
+ manifest_data = json.loads(content)
180
+ except Exception:
181
+ manifest_data = {}
182
+
183
+ # Manifest source inspection (Git URLs, tarballs)
184
+ if manifest_data:
185
+ src_findings = inspect_manifest_dependency_sources(manifest_data, rel_path)
186
+ for sf in src_findings:
187
+ sf["change_origin"] = origin
188
+ sf["commit_reference"] = commit_ref
189
+ raw_findings.extend(src_findings)
190
+
191
+ # Check for floating versions in dependencies
192
+ lines = content.splitlines()
193
+ for dep_sec in ("dependencies", "devDependencies"):
194
+ deps = manifest_data.get(dep_sec, {})
195
+ if isinstance(deps, dict):
196
+ for pkg, spec in deps.items():
197
+ if isinstance(spec, str):
198
+ clean_s = spec.strip().lower()
199
+ if clean_s in ("latest", "*") or (clean_s.startswith((">=", ">")) and "<" not in clean_s):
200
+ line_no = next((i for i, l in enumerate(lines, 1) if f'"{pkg}"' in l), 1)
201
+ raw_findings.append({
202
+ "id": f"SUSP-DEP-FLOATING-{pkg.upper().replace('@', '').replace('/', '_')}",
203
+ "category": "Dependency Change",
204
+ "title": f"Floating Dependency Version Constraint for '{pkg}'",
205
+ "severity": "HIGH",
206
+ "confidence": "CONFIRMED",
207
+ "status": "OBSERVED",
208
+ "affected_file": rel_path,
209
+ "line_number": line_no,
210
+ "commit_reference": commit_ref,
211
+ "change_origin": origin,
212
+ "evidence_type": "HEURISTIC_FLAG",
213
+ "evidence": f'"{pkg}": "{spec}",',
214
+ "technical_explanation": (
215
+ f"Package '{pkg}' declares a floating '{spec}' version constraint in '{dep_sec}'. "
216
+ "Floating constraints allow automated adoption of upstream breaking or malicious updates without manifest review."
217
+ ),
218
+ "potential_impact": "Automatic installation of unvetted new releases or malicious package versions.",
219
+ "recommended_action": f"Pin '{pkg}' to a specific immutable semantic version.",
220
+ "references": ["https://docs.npmjs.com/about-semantic-versioning"]
221
+ })
222
+
223
+ # Static Lifecycle Script inspection
224
+ script_findings = inspect_lifecycle_scripts_text(
225
+ content,
226
+ file_path=rel_path,
227
+ commit_reference=commit_ref,
228
+ change_origin=origin
229
+ )
230
+ raw_findings.extend(script_findings)
231
+
232
+ # Typosquatting / Name Similarity inspection on dependencies
233
+ typo_findings = self._inspect_manifest_typosquatting(content, rel_path, origin, commit_ref)
234
+ raw_findings.extend(typo_findings)
235
+
236
+ for l_file in lockfiles:
237
+ if "node_modules" in str(l_file) or ".venv" in str(l_file):
238
+ continue
239
+ rel_path = str(l_file.relative_to(self.repo_dir)).replace("\\", "/")
240
+ origin = self._determine_origin(rel_path)
241
+ commit_ref = self.head_info if origin == "INTRODUCED_IN_RANGE" else {}
242
+
243
+ try:
244
+ l_content = l_file.read_text(encoding="utf-8", errors="replace")
245
+ except OSError:
246
+ continue
247
+
248
+ try:
249
+ lock_data = json.loads(l_content)
250
+ except Exception:
251
+ lock_data = {}
252
+
253
+ # Lockfile resolved URL inspection
254
+ if lock_data:
255
+ res_findings = inspect_lockfile_sources(lock_data, rel_path)
256
+ for rf in res_findings:
257
+ rf["change_origin"] = origin
258
+ rf["commit_reference"] = commit_ref
259
+ raw_findings.extend(res_findings)
260
+
261
+ # Lockfile install scripts (hasInstallScript: true)
262
+ l_script_findings = inspect_lockfile_install_scripts(
263
+ l_content,
264
+ file_path=rel_path,
265
+ commit_reference=commit_ref,
266
+ change_origin=origin
267
+ )
268
+ raw_findings.extend(l_script_findings)
269
+
270
+ # Typosquatting on lockfile dependencies
271
+ l_typo_findings = self._inspect_lockfile_typosquatting(l_content, rel_path, origin, commit_ref)
272
+ raw_findings.extend(l_typo_findings)
273
+
274
+ # 4. CI/CD Workflows
275
+ workflow_files = list(self.repo_dir.glob("**/.github/workflows/*.yml")) + list(
276
+ self.repo_dir.glob("**/.github/workflows/*.yaml")
277
+ )
278
+ for w_file in workflow_files:
279
+ if "node_modules" in str(w_file) or ".venv" in str(w_file):
280
+ continue
281
+ rel_path = str(w_file.relative_to(self.repo_dir)).replace("\\", "/")
282
+ origin = self._determine_origin(rel_path)
283
+ commit_ref = self.head_info if origin == "INTRODUCED_IN_RANGE" else {}
284
+ wf_slug = w_file.stem.upper().replace('.', '_').replace('-', '_')
285
+
286
+ ci_findings, _ = CIWorkflowAdapter.inspect(w_file, self.repo_dir)
287
+ for cif in ci_findings:
288
+ # Convert PipelineFinding structure to standard finding schema
289
+ raw_findings.append({
290
+ "id": f"SUSP-CICD-{cif.get('rule_id', 'GHA')}-{wf_slug}-L{cif.get('line', 1)}",
291
+ "category": "Docker & CI/CD",
292
+ "title": cif.get("title", "CI/CD Security Finding"),
293
+ "severity": cif.get("severity", "MEDIUM"),
294
+ "confidence": "CONFIRMED" if cif.get("evidence_strength") == "high" else "MEDIUM",
295
+ "status": "OBSERVED",
296
+ "affected_file": rel_path,
297
+ "line_number": cif.get("line", 1),
298
+ "commit_reference": commit_ref,
299
+ "change_origin": origin,
300
+ "evidence_type": "HEURISTIC_FLAG",
301
+ "evidence": cif.get("snippet", ""),
302
+ "technical_explanation": cif.get("why", ""),
303
+ "potential_impact": cif.get("why", ""),
304
+ "recommended_action": cif.get("remediation", ""),
305
+ "references": cif.get("references", []),
306
+ })
307
+
308
+ # 5. Dockerfiles & Compose files
309
+ docker_files = [
310
+ f for f in list(self.repo_dir.glob("**/Dockerfile*")) + list(
311
+ self.repo_dir.glob("**/docker-compose*.yml")
312
+ ) + list(self.repo_dir.glob("**/docker-compose*.yaml"))
313
+ if f.suffix.lower() not in (".py", ".pyc", ".js", ".ts", ".json", ".md", ".txt")
314
+ and not f.name.endswith(".py")
315
+ ]
316
+
317
+ for d_file in docker_files:
318
+ if "node_modules" in str(d_file) or ".venv" in str(d_file):
319
+ continue
320
+ rel_path = str(d_file.relative_to(self.repo_dir)).replace("\\", "/")
321
+ origin = self._determine_origin(rel_path)
322
+ commit_ref = self.head_info if origin == "INTRODUCED_IN_RANGE" else {}
323
+
324
+ try:
325
+ d_content = d_file.read_text(encoding="utf-8", errors="replace")
326
+ except OSError:
327
+ continue
328
+
329
+ if "compose" in d_file.name.lower():
330
+ df_findings, _ = analyze_compose(d_content, rel_path)
331
+ else:
332
+ df_findings, _ = analyze_dockerfile(d_content, rel_path)
333
+
334
+ for dff in df_findings:
335
+ raw_findings.append({
336
+ "id": f"SUSP-DOCKER-{dff.rule_id}-L{dff.line}",
337
+ "category": "Docker & CI/CD",
338
+ "title": dff.title,
339
+ "severity": dff.severity,
340
+ "confidence": "CONFIRMED" if dff.evidence_strength == "high" else "MEDIUM",
341
+ "status": "OBSERVED",
342
+ "affected_file": rel_path,
343
+ "line_number": dff.line,
344
+ "commit_reference": commit_ref,
345
+ "change_origin": origin,
346
+ "evidence_type": "HEURISTIC_FLAG",
347
+ "evidence": dff.snippet,
348
+ "technical_explanation": dff.why,
349
+ "potential_impact": dff.why,
350
+ "recommended_action": dff.remediation,
351
+ "references": dff.references,
352
+ })
353
+
354
+ # Deduplicate and normalize findings
355
+ unified_findings = self._normalize_and_deduplicate(raw_findings)
356
+ metrics = self._calculate_metrics(unified_findings)
357
+
358
+ # Correlate findings into multi-vector attack scenarios (Phase 2)
359
+ correlation_result = correlate_suspicious_changes(unified_findings)
360
+
361
+ # AI-Assisted Investigation Agent (Phase 3)
362
+ ai_investigations = []
363
+ if self.enable_ai:
364
+ try:
365
+ agent = SuspiciousChangeAgent()
366
+ ai_investigations = agent.investigate_all(
367
+ findings=unified_findings,
368
+ correlated_scenarios=correlation_result.get("scenarios", []),
369
+ repo_dir=self.repo_dir,
370
+ base_commit=self.base_sha or self.base_commit,
371
+ head_commit=self.head_sha or self.head_commit
372
+ )
373
+ except Exception as e:
374
+ ai_investigations = []
375
+
376
+ return {
377
+ "analysis_type": "Suspicious Supply Chain Change Detection",
378
+ "timestamp": self.scan_timestamp,
379
+ "target": str(self.target_dir.name or "Repository Root"),
380
+ "repository": str(self.repo_dir),
381
+ "base_commit": self.base_sha or self.base_commit,
382
+ "head_commit": self.head_sha or self.head_commit,
383
+ "metrics": metrics,
384
+ "findings": unified_findings,
385
+ "correlated_scenarios": correlation_result.get("scenarios", []),
386
+ "correlation_metrics": correlation_result.get("metrics", {}),
387
+ "ai_investigations": ai_investigations,
388
+ }
389
+
390
+ def _inspect_manifest_typosquatting(
391
+ self,
392
+ content: str,
393
+ rel_path: str,
394
+ origin: str,
395
+ commit_ref: Dict[str, str]
396
+ ) -> List[Dict[str, Any]]:
397
+ """Static similarity check on manifest dependencies against popular packages."""
398
+ findings = []
399
+ try:
400
+ data = json.loads(content)
401
+ except Exception:
402
+ return []
403
+
404
+ npm_refs = POPULAR.get("npm", [])
405
+ lines = content.splitlines()
406
+ seen_pairs = set()
407
+
408
+ for sec in ("dependencies", "devDependencies"):
409
+ deps = data.get(sec, {})
410
+ if not isinstance(deps, dict):
411
+ continue
412
+ for pkg_name in deps.keys():
413
+ matches = candidate_matches("npm", pkg_name, npm_refs)
414
+ for m in matches:
415
+ ref = m.get("ref", "")
416
+ pair_key = tuple(sorted([pkg_name.lower(), ref.lower()]))
417
+ if pair_key in seen_pairs:
418
+ continue
419
+ seen_pairs.add(pair_key)
420
+
421
+ is_conv = m.get("is_ecosystem_convention", False)
422
+ both_ref = m.get("both_in_reference", False)
423
+ is_deceptive = m.get("is_deceptive", False)
424
+
425
+ # Distinguish legitimate companion packages from potential impersonation:
426
+ # If both are in the reference catalog and match by ecosystem convention without deceptive indicators:
427
+ if both_ref and is_conv and not is_deceptive:
428
+ continue
429
+
430
+ line_no = next((i for i, l in enumerate(lines, 1) if f'"{pkg_name}"' in l), 1)
431
+ sim = m.get("similarity", m.get("sim", 0))
432
+ dist = m.get("distance", m.get("dist", 99))
433
+ tech = ", ".join(m.get("techniques", []))
434
+
435
+ # Calibrate severity: deceptive indicators are HIGH/MEDIUM;
436
+ # ecosystem conventions (e.g. implementation affix like -nodejs) are LOW signals.
437
+ if is_deceptive:
438
+ sev = "HIGH" if dist <= 1 else "MEDIUM"
439
+ conf = "MEDIUM"
440
+ elif is_conv:
441
+ sev = "LOW"
442
+ conf = "LOW"
443
+ else:
444
+ sev = "MEDIUM" if sim >= 85 else "LOW"
445
+ conf = "LOW"
446
+
447
+ findings.append({
448
+ "id": f"SUSP-TYPO-{pkg_name.upper().replace('@', '').replace('/', '_')}",
449
+ "category": "Typosquatting",
450
+ "title": f"Package '{pkg_name}' Shares Name Similarity with '{ref}'",
451
+ "severity": sev,
452
+ "confidence": conf,
453
+ "status": "SUSPECTED",
454
+ "affected_file": rel_path,
455
+ "line_number": line_no,
456
+ "commit_reference": commit_ref,
457
+ "change_origin": origin,
458
+ "evidence_type": "HEURISTIC_FLAG",
459
+ "evidence": f'Package "{pkg_name}" similar to popular "{ref}" (similarity: {sim}%, edit distance: {dist})',
460
+ "technical_explanation": (
461
+ f"Package '{pkg_name}' has an edit distance of {dist} ({sim}% similarity) relative to '{ref}'. "
462
+ f"Techniques identified: {tech}. Similarity is an indicator requiring contextual disambiguation."
463
+ ),
464
+ "potential_impact": "Developers or automated build tools may install unvetted package variants.",
465
+ "recommended_action": f"Verify whether '{pkg_name}' is an intended implementation variant or should be replaced with canonical '{ref}'.",
466
+ "references": ["https://blog.reversinglabs.com/blog/typosquatting-in-open-source"]
467
+ })
468
+ return findings
469
+
470
+ def _inspect_lockfile_typosquatting(
471
+ self,
472
+ content: str,
473
+ rel_path: str,
474
+ origin: str,
475
+ commit_ref: Dict[str, str]
476
+ ) -> List[Dict[str, Any]]:
477
+ """Static similarity check on lockfile dependencies (distinguishing companion packages and preventing reciprocal duplicates)."""
478
+ findings = []
479
+ try:
480
+ data = json.loads(content)
481
+ except Exception:
482
+ return []
483
+
484
+ npm_refs = POPULAR.get("npm", [])
485
+ packages = data.get("packages", {})
486
+ if not isinstance(packages, dict):
487
+ return []
488
+
489
+ # Check select lockfile packages to avoid exponential combinations
490
+ seen_names = set()
491
+ seen_pairs = set()
492
+ for pkg_path in packages.keys():
493
+ if not pkg_path:
494
+ continue
495
+ pkg_name = pkg_path.split("node_modules/")[-1] if "node_modules/" in pkg_path else pkg_path
496
+ if pkg_name in seen_names or pkg_name.startswith("@types/"):
497
+ continue
498
+ seen_names.add(pkg_name)
499
+
500
+ matches = candidate_matches("npm", pkg_name, npm_refs)
501
+ for m in matches:
502
+ ref = m.get("ref", "")
503
+ pair_key = tuple(sorted([pkg_name.lower(), ref.lower()]))
504
+ if pair_key in seen_pairs:
505
+ continue
506
+ seen_pairs.add(pair_key)
507
+
508
+ is_conv = m.get("is_ecosystem_convention", False)
509
+ both_ref = m.get("both_in_reference", False)
510
+ is_deceptive = m.get("is_deceptive", False)
511
+
512
+ # Established companion packages in reference catalog (e.g. safe-buffer / safer-buffer, through / through2)
513
+ if both_ref and is_conv and not is_deceptive:
514
+ continue
515
+
516
+ # In lockfiles, suppress transitive conventions (version forks, companion packages)
517
+ if is_conv and not is_deceptive:
518
+ continue
519
+
520
+ dist = m.get("distance", m.get("dist", 99))
521
+ sim = m.get("similarity", m.get("sim", 0))
522
+ tech = ", ".join(m.get("techniques", []))
523
+
524
+ if dist <= 2 or sim >= 85:
525
+ sev = "MEDIUM" if is_deceptive else "LOW"
526
+ findings.append({
527
+ "id": f"SUSP-TYPO-LOCK-{pkg_name.upper().replace('@', '').replace('/', '_')}",
528
+ "category": "Typosquatting",
529
+ "title": f"Transitive Dependency '{pkg_name}' Similar to '{ref}'",
530
+ "severity": sev,
531
+ "confidence": "LOW",
532
+ "status": "SUSPECTED",
533
+ "affected_file": rel_path,
534
+ "line_number": 1,
535
+ "commit_reference": commit_ref,
536
+ "change_origin": origin,
537
+ "evidence_type": "HEURISTIC_FLAG",
538
+ "evidence": f'Package "{pkg_name}" has edit distance {dist} from "{ref}"',
539
+ "technical_explanation": (
540
+ f"Lockfile package '{pkg_name}' shares similarity with '{ref}' ({tech}). "
541
+ "Transitive similarity is flagged for dependency graph review."
542
+ ),
543
+ "potential_impact": "Transitive dependency substitution or masquerading.",
544
+ "recommended_action": f"Verify supply chain path introducing '{pkg_name}'.",
545
+ "references": []
546
+ })
547
+ return findings
548
+
549
+ def _normalize_and_deduplicate(self, findings: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
550
+ """Ensure consistent schemas and prevent duplicate findings."""
551
+ seen_keys = set()
552
+ normalized: List[Dict[str, Any]] = []
553
+
554
+ sev_rank = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4}
555
+
556
+ for f in findings:
557
+ # Generate deduplication key
558
+ file_part = f.get("affected_file", "")
559
+ evidence_part = f.get("evidence", "")[:80]
560
+ cat_part = f.get("category", "")
561
+ key = (file_part, cat_part, f.get("line_number", 0), evidence_part)
562
+
563
+ if key in seen_keys:
564
+ continue
565
+ seen_keys.add(key)
566
+
567
+ # Ensure backward-compatible fields
568
+ explanation = f.get("explanation") or f.get("technical_explanation", "")
569
+ title = f.get("title") or f.get("id", "Suspicious Signal")
570
+
571
+ # Normalize evidence_type and commit_reference strictly:
572
+ orig = f.get("change_origin", "PRE_EXISTING")
573
+ ev_type = f.get("evidence_type", "HEURISTIC_FLAG")
574
+ commit_ref = f.get("commit_reference") or {}
575
+
576
+ # Strict Invariant: OBSERVED_CHANGE requires INTRODUCED_IN_RANGE and a valid commit SHA
577
+ if orig == "PRE_EXISTING":
578
+ ev_type = "HEURISTIC_FLAG"
579
+ commit_ref = {}
580
+ elif ev_type == "OBSERVED_CHANGE" and not commit_ref.get("sha"):
581
+ ev_type = "HEURISTIC_FLAG"
582
+
583
+ # Typosquatting confidence calibration: similarity is an indicator, never confirmed malice
584
+ conf = f.get("confidence", "MEDIUM").upper()
585
+ stat = f.get("status", "OBSERVED")
586
+ cat = f.get("category", "General")
587
+ if cat == "Typosquatting":
588
+ stat = "SUSPECTED"
589
+ if conf in ("CONFIRMED", "HIGH"):
590
+ conf = "MEDIUM"
591
+
592
+ entry = {
593
+ "id": f.get("id", f"SUSP-{len(normalized)+1:03d}"),
594
+ "detection_scope": "Non-CVE Risk",
595
+ "category": cat,
596
+ "title": title,
597
+ "severity": f.get("severity", "MEDIUM").upper(),
598
+ "confidence": conf,
599
+ "status": stat,
600
+ "affected_file": file_part,
601
+ "line_number": f.get("line_number", 1),
602
+ "commit_reference": commit_ref,
603
+ "change_origin": orig,
604
+ "evidence_type": ev_type,
605
+ "evidence": f.get("evidence", ""),
606
+ "explanation": explanation,
607
+ "technical_explanation": explanation,
608
+ "potential_impact": f.get("potential_impact", ""),
609
+ "recommended_action": f.get("recommended_action", ""),
610
+ "references": f.get("references", []),
611
+ }
612
+ normalized.append(entry)
613
+
614
+ # Sort by severity then file
615
+ normalized.sort(key=lambda x: (sev_rank.get(x["severity"], 9), x["affected_file"], x["line_number"]))
616
+ return normalized
617
+
618
+ def _calculate_metrics(self, findings: List[Dict[str, Any]]) -> Dict[str, Any]:
619
+ """Aggregate counts across category, severity, confidence, evidence type, and origin."""
620
+ category_counts: Dict[str, int] = {}
621
+ severity_counts: Dict[str, int] = {}
622
+ confidence_counts: Dict[str, int] = {}
623
+ evidence_type_counts: Dict[str, int] = {}
624
+ origin_counts: Dict[str, int] = {}
625
+
626
+ for f in findings:
627
+ cat = f.get("category", "Other")
628
+ sev = f.get("severity", "MEDIUM")
629
+ conf = f.get("confidence", "MEDIUM")
630
+ ev_type = f.get("evidence_type", "HEURISTIC_FLAG")
631
+ orig = f.get("change_origin", "PRE_EXISTING")
632
+
633
+ category_counts[cat] = category_counts.get(cat, 0) + 1
634
+ severity_counts[sev] = severity_counts.get(sev, 0) + 1
635
+ confidence_counts[conf] = confidence_counts.get(conf, 0) + 1
636
+ evidence_type_counts[ev_type] = evidence_type_counts.get(ev_type, 0) + 1
637
+ origin_counts[orig] = origin_counts.get(orig, 0) + 1
638
+
639
+ return {
640
+ "total_findings": len(findings),
641
+ "category_counts": category_counts,
642
+ "severity_counts": severity_counts,
643
+ "confidence_counts": confidence_counts,
644
+ "evidence_type_counts": evidence_type_counts,
645
+ "origin_counts": origin_counts,
646
+ }
647
+
648
+
649
+ def format_summary_table(report: Dict[str, Any]) -> str:
650
+ """Generate human-readable console summary."""
651
+ metrics = report.get("metrics", {})
652
+ findings = report.get("findings", [])
653
+
654
+ lines = [
655
+ "=" * 80,
656
+ " GUARDIAN: SUSPICIOUS CHANGE INVESTIGATOR (PERSON 2 - PHASE 1)",
657
+ "=" * 80,
658
+ f" Target Repository: {report.get('repository')}",
659
+ f" Commit Range: {str(report.get('base_commit'))[:10]} -> {str(report.get('head_commit'))[:10]}",
660
+ f" Total Findings: {metrics.get('total_findings', 0)}",
661
+ f" Evidence Types: OBSERVED_CHANGE: {metrics.get('evidence_type_counts', {}).get('OBSERVED_CHANGE', 0)} | "
662
+ f"HEURISTIC_FLAG: {metrics.get('evidence_type_counts', {}).get('HEURISTIC_FLAG', 0)}",
663
+ f" Change Origin: INTRODUCED_IN_RANGE: {metrics.get('origin_counts', {}).get('INTRODUCED_IN_RANGE', 0)} | "
664
+ f"PRE_EXISTING: {metrics.get('origin_counts', {}).get('PRE_EXISTING', 0)}",
665
+ "-" * 80,
666
+ " Severity Breakdown:",
667
+ ]
668
+
669
+ for sev, count in sorted(metrics.get("severity_counts", {}).items()):
670
+ lines.append(f" * {sev:<10}: {count}")
671
+
672
+ lines.append("-" * 80)
673
+ lines.append(" Category Breakdown:")
674
+ for cat, count in sorted(metrics.get("category_counts", {}).items()):
675
+ lines.append(f" * {cat:<22}: {count}")
676
+
677
+ lines.append("=" * 80)
678
+ lines.append(f"{'SEVERITY':<10} | {'CATEGORY':<20} | {'FILE:LINE':<35} | {'EVIDENCE TYPE'}")
679
+ lines.append("-" * 80)
680
+
681
+ for f in findings[:25]:
682
+ loc = f"{f['affected_file']}:{f['line_number']}"
683
+ if len(loc) > 35:
684
+ loc = "..." + loc[-32:]
685
+ lines.append(
686
+ f"{f['severity']:<10} | {f['category']:<20} | {loc:<35} | {f['evidence_type']}"
687
+ )
688
+
689
+ if len(findings) > 25:
690
+ lines.append(f"... and {len(findings) - 25} more findings (see JSON output).")
691
+
692
+ scenarios = report.get("correlated_scenarios", [])
693
+ if scenarios:
694
+ lines.append("=" * 80)
695
+ lines.append(" CORRELATED ATTACK SCENARIOS (PHASE 2 ENGINE)")
696
+ lines.append("=" * 80)
697
+ lines.append(f"{'SEVERITY':<10} | {'CONFIDENCE':<10} | {'SCENARIO NAME'}")
698
+ lines.append("-" * 80)
699
+ for s in scenarios:
700
+ lines.append(f"{s['severity']:<10} | {s['correlation_confidence']:<10} | {s['scenario_name']}")
701
+ lines.append(f" -> Attack: {s.get('attack_technique')}")
702
+ lines.append(f" -> Primary: {', '.join(s.get('primary_finding_ids', []))}")
703
+ if s.get("contradicting_evidence"):
704
+ lines.append(f" -> Mitigating Factor: {s['contradicting_evidence'][0].get('factor')}")
705
+ lines.append("-" * 80)
706
+
707
+ ai_invs = report.get("ai_investigations", [])
708
+ if ai_invs:
709
+ lines.append("=" * 80)
710
+ lines.append(" AI INVESTIGATION VERDICTS & EVIDENCE GROUNDING (PHASE 3 LANGGRAPH AGENT)")
711
+ lines.append("=" * 80)
712
+ lines.append(f"{'VERDICT':<30} | {'CONF':<6} | {'FINDING / TARGET':<35}")
713
+ lines.append("-" * 80)
714
+ for inv in ai_invs:
715
+ loc = f"{inv.get('finding_id', '')} ({inv.get('affected_file', '')})"
716
+ if len(loc) > 35:
717
+ loc = loc[:32] + "..."
718
+ lines.append(f"{inv['verdict']:<30} | {inv['confidence']:<6} | {loc:<35}")
719
+ lines.append(f" -> Rationale: {inv['rationale'][:160]}")
720
+ if inv.get("contradicting_evidence"):
721
+ lines.append(f" -> Mitigating Factor: {inv['contradicting_evidence'][0].get('factor', '')}")
722
+ if inv.get("attack_scenario"):
723
+ lines.append(f" -> Suspected Attack: {inv['attack_scenario'][:140]}")
724
+ lines.append(f" -> Engine: {inv.get('planner', 'deterministic')} | Steps: {len(inv.get('investigation_steps', []))}")
725
+ lines.append("-" * 80)
726
+
727
+ lines.append("=" * 80)
728
+ return "\n".join(lines)
729
+
730
+
731
+ def generate_markdown_report(report: Dict[str, Any], output_path: Path) -> str:
732
+ """Generate the formal Phase 3 investigation report: GIT_DIFF_INVESTIGATION.md."""
733
+ metrics = report.get("metrics", {})
734
+ findings = report.get("findings", [])
735
+ scenarios = report.get("correlated_scenarios", [])
736
+ ai_invs = report.get("ai_investigations", [])
737
+
738
+ by_cat: Dict[str, List[Dict[str, Any]]] = {}
739
+ for f in findings:
740
+ by_cat.setdefault(f.get("category", "General"), []).append(f)
741
+
742
+ md = []
743
+ md.append("# Software Supply Chain Guardian: Repository & Change Investigation Report")
744
+ md.append(f"**Target Repository:** `{report.get('repository')}` ")
745
+ md.append(f"**Analysis Timestamp:** `{report.get('timestamp')}` ")
746
+ md.append(f"**Commit Range Investigated:** `{report.get('base_commit', 'N/A')[:10]}` $\\to$ `{report.get('head_commit', 'N/A')[:10]}` ")
747
+ md.append(f"**Total Findings:** {metrics.get('total_findings', 0)} ({metrics.get('origin_counts', {}).get('INTRODUCED_IN_RANGE', 0)} introduced in range, {metrics.get('origin_counts', {}).get('PRE_EXISTING', 0)} pre-existing) ")
748
+ md.append(f"**Correlated Multi-Vector Scenarios:** {len(scenarios)} ")
749
+ md.append(f"**AI Investigations Conducted:** {len(ai_invs)} \n")
750
+ md.append("---\n")
751
+
752
+ # 1. Executive Summary
753
+ md.append("## 1. Executive Summary")
754
+ md.append(
755
+ "Software Supply Chain Guardian implements an evidence-driven, tool-using investigation pipeline "
756
+ "designed to identify malicious, suspicious, and unauthorized software supply chain activities that "
757
+ "conventional advisory databases (NVD, CVE, OSV) fail to detect. By analyzing Git commit diffs, "
758
+ "manifest changes, lifecycle script commands, external package registries, and CI/CD pipelines, "
759
+ "Guardian detects stealthy supply chain attacks and distinguishes them from benign engineering patterns.\n"
760
+ )
761
+
762
+ # 2. Scope & Commit Range
763
+ md.append("## 2. Investigation Scope and Commit Range")
764
+ md.append(f"- **Repository Path:** `{report.get('repository')}`")
765
+ md.append(f"- **Baseline Commit:** `{report.get('base_commit')}`")
766
+ md.append(f"- **Head Commit:** `{report.get('head_commit')}`")
767
+ md.append(f"- **Scanned Files:** Manifests (`package.json`), lockfiles (`package-lock.json`), registry configurations (`.npmrc`), CI/CD workflows (`.github/workflows/*.yml`), and container specifications (`Dockerfile`, `docker-compose.yml`).\n")
768
+
769
+ # 3. Methodology
770
+ md.append("## 3. Methodology")
771
+ md.append(
772
+ "The investigation combines four complementary analysis layers:\n"
773
+ "1. **Deterministic Git Diff Engine:** Audits version control differences, tagging findings with strict commit provenance (`OBSERVED_CHANGE` vs `HEURISTIC_FLAG`).\n"
774
+ "2. **Static Surface Inspectors:** Scans lifecycle scripts for shell execution hooks, verifies registry TLS protocols, checks package lexical similarity, and evaluates CI/CD permissions.\n"
775
+ "3. **Evidence Correlation Engine:** Correlates disparate indicators across vectors into multi-stage attack scenarios using MITRE ATT&CK techniques.\n"
776
+ "4. **LangGraph AI Investigator:** An autonomous agent using a bounded read-only tool loop with a strict Grounding Gate to evaluate evidence, test hypotheses, and document mitigating factors.\n"
777
+ )
778
+
779
+ # 4. Repository Changes
780
+ md.append("## 4. Repository Changes")
781
+ repo_diffs = by_cat.get("Repository Diff", [])
782
+ if repo_diffs:
783
+ for f in repo_diffs:
784
+ md.append(f"- **{f['id']}** ({f['severity']}): {f['title']} in `{f['affected_file']}` (Line {f['line_number']})")
785
+ else:
786
+ md.append("No sensitive repository file structural modifications detected in the commit range.\n")
787
+
788
+ # 5. Dependency Changes
789
+ md.append("## 5. Dependency Changes")
790
+ dep_changes = by_cat.get("Dependency Change", [])
791
+ if dep_changes:
792
+ for f in dep_changes:
793
+ origin_badge = "Introduced in Range" if f.get("change_origin") == "INTRODUCED_IN_RANGE" else "Pre-Existing"
794
+ md.append(f"- **{f['id']}** [{f['severity']} | {origin_badge}]: {f['title']} (`{f['affected_file']}:{f['line_number']}`)")
795
+ md.append(f" - *Evidence:* `{f.get('evidence', '')}`")
796
+ else:
797
+ md.append("No dependency version modifications detected.\n")
798
+
799
+ # 6. Lifecycle-Script Findings
800
+ md.append("## 6. Lifecycle-Script Findings")
801
+ scripts = by_cat.get("Lifecycle Script", [])
802
+ if scripts:
803
+ for f in scripts:
804
+ md.append(f"- **{f['id']}** [{f['severity']}]: {f['title']} (`{f['affected_file']}:{f['line_number']}`)")
805
+ md.append(f" - *Command:* `{f.get('evidence', '')}`")
806
+ else:
807
+ md.append("No dangerous lifecycle execution hooks identified.\n")
808
+
809
+ # 7. Registry and Dependency-Source Findings
810
+ md.append("## 7. Registry and Dependency-Source Findings")
811
+ sources = by_cat.get("Registry & Source", []) + by_cat.get("Dependency Source", [])
812
+ if sources:
813
+ for f in sources:
814
+ md.append(f"- **{f['id']}** [{f['severity']}]: {f['title']} in `{f['affected_file']}`")
815
+ else:
816
+ md.append("All packages resolved through default secure encrypted registries.\n")
817
+
818
+ # 8. CI/CD Findings
819
+ md.append("## 8. CI/CD Pipeline Findings")
820
+ cicd = [f for f in by_cat.get("Docker & CI/CD", []) if ".github" in f.get("affected_file", "")]
821
+ if cicd:
822
+ for f in cicd:
823
+ md.append(f"- **{f['id']}** [{f['severity']}]: {f['title']} (`{f['affected_file']}:{f['line_number']}`)")
824
+ else:
825
+ md.append("No CI/CD pipeline vulnerabilities identified.\n")
826
+
827
+ # 9. Docker and Build Findings
828
+ md.append("## 9. Docker and Container Build Findings")
829
+ docker_f = [f for f in by_cat.get("Docker & CI/CD", []) if "docker" in f.get("affected_file", "").lower() or "dockerfile" in f.get("affected_file", "").lower()]
830
+ if docker_f:
831
+ for f in docker_f:
832
+ md.append(f"- **{f['id']}** [{f['severity']}]: {f['title']} in `{f['affected_file']}:{f['line_number']}`")
833
+ else:
834
+ md.append("No container configuration weaknesses detected.\n")
835
+
836
+ # 10. Correlated Investigation Scenarios
837
+ md.append("## 10. Correlated Investigation Scenarios (Phase 2 Multi-Vector Engine)")
838
+ if scenarios:
839
+ for s in scenarios:
840
+ md.append(f"### Scenario: {s['scenario_name']}")
841
+ md.append(f"- **Composite ID:** `{s['composite_id']}`")
842
+ md.append(f"- **Severity:** `{s['severity']}` | **Confidence:** `{s['correlation_confidence']}` | **Status:** `{s['status']}`")
843
+ md.append(f"- **Attack Technique:** `{s.get('attack_technique')}`")
844
+ md.append(f"- **Suspected Narrative:** {s.get('suspected_scenario')}")
845
+ md.append("- **Observed Facts:**")
846
+ for fact in s.get("observed_facts", []):
847
+ md.append(f" - {fact}")
848
+ if s.get("contradicting_evidence"):
849
+ md.append("- **Contradicting / Mitigating Evidence:**")
850
+ for c in s["contradicting_evidence"]:
851
+ md.append(f" - **{c.get('factor')}:** {c.get('detail')}")
852
+ else:
853
+ md.append("No multi-vector correlation chains identified.\n")
854
+
855
+ # 11. AI Investigation Agent Verdicts
856
+ md.append("## 11. AI Investigation Agent Findings (Phase 3 LangGraph Tool-Using Loop)")
857
+ if ai_invs:
858
+ for inv in ai_invs:
859
+ md.append(f"### Investigation: `{inv['finding_id']}`")
860
+ md.append(f"- **Verdict:** `{inv['verdict']}` | **Confidence:** `{inv['confidence']}`")
861
+ md.append(f"- **Planner:** `{inv.get('planner')}` | **Steps Executed:** {len(inv.get('investigation_steps', []))}")
862
+ md.append(f"- **Rationale:** {inv['rationale']}")
863
+ if inv.get("attack_scenario"):
864
+ md.append(f"- **Suspected Attack Scenario:** {inv['attack_scenario']}")
865
+ if inv.get("contradicting_evidence"):
866
+ md.append("- **Mitigating Factors Identified:**")
867
+ for ce in inv["contradicting_evidence"]:
868
+ md.append(f" - *{ce.get('factor')}:* {ce.get('detail')}")
869
+ if inv.get("recommended_action"):
870
+ md.append(f"- **Actionable Remediation:** {inv['recommended_action']}")
871
+ else:
872
+ md.append("No autonomous AI investigations conducted.\n")
873
+
874
+ # 12. False-Positive Considerations
875
+ md.append("## 12. False-Positive Considerations")
876
+ md.append(
877
+ "- **Lexical Similarities vs Intentional Polyfills:** Package names like `bcrypt-nodejs` share similarity with `bcrypt`, "
878
+ "but investigation confirms legitimate engineering intent (pure-JS implementation avoiding native C++ toolchain errors).\n"
879
+ "- **Internal Private Registries:** Registries hosted on corporate networks are authenticated and safe when TLS (`strict-ssl=true`) is enforced.\n"
880
+ "- **Official First-Party Actions:** Mutable tags on `actions/*` repositories pose operational update risks but not maintainer account takeover risks.\n"
881
+ "- **Cryptographic Commit Pinning:** Git dependencies pinned to full 40-character commit SHAs are cryptographically immutable.\n"
882
+ )
883
+
884
+ # 13. Limitations
885
+ md.append("## 13. Limitations")
886
+ md.append(
887
+ "- Static analysis cannot observe runtime dynamic module loading (e.g. `eval(process.env.CODE)` computed at runtime).\n"
888
+ "- Obfuscated bytecode or compiled binary native addons require isolated dynamic sandboxing.\n"
889
+ "- Conventional CVE scanners remain necessary for published vulnerabilities in third-party dependency code.\n"
890
+ )
891
+
892
+ # 14. Research Foundation
893
+ md.append("## 14. Research Foundation")
894
+ md.append(f"- {CITATIONS['ohm_2020']}")
895
+ md.append(f"- {CITATIONS['ladisa_2023']}")
896
+ md.append(f"- {CITATIONS['wang_2026']}")
897
+ md.append(f"- {CITATIONS['lin_2024']}")
898
+ md.append(f"- {CITATIONS['birsan_2021']}\n")
899
+
900
+ # 15. Answer to Research Question
901
+ md.append("## 15. Answer to the Central Research Question")
902
+ md.append(
903
+ "> **\"Can combining repository changes, dependency changes and pipeline changes reveal suspicious activity that vulnerability databases cannot detect?\"**\n\n"
904
+ "**Yes, demonstrably.** Vulnerability databases such as NVD, CVE, and OSV index catalogued software defects after formal disclosure. "
905
+ "They provide zero visibility into:\n"
906
+ "1. Direct tarball and Git URLs introduced in pull requests.\n"
907
+ "2. Dangerous install-time lifecycle execution hooks (`curl | sh`).\n"
908
+ "3. CI/CD expression injection weaknesses (`${{ github.event... }}`).\n"
909
+ "4. Insecure registry configurations and disabled TLS certificate validation.\n"
910
+ "5. Lockfile tampering uncorroborated by manifest modifications.\n\n"
911
+ "By synthesizing Git diffs, dependency provenance, static script syntax, and CI/CD policies into a unified LangGraph "
912
+ "investigation loop, Guardian successfully identifies, correlates, and explains stealthy supply chain attack vectors "
913
+ "even when no published CVE exists."
914
+ )
915
+
916
+ content = "\n".join(md)
917
+ try:
918
+ output_path.parent.mkdir(parents=True, exist_ok=True)
919
+ output_path.write_text(content, encoding="utf-8")
920
+ except OSError as e:
921
+ pass
922
+ return content
923
+
924
+
925
+ def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
926
+ parser = argparse.ArgumentParser(
927
+ description="Guardian - Person 2: Suspicious Change Investigator Engine & AI Agent"
928
+ )
929
+ parser.add_argument(
930
+ "--repo",
931
+ default=".",
932
+ help="Path to Git repository or project root (default: current directory)"
933
+ )
934
+ parser.add_argument(
935
+ "--base",
936
+ default="HEAD~1",
937
+ help="Base Git commit or ref for diff comparison (default: HEAD~1)"
938
+ )
939
+ parser.add_argument(
940
+ "--head",
941
+ default="HEAD",
942
+ help="Head Git commit or ref for diff comparison (default: HEAD)"
943
+ )
944
+ parser.add_argument(
945
+ "--target-dir",
946
+ default=None,
947
+ help="Optional sub-directory inside repository to focus investigation (e.g. nodegoat)"
948
+ )
949
+ parser.add_argument(
950
+ "--out",
951
+ default="suspicious_changes.json",
952
+ help="Path to output JSON file (default: suspicious_changes.json)"
953
+ )
954
+ parser.add_argument(
955
+ "--report-md",
956
+ default="artifacts/reports/GIT_DIFF_INVESTIGATION.md",
957
+ help="Path to output Markdown report (default: artifacts/reports/GIT_DIFF_INVESTIGATION.md)"
958
+ )
959
+ parser.add_argument(
960
+ "--no-ai",
961
+ action="store_true",
962
+ help="Disable autonomous LangGraph AI agent investigations (deterministic only)"
963
+ )
964
+ parser.add_argument(
965
+ "--format",
966
+ choices=["json", "summary", "both"],
967
+ default="both",
968
+ help="Output format to display in stdout (json, summary, or both; default: both)"
969
+ )
970
+ return parser.parse_args(argv)
971
+
972
+
973
+ def main(argv: Optional[List[str]] = None) -> int:
974
+ args = parse_args(argv)
975
+ repo_path = Path(args.repo).resolve()
976
+ target_path = Path(args.target_dir).resolve() if args.target_dir else None
977
+
978
+ if not repo_path.exists():
979
+ print(f"Error: Repository path '{repo_path}' does not exist.", file=sys.stderr)
980
+ return 1
981
+
982
+ analyzer = ChangeAnalyzer(
983
+ repo_dir=repo_path,
984
+ base_commit=args.base,
985
+ head_commit=args.head,
986
+ target_dir=target_path,
987
+ enable_ai=not args.no_ai
988
+ )
989
+
990
+ report = analyzer.run_investigation()
991
+
992
+ # Write output JSON artifact
993
+ out_path = Path(args.out)
994
+ try:
995
+ out_path.parent.mkdir(parents=True, exist_ok=True)
996
+ out_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
997
+ except OSError as e:
998
+ print(f"Warning: Failed to write output to '{out_path}': {e}", file=sys.stderr)
999
+
1000
+ # Write output Markdown report
1001
+ if args.report_md:
1002
+ try:
1003
+ report_md_path = Path(args.report_md)
1004
+ generate_markdown_report(report, report_md_path)
1005
+ except Exception as e:
1006
+ print(f"Warning: Failed to write Markdown report to '{args.report_md}': {e}", file=sys.stderr)
1007
+
1008
+ # Print requested stdout format
1009
+ if args.format in ("summary", "both"):
1010
+ print(format_summary_table(report))
1011
+ print(f"\n[+] Investigation report successfully written to: {out_path.resolve()}")
1012
+ if args.report_md:
1013
+ print(f"[+] Formal markdown report written to: {Path(args.report_md).resolve()}\n")
1014
+
1015
+ if args.format == "json":
1016
+ print(json.dumps(report, indent=2))
1017
+
1018
+ return 0
1019
+
1020
+
1021
+ if __name__ == "__main__":
1022
+ sys.exit(main())