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,155 @@
1
+ """Layered, validated configuration.
2
+
3
+ Precedence (highest first): environment variable ``SCANNER_<NAME>`` > ``.env`` (loaded into the environment) > ``scanner.toml`` > built-in default.
4
+
5
+ * The config file is ``scanner.toml`` in the project root, or the path in ``SCANNER_CONFIG``. See ``scanner.example.toml``.
6
+ * Every value is type- and range-checked. An invalid value never crashes the app: it is ignored, the default is used, and the problem is
7
+ listed (Settings & Health page, ``Settings.problems``).
8
+ * Secrets (API keys) are accepted from the environment only; a secret found in the file is rejected and reported.
9
+ * ``Settings.sources`` records where each effective value came from.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ try:
18
+ import tomllib
19
+ except ImportError: # pragma: no cover
20
+ import tomli as tomllib # type: ignore
21
+
22
+ # name -> (type, minimum, maximum, meaning)
23
+ TUNABLES: dict[str, tuple[type, float, float, str]] = {
24
+ "clone_timeout_s": (int, 10, 3600, "git clone time limit (seconds)"),
25
+ "clone_depth": (int, 1, 5000, "shallow clone depth (commits)"),
26
+ "max_repo_bytes": (int, 1_000_000, 20_000_000_000, "largest repository accepted (bytes)"),
27
+ "max_files_walked": (int, 1000, 5_000_000, "file walk cap during inspection"),
28
+ "syft_timeout_s": (int, 10, 7200, "Syft/Trivy run time limit (seconds)"),
29
+ "max_file_bytes": (int, 10_000, 500_000_000, "largest manifest/lockfile parsed (bytes)"),
30
+ "http_timeout_s": (int, 3, 300, "HTTP timeout for OSV/NVD/KEV/registries (seconds)"),
31
+ "http_retries": (int, 0, 10, "HTTP retries"),
32
+ "osv_batch_size": (int, 1, 1000, "OSV batch size"),
33
+ "osv_workers": (int, 1, 32, "parallel OSV requests"),
34
+ "nvd_max_cves_no_key": (int, 0, 1000, "NVD CVE lookups without an API key"),
35
+ "nvd_max_cves_with_key": (int, 0, 5000, "NVD CVE lookups with an API key"),
36
+ "metadata_budget_s": (int, 5, 1800, "registry metadata look-up budget per scan (seconds)"),
37
+ "scan_cache_ttl_s": (int, 0, 31_536_000, "reuse a stored scan of the same commit for at most this long (seconds)"),
38
+ "workspace_max_age_s": (int, 60, 604_800, "orphaned clone workspaces older than this are deleted (seconds)"),
39
+ "keep_scans_per_repo": (int, 1, 1000, "scans kept per repository"),
40
+ "investigator_llm_max": (int, 0, 100, "findings the optional LLM may investigate per scan"),
41
+ "investigator_max_steps": (int, 1, 12, "tool calls per LLM investigation"),
42
+ "remediation_max_groups": (int, 0, 500, "source-package groups planned per scan"),
43
+ "remediation_budget_s": (int, 10, 1800, "time budget for remediation planning (seconds)"),
44
+ "cache_max_rows": (int, 1000, 50_000_000, "upper bound for rows in the TTL cache"),
45
+ "cache_max_age_days": (int, 1, 3650, "cache rows older than this are purged"),
46
+ "max_paths_per_target": (int, 1, 500, "dependency paths kept per finding"),
47
+ "max_path_depth": (int, 2, 200, "deepest dependency path enumerated"),
48
+ "dashboard_port": (int, 1, 65535, "localhost port of the dashboard"),
49
+ }
50
+ STRINGS = {"syft_bin": "Syft executable", "trivy_bin": "Trivy executable", "llm_model": "optional LLM model name (default per provider)", "llm_provider": "optional LLM provider (auto-detected from LLM_API_KEY)", "llm_base_url": "base URL for an OpenAI-compatible LLM endpoint"}
51
+ PATHS = {"data_dir": "SQLite database folder", "workspace_dir": "temporary clone folder"}
52
+ SECRETS = {"nvd_api_key", "llm_api_key", "anthropic_api_key"}
53
+ ROOT = Path(__file__).resolve().parent.parent.parent # repository root (src/config/ -> repo)
54
+
55
+
56
+ def _coerce(name: str, raw: Any) -> tuple[Any, str | None]:
57
+ typ, lo, hi, _ = TUNABLES[name]
58
+ try:
59
+ if isinstance(raw, bool):
60
+ raise ValueError("boolean is not a number")
61
+ v = typ(raw)
62
+ except (TypeError, ValueError):
63
+ return None, f"{name}: '{raw}' is not a valid {typ.__name__}"
64
+ if not (lo <= v <= hi):
65
+ return None, f"{name}: {v} is outside the allowed range {int(lo)}..{int(hi)}"
66
+ return v, None
67
+
68
+
69
+ def config_file() -> Path:
70
+ explicit = os.environ.get("STACKPARITY_CONFIG") or os.environ.get("SCANNER_CONFIG")
71
+ if explicit:
72
+ return Path(explicit).expanduser()
73
+ from config.settings import APP_HOME
74
+ for cand in (APP_HOME / "stackparity.toml", APP_HOME / "scanner.toml"):
75
+ if cand.exists():
76
+ return cand
77
+ return APP_HOME / "stackparity.toml"
78
+
79
+
80
+ def apply(settings: Any) -> Any:
81
+ """Apply scanner.toml and SCANNER_* environment overrides to ``settings`` in place; returns it."""
82
+ sources: dict[str, str] = {}
83
+ problems: list[str] = []
84
+ file_vals: dict[str, Any] = {}
85
+ cf = config_file()
86
+ file_found = cf.exists()
87
+ if file_found:
88
+ try:
89
+ file_vals = tomllib.loads(cf.read_text(encoding="utf-8"))
90
+ except Exception as e:
91
+ problems.append(f"{cf.name}: cannot be parsed ({type(e).__name__}: {e}); file ignored")
92
+ file_vals = {}
93
+ for k in file_vals:
94
+ if k.lower() in SECRETS:
95
+ problems.append(f"{cf.name}: '{k}' is a secret and must be set via environment variable, not in the file (ignored)")
96
+ elif k not in TUNABLES and k not in STRINGS and k not in PATHS:
97
+ problems.append(f"{cf.name}: unknown key '{k}' (ignored)")
98
+
99
+ def pick(name: str):
100
+ env = os.environ.get(f"STACKPARITY_{name.upper()}") or os.environ.get(f"SCANNER_{name.upper()}")
101
+ if env not in (None, ""):
102
+ return env, "env"
103
+ if name in file_vals and name.lower() not in SECRETS:
104
+ return file_vals[name], "file"
105
+ return None, "default"
106
+
107
+ for name in TUNABLES:
108
+ raw, src = pick(name)
109
+ if src != "default":
110
+ v, err = _coerce(name, raw)
111
+ if err:
112
+ problems.append(f"{err} ({src}); using default {getattr(settings, name)}")
113
+ else:
114
+ setattr(settings, name, v)
115
+ sources[name] = src
116
+ continue
117
+ sources[name] = "default"
118
+ for name in STRINGS:
119
+ raw, src = pick(name)
120
+ legacy = {"syft_bin": "SYFT_BIN", "trivy_bin": "TRIVY_BIN", "llm_model": "LLM_MODEL", "llm_provider": "LLM_PROVIDER", "llm_base_url": "LLM_BASE_URL"}[name]
121
+ if src == "default" and os.environ.get(legacy):
122
+ raw, src = os.environ[legacy], "env"
123
+ if src != "default" and isinstance(raw, str) and raw.strip():
124
+ setattr(settings, name, raw.strip())
125
+ sources[name] = src
126
+ else:
127
+ sources[name] = "default"
128
+ for name in PATHS:
129
+ raw, src = pick(name)
130
+ legacy = {"data_dir": "SCANNER_DATA_DIR", "workspace_dir": "SCANNER_WORKSPACE_DIR"}[name]
131
+ if src == "default" and os.environ.get(legacy):
132
+ raw, src = os.environ[legacy], "env"
133
+ if src != "default" and isinstance(raw, str) and raw.strip():
134
+ setattr(settings, name, Path(raw).expanduser().resolve())
135
+ sources[name] = src
136
+ else:
137
+ sources[name] = "default"
138
+ for sec, envs in (("nvd_api_key", ("NVD_API_KEY",)), ("llm_api_key", ("LLM_API_KEY", "ANTHROPIC_API_KEY"))):
139
+ sources[sec] = "env" if any(os.environ.get(e) for e in envs) else "unset"
140
+ if settings.nvd_max_cves_with_key < settings.nvd_max_cves_no_key:
141
+ problems.append("nvd_max_cves_with_key is lower than nvd_max_cves_no_key")
142
+ settings.sources, settings.problems, settings.config_file = sources, problems, (str(cf) if file_found else None)
143
+ return settings
144
+
145
+
146
+ def effective(settings: Any) -> list[dict]:
147
+ """Rows for display: name, value (secrets masked), source, meaning."""
148
+ rows = []
149
+ for name, (_, lo, hi, doc) in TUNABLES.items():
150
+ rows.append({"setting": name, "value": getattr(settings, name), "source": settings.sources.get(name, "default"), "allowed": f"{int(lo)}..{int(hi)}", "meaning": doc})
151
+ for name, doc in {**STRINGS, **PATHS}.items():
152
+ rows.append({"setting": name, "value": str(getattr(settings, name)), "source": settings.sources.get(name, "default"), "allowed": "text", "meaning": doc})
153
+ for name, label in (("nvd_api_key", "NVD API key (env NVD_API_KEY)"), ("llm_api_key", "optional LLM API key (env LLM_API_KEY: Groq, Gemini, Anthropic or OpenAI-compatible)")):
154
+ rows.append({"setting": name, "value": "set (hidden)" if getattr(settings, name) else "not set", "source": settings.sources.get(name, "unset"), "allowed": "environment only", "meaning": label})
155
+ return rows
@@ -0,0 +1,108 @@
1
+ """Runtime configuration (layered: env > .env > scanner.toml > defaults; see config/loader.py). Secrets come from environment variables only."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from dotenv import load_dotenv
10
+
11
+ ROOT = Path(__file__).resolve().parent.parent.parent # repository root (src/config/ -> repo)
12
+ _IS_REPO_CHECKOUT = (ROOT / "pyproject.toml").exists() and os.access(ROOT, os.W_OK)
13
+ APP_HOME = Path(os.environ.get("STACKPARITY_HOME") or os.environ.get("SC_GUARDIAN_HOME") or (Path.home() / ".stackparity")).expanduser().resolve()
14
+
15
+ load_dotenv(APP_HOME / ".env")
16
+
17
+ # Preserve existing checkout history unless the operator selects a new home.
18
+ _legacy_store = _IS_REPO_CHECKOUT and (ROOT / "data" / "scanner.db").is_file()
19
+ _DEFAULT_BASE = ROOT if _legacy_store and not (os.getenv("STACKPARITY_HOME") or os.getenv("SC_GUARDIAN_HOME")) else APP_HOME
20
+
21
+
22
+ def _env_path(name: str, default: Path) -> Path:
23
+ v = os.environ.get(name)
24
+ return Path(v).expanduser().resolve() if v else default
25
+
26
+
27
+ @dataclass
28
+ class Settings:
29
+ data_dir: Path = field(default_factory=lambda: _env_path("STACKPARITY_DATA_DIR", _env_path("SCANNER_DATA_DIR", _DEFAULT_BASE / "data")))
30
+ workspace_dir: Path = field(default_factory=lambda: _env_path("STACKPARITY_WORKSPACE_DIR", _env_path("SCANNER_WORKSPACE_DIR", _DEFAULT_BASE / ".workspaces")))
31
+ artifacts_dir: Path = field(default_factory=lambda: _DEFAULT_BASE / "artifacts")
32
+ syft_bin: str = field(default_factory=lambda: os.environ.get("SYFT_BIN") or shutil.which("syft") or "syft")
33
+ trivy_bin: str = field(default_factory=lambda: os.environ.get("TRIVY_BIN") or shutil.which("trivy") or "trivy")
34
+ nvd_api_key: str | None = field(default_factory=lambda: os.environ.get("NVD_API_KEY") or None)
35
+ llm_api_key: str | None = field(default_factory=lambda: os.environ.get("LLM_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") or None)
36
+ llm_provider: str | None = field(default_factory=lambda: os.environ.get("LLM_PROVIDER") or None) # groq | gemini | anthropic | openai | openai_compatible (auto-detected from the key)
37
+ llm_model: str | None = field(default_factory=lambda: os.environ.get("LLM_MODEL") or os.environ.get("EXPLAIN_LLM_MODEL") or None)
38
+ llm_base_url: str | None = field(default_factory=lambda: os.environ.get("LLM_BASE_URL") or None)
39
+
40
+ # clone / scan limits
41
+ clone_timeout_s: int = 180
42
+ clone_depth: int = 50
43
+ max_repo_bytes: int = 600 * 1024 * 1024
44
+ max_files_walked: int = 200_000
45
+ syft_timeout_s: int = 600
46
+ max_file_bytes: int = 20 * 1024 * 1024 # per parsed manifest/lockfile
47
+
48
+ # container scanning (opt-in Trivy container image vulnerability analysis)
49
+ container_scan_enabled: bool = field(default_factory=lambda: os.environ.get("CONTAINER_SCAN_ENABLED", "").lower() in ("1", "true", "yes"))
50
+ container_scan_os_packages: bool = True
51
+ container_scan_app_packages: bool = True
52
+ container_scan_timeout_s: int = 180
53
+ container_scan_max_images: int = 5
54
+ container_scan_allow_remote_pull: bool = False
55
+
56
+ # network
57
+ http_timeout_s: int = 25
58
+ http_retries: int = 3
59
+ osv_batch_size: int = 500
60
+ osv_workers: int = 8
61
+ nvd_max_cves_no_key: int = 20
62
+ nvd_max_cves_with_key: int = 300
63
+
64
+ # metadata fusion
65
+ metadata_budget_s: int = 120 # wall-clock budget for registry look-ups per scan (results are cached)
66
+
67
+ # freshness / retention
68
+ scan_cache_ttl_s: int = 24 * 3600 # a stored scan of the same commit is reused only while younger than this
69
+ workspace_max_age_s: int = 3600 # orphaned clone workspaces older than this are removed at start
70
+ keep_scans_per_repo: int = 20
71
+
72
+ # investigator
73
+ investigator_llm_max: int = 8 # findings the optional LLM may investigate per scan
74
+ investigator_max_steps: int = 5 # tool calls per LLM investigation
75
+
76
+ # remediation
77
+ remediation_max_groups: int = 300 # source-package groups planned per scan (highest priority first)
78
+ remediation_budget_s: int = 900 # wall-clock budget for planning
79
+
80
+ # cache bounds
81
+ cache_max_rows: int = 2_000_000
82
+ cache_max_age_days: int = 120
83
+
84
+ # graph
85
+ max_paths_per_target: int = 25
86
+ max_path_depth: int = 40
87
+
88
+ # optional localhost dashboard (the bind address is always 127.0.0.1)
89
+ dashboard_port: int = 8501
90
+
91
+ # filled by config.loader.apply(): where each value came from and what was wrong with the configuration
92
+ sources: dict = field(default_factory=dict, repr=False)
93
+ problems: list = field(default_factory=list, repr=False)
94
+ config_file: str | None = field(default=None, repr=False)
95
+
96
+ @property
97
+ def db_path(self) -> Path:
98
+ return self.data_dir / "scanner.db"
99
+
100
+
101
+ def get_settings() -> Settings:
102
+ from config.loader import apply
103
+ s = apply(Settings())
104
+ s.data_dir.mkdir(parents=True, exist_ok=True)
105
+ s.workspace_dir.mkdir(parents=True, exist_ok=True)
106
+ for sub in ("sbom", "scans", "reports", "graphs"):
107
+ (s.artifacts_dir / sub).mkdir(parents=True, exist_ok=True)
108
+ return s
@@ -0,0 +1,12 @@
1
+ """Container scanning package."""
2
+ from containers.discovery import discover_container_assets
3
+ from containers.models import ContainerScanFinding, DiscoveredContainerAsset
4
+ from containers.trivy_image_scanner import parse_trivy_image_json, scan_container_image
5
+
6
+ __all__ = [
7
+ "DiscoveredContainerAsset",
8
+ "ContainerScanFinding",
9
+ "discover_container_assets",
10
+ "scan_container_image",
11
+ "parse_trivy_image_json",
12
+ ]
@@ -0,0 +1,143 @@
1
+ """Container image and build specification discovery engine."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any, Optional
6
+
7
+ from containers.models import DiscoveredContainerAsset
8
+ from core.repository_inspector import safe_read_text
9
+ from pipeline_analysis.dockerfile import analyze_compose, parse_dockerfile, split_image
10
+
11
+
12
+ def discover_container_assets(
13
+ repo_root: Path,
14
+ dockerfiles: list[str],
15
+ container_files: list[str],
16
+ ci_docker_builds: Optional[list[dict[str, Any]]] = None,
17
+ ) -> list[DiscoveredContainerAsset]:
18
+ """Correlate Dockerfiles, Compose files, and CI Docker builds into canonical container assets."""
19
+ assets: list[DiscoveredContainerAsset] = []
20
+ seen_ids: set[str] = set()
21
+ ci_builds = ci_docker_builds or []
22
+
23
+ # Map dockerfile path normalized -> list of CI build directives
24
+ ci_by_df: dict[str, list[dict[str, Any]]] = {}
25
+ for b in ci_builds:
26
+ df_target = str(b.get("dockerfile_path", "Dockerfile")).replace("\\", "/").lstrip("./")
27
+ ci_by_df.setdefault(df_target, []).append(b)
28
+
29
+ # 1. Process Dockerfiles
30
+ for rel in dockerfiles:
31
+ norm_rel = rel.replace("\\", "/").lstrip("./")
32
+ text = safe_read_text(repo_root, rel)
33
+ if text is None:
34
+ continue
35
+
36
+ instructions = parse_dockerfile(text)
37
+ stages: list[str] = []
38
+ base_images: list[str] = []
39
+
40
+ for inst in instructions:
41
+ if inst.op == "FROM":
42
+ # FROM image [AS stage]
43
+ parts = inst.args.split()
44
+ if parts:
45
+ base_images.append(parts[0])
46
+ if len(parts) >= 3 and parts[1].upper() == "AS":
47
+ stages.append(parts[2])
48
+
49
+ final_base = base_images[-1] if base_images else None
50
+ nm, tag, dig = split_image(final_base) if final_base else (None, None, None)
51
+
52
+ # Match with any CI builds
53
+ matching_ci = ci_by_df.get(norm_rel, [])
54
+ # Also check just the filename if path didn't match directly
55
+ if not matching_ci and "/" in norm_rel:
56
+ matching_ci = ci_by_df.get(norm_rel.rsplit("/", 1)[-1], [])
57
+
58
+ ci_jobs: list[str] = []
59
+ target_tags: list[str] = []
60
+ for cib in matching_ci:
61
+ ci_file = cib.get("ci_file", "")
62
+ ci_job = cib.get("ci_job", "")
63
+ if ci_file and ci_job:
64
+ ci_jobs.append(f"{ci_file}#{ci_job}")
65
+ if cib.get("image_tag"):
66
+ target_tags.append(str(cib["image_tag"]))
67
+
68
+ primary_tag = target_tags[0] if target_tags else None
69
+ aid = DiscoveredContainerAsset.generate_id(rel, primary_tag, final_base)
70
+ if aid not in seen_ids:
71
+ seen_ids.add(aid)
72
+ assets.append(
73
+ DiscoveredContainerAsset(
74
+ asset_id=aid,
75
+ source_type="dockerfile",
76
+ source_file=rel,
77
+ image_tag=primary_tag,
78
+ base_image=nm,
79
+ base_image_tag=tag,
80
+ base_image_digest=dig,
81
+ stage_names=stages,
82
+ associated_ci_jobs=ci_jobs,
83
+ )
84
+ )
85
+
86
+ # 2. Process Docker Compose files
87
+ for rel in container_files:
88
+ name = rel.rsplit("/", 1)[-1].lower()
89
+ if not name.startswith(("docker-compose", "compose")):
90
+ continue
91
+ text = safe_read_text(repo_root, rel)
92
+ if text is None:
93
+ continue
94
+
95
+ _, im_list = analyze_compose(text, rel)
96
+ for im in im_list:
97
+ raw_ref = im.get("ref", "")
98
+ nm = im.get("name")
99
+ tag = im.get("tag")
100
+ dig = im.get("digest")
101
+ aid = DiscoveredContainerAsset.generate_id(rel, raw_ref, None)
102
+ if aid not in seen_ids:
103
+ seen_ids.add(aid)
104
+ assets.append(
105
+ DiscoveredContainerAsset(
106
+ asset_id=aid,
107
+ source_type="compose",
108
+ source_file=rel,
109
+ image_tag=raw_ref,
110
+ base_image=nm,
111
+ base_image_tag=tag,
112
+ base_image_digest=dig,
113
+ )
114
+ )
115
+
116
+ handled_dockerfiles = {rel.replace("\\", "/").lstrip("./") for rel in dockerfiles}
117
+ for rel in dockerfiles:
118
+ if "/" in rel:
119
+ handled_dockerfiles.add(rel.rsplit("/", 1)[-1])
120
+
121
+ # 3. Process any remaining CI Docker builds not linked to discovered Dockerfiles
122
+ for b in ci_builds:
123
+ df_target = str(b.get("dockerfile_path", "Dockerfile"))
124
+ norm_df = df_target.replace("\\", "/").lstrip("./")
125
+ if norm_df in handled_dockerfiles or (norm_df.rsplit("/", 1)[-1] in handled_dockerfiles):
126
+ continue
127
+ tag = b.get("image_tag")
128
+ ci_file = b.get("ci_file", "")
129
+ ci_job = b.get("ci_job", "")
130
+ aid = DiscoveredContainerAsset.generate_id(df_target, tag, None)
131
+ if aid not in seen_ids:
132
+ seen_ids.add(aid)
133
+ assets.append(
134
+ DiscoveredContainerAsset(
135
+ asset_id=aid,
136
+ source_type="ci_pipeline",
137
+ source_file=df_target,
138
+ image_tag=tag,
139
+ associated_ci_jobs=[f"{ci_file}#{ci_job}"] if ci_file and ci_job else [],
140
+ )
141
+ )
142
+
143
+ return assets
@@ -0,0 +1,72 @@
1
+ """Container asset discovery and vulnerability scanning models."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Literal, Optional
7
+
8
+
9
+ @dataclass
10
+ class DiscoveredContainerAsset:
11
+ """Represents a container image or build specification discovered in a repo."""
12
+ asset_id: str
13
+ source_type: Literal["dockerfile", "compose", "ci_pipeline", "prebuilt_image"]
14
+ source_file: str
15
+ image_tag: Optional[str] = None
16
+ base_image: Optional[str] = None
17
+ base_image_tag: Optional[str] = None
18
+ base_image_digest: Optional[str] = None
19
+ context_dir: Optional[str] = None
20
+ stage_names: list[str] = field(default_factory=list)
21
+ associated_ci_jobs: list[str] = field(default_factory=list)
22
+ scan_status: Literal["pending", "scanned", "skipped", "failed"] = "pending"
23
+ scan_error: Optional[str] = None
24
+
25
+ @staticmethod
26
+ def generate_id(source_file: str, image_tag: Optional[str], base_image: Optional[str]) -> str:
27
+ key = f"{source_file}:{image_tag or ''}:{base_image or ''}"
28
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()[:12]
29
+
30
+
31
+ @dataclass
32
+ class ContainerScanFinding:
33
+ """Normalized vulnerability finding inside a container image."""
34
+ finding_id: str
35
+ vuln_id: str
36
+ package_name: str
37
+ installed_version: str
38
+ fixed_version: Optional[str] = None
39
+ severity: Literal["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN"] = "UNKNOWN"
40
+ cvss_score: Optional[float] = None
41
+ package_type: Literal["os_pkg", "lang_pkg"] = "os_pkg"
42
+ os_distribution: Optional[str] = None
43
+ target: str = ""
44
+ layer_diff_id: Optional[str] = None
45
+ title: str = ""
46
+ description: str = ""
47
+ references: list[str] = field(default_factory=list)
48
+ image_tag: str = ""
49
+ source_file: str = ""
50
+ extra: dict[str, Any] = field(default_factory=dict)
51
+
52
+ def to_dict(self) -> dict[str, Any]:
53
+ return {
54
+ "finding_id": self.finding_id,
55
+ "vuln_id": self.vuln_id,
56
+ "package_name": self.package_name,
57
+ "installed_version": self.installed_version,
58
+ "fixed_version": self.fixed_version,
59
+ "severity": self.severity,
60
+ "cvss_score": self.cvss_score,
61
+ "package_type": self.package_type,
62
+ "os_distribution": self.os_distribution,
63
+ "target": self.target,
64
+ "layer_diff_id": self.layer_diff_id,
65
+ "title": self.title,
66
+ "description": self.description,
67
+ "references": self.references,
68
+ "image_tag": self.image_tag,
69
+ "source_file": self.source_file,
70
+ "asset_type": "container_image",
71
+ "extra": self.extra,
72
+ }
@@ -0,0 +1,165 @@
1
+ """Controlled Trivy container image vulnerability scanner wrapper."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import subprocess
7
+ from typing import Any, Optional
8
+
9
+ from config.settings import Settings, get_settings
10
+ from containers.models import ContainerScanFinding, DiscoveredContainerAsset
11
+ from core.safe_env import scrubbed_env
12
+ from sbom.trivy_runner import resolve_trivy
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def parse_trivy_image_json(
18
+ json_text: str,
19
+ image_tag: str,
20
+ source_file: str = "",
21
+ ) -> list[ContainerScanFinding]:
22
+ """Parse Trivy image scan JSON output into normalized ContainerScanFinding records."""
23
+ findings: list[ContainerScanFinding] = []
24
+ if not json_text or not json_text.strip():
25
+ return findings
26
+
27
+ try:
28
+ data = json.loads(json_text)
29
+ except Exception as e:
30
+ logger.warning("Failed to decode Trivy image output as JSON: %s", e)
31
+ return findings
32
+
33
+ results = data.get("Results") or []
34
+ finding_idx = 1
35
+
36
+ for res in results:
37
+ target_name = str(res.get("Target", ""))
38
+ target_class = str(res.get("Class", "")) # e.g., "os-pkgs", "lang-pkgs"
39
+ target_type = str(res.get("Type", "")) # e.g., "debian", "alpine", "pip", "npm"
40
+
41
+ pkg_type = "os_pkg" if target_class == "os-pkgs" or target_type in ("debian", "ubuntu", "alpine", "redhat", "centos", "apk", "rpm") else "lang_pkg"
42
+
43
+ for v in res.get("Vulnerabilities") or []:
44
+ vid = str(v.get("VulnerabilityID", ""))
45
+ pname = str(v.get("PkgName", ""))
46
+ inst_ver = str(v.get("InstalledVersion", ""))
47
+ fixed_ver = v.get("FixedVersion")
48
+ sev = str(v.get("Severity", "UNKNOWN")).upper()
49
+ if sev not in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"):
50
+ sev = "UNKNOWN"
51
+
52
+ # Parse CVSS score
53
+ cvss_obj = v.get("CVSS") or {}
54
+ cvss_val: Optional[float] = None
55
+ for src_key in ("nvd", "redhat", "ghsa"):
56
+ if src_key in cvss_obj and isinstance(cvss_obj[src_key], dict):
57
+ score = cvss_obj[src_key].get("V3Score")
58
+ if score is not None:
59
+ try:
60
+ cvss_val = float(score)
61
+ break
62
+ except (ValueError, TypeError):
63
+ pass
64
+
65
+ layer_diff = (v.get("Layer") or {}).get("DiffID")
66
+ refs = v.get("References") or []
67
+ if v.get("PrimaryURL") and v["PrimaryURL"] not in refs:
68
+ refs = [v["PrimaryURL"]] + list(refs)
69
+
70
+ fid = f"CONT-{finding_idx:04d}"
71
+ finding_idx += 1
72
+
73
+ findings.append(
74
+ ContainerScanFinding(
75
+ finding_id=fid,
76
+ vuln_id=vid,
77
+ package_name=pname,
78
+ installed_version=inst_ver,
79
+ fixed_version=str(fixed_version) if (fixed_version := fixed_ver) else None,
80
+ severity=sev,
81
+ cvss_score=cvss_val,
82
+ package_type=pkg_type,
83
+ os_distribution=target_type if pkg_type == "os_pkg" else None,
84
+ target=target_name,
85
+ layer_diff_id=str(layer_diff) if layer_diff else None,
86
+ title=str(v.get("Title", f"{vid} in {pname}")),
87
+ description=str(v.get("Description", "")),
88
+ references=[str(r) for r in refs[:5]],
89
+ image_tag=image_tag,
90
+ source_file=source_file,
91
+ )
92
+ )
93
+
94
+ return findings
95
+
96
+
97
+ def scan_container_image(
98
+ image_ref: str,
99
+ asset: DiscoveredContainerAsset,
100
+ settings: Optional[Settings] = None,
101
+ ) -> tuple[list[ContainerScanFinding], dict[str, Any]]:
102
+ """Execute Trivy image scan against an image reference, returning findings and execution metadata."""
103
+ s = settings or get_settings()
104
+
105
+ if not s.container_scan_enabled:
106
+ asset.scan_status = "skipped"
107
+ return [], {"ok": False, "skipped": True, "reason": "Container scanning is disabled (opt-in)"}
108
+
109
+ trivy_bin = resolve_trivy(s)
110
+ if not trivy_bin:
111
+ asset.scan_status = "skipped"
112
+ asset.scan_error = "Trivy binary not found on PATH"
113
+ return [], {"ok": False, "skipped": True, "reason": "Trivy binary not found"}
114
+
115
+ cmd = [
116
+ trivy_bin,
117
+ "image",
118
+ "--format", "json",
119
+ "--quiet",
120
+ "--scanners", "vuln",
121
+ ]
122
+
123
+ # Select vulnerability types based on settings
124
+ vuln_types: list[str] = []
125
+ if s.container_scan_os_packages:
126
+ vuln_types.append("os")
127
+ if s.container_scan_app_packages:
128
+ vuln_types.append("library")
129
+ if vuln_types:
130
+ cmd.extend(["--vuln-type", ",".join(vuln_types)])
131
+
132
+ cmd.append(image_ref)
133
+
134
+ try:
135
+ proc = subprocess.run(
136
+ cmd,
137
+ capture_output=True,
138
+ text=True,
139
+ encoding="utf-8",
140
+ errors="replace", # Trivy emits UTF-8 JSON; the Windows default (cp1252) crashes on it and silently yields zero findings
141
+ timeout=s.container_scan_timeout_s,
142
+ shell=False,
143
+ env=scrubbed_env(),
144
+ )
145
+ except subprocess.TimeoutExpired:
146
+ asset.scan_status = "failed"
147
+ asset.scan_error = f"Trivy scan timed out after {s.container_scan_timeout_s}s"
148
+ logger.warning("Trivy image scan timed out for %s", image_ref)
149
+ return [], {"ok": False, "error": asset.scan_error}
150
+ except Exception as e:
151
+ asset.scan_status = "failed"
152
+ asset.scan_error = f"Subprocess execution error: {e}"
153
+ logger.warning("Trivy scan execution failed for %s: %s", image_ref, e)
154
+ return [], {"ok": False, "error": str(e)}
155
+
156
+ if proc.returncode != 0:
157
+ err_msg = proc.stderr.strip() or f"Trivy exited with code {proc.returncode}"
158
+ asset.scan_status = "failed"
159
+ asset.scan_error = err_msg
160
+ logger.info("Trivy image scan failed for %s: %s", image_ref, err_msg)
161
+ return [], {"ok": False, "error": err_msg}
162
+
163
+ findings = parse_trivy_image_json(proc.stdout, image_ref, asset.source_file)
164
+ asset.scan_status = "scanned"
165
+ return findings, {"ok": True, "count": len(findings)}
File without changes