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,356 @@
1
+ """GitHub Actions pipeline adapter."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Any, Optional
6
+
7
+ import yaml
8
+
9
+ from pipeline_analysis.ci import (
10
+ DEPRECATED_BELOW,
11
+ FIRST_PARTY,
12
+ INJECTABLE,
13
+ INJECTABLE_FIELDS,
14
+ SHA40,
15
+ UNTRUSTED_TRIGGERS,
16
+ parse_action_ref,
17
+ )
18
+ from pipeline_analysis.ci_adapters.base import BaseCIAdapter
19
+ from pipeline_analysis.ci_models import CIDockerBuild, UnifiedJob, UnifiedPipeline, UnifiedStep
20
+ from pipeline_analysis.dockerfile import INSECURE, PIPE_TO_SHELL
21
+ from pipeline_analysis.models import PipelineFinding
22
+
23
+ GHA_FILE_RE = re.compile(r"^(.*/)?\.github/workflows/[^/]+\.ya?ml$", re.IGNORECASE)
24
+
25
+
26
+ class GitHubActionsAdapter(BaseCIAdapter):
27
+ """Adapter for GitHub Actions workflows (.github/workflows/*.yml)."""
28
+
29
+ @property
30
+ def platform_id(self) -> str:
31
+ return "github_actions"
32
+
33
+ @property
34
+ def platform_name(self) -> str:
35
+ return "GitHub Actions"
36
+
37
+ def can_handle(self, file_path: str) -> bool:
38
+ norm = file_path.replace("\\", "/")
39
+ return bool(GHA_FILE_RE.match(norm))
40
+
41
+ def analyze(self, text: str, file_path: str) -> UnifiedPipeline:
42
+ pipeline = UnifiedPipeline(platform=self.platform_id, file_path=file_path)
43
+ lines = text.splitlines()
44
+
45
+ try:
46
+ data = yaml.safe_load(text)
47
+ except Exception as e:
48
+ pipeline.parse_success = False
49
+ pipeline.error_message = str(e)
50
+ return pipeline
51
+
52
+ if not isinstance(data, dict):
53
+ pipeline.parse_success = False
54
+ pipeline.error_message = "Root must be a YAML mapping"
55
+ return pipeline
56
+
57
+ pipeline.raw_parsed = data
58
+
59
+ # Triggers
60
+ on = data.get("on", data.get(True)) # PyYAML parses unquoted 'on:' as True
61
+ triggers = set(on) if isinstance(on, (dict, list)) else ({on} if isinstance(on, str) else set())
62
+ triggers_set = {str(t) for t in triggers}
63
+ pipeline.triggers = sorted(triggers_set)
64
+
65
+ untrusted = bool(triggers_set & UNTRUSTED_TRIGGERS)
66
+ pr_trigger = bool(triggers_set & {"pull_request", "pull_request_target"})
67
+
68
+ # Global permissions check
69
+ perms = data.get("permissions")
70
+ raw_jobs = data.get("jobs") if isinstance(data.get("jobs"), dict) else {}
71
+
72
+ if perms is None and not any(isinstance(j, dict) and j.get("permissions") is not None for j in raw_jobs.values()):
73
+ pipeline.findings.append(
74
+ self._create_finding(
75
+ "GHA004",
76
+ "No explicit token permissions (defaults may be read-write)",
77
+ "LOW",
78
+ file_path,
79
+ 1,
80
+ "(no `permissions:` key)",
81
+ "permissions",
82
+ "Without an explicit `permissions:` block the GITHUB_TOKEN gets the repository default, which can include write access.",
83
+ "Add a top-level `permissions: contents: read` and grant extra scopes per job.",
84
+ evidence_strength="medium",
85
+ references=["https://docs.github.com/actions/security-guides/automatic-token-authentication"],
86
+ )
87
+ )
88
+
89
+ if perms in ("write-all",) or (isinstance(perms, dict) and any(v == "write" for v in perms.values()) and untrusted):
90
+ pipeline.findings.append(
91
+ self._create_finding(
92
+ "GHA004",
93
+ "Over-broad GITHUB_TOKEN permissions",
94
+ "HIGH",
95
+ file_path,
96
+ self._find_line(lines, "permissions"),
97
+ "permissions: " + (perms if isinstance(perms, str) else "write scopes"),
98
+ "permissions",
99
+ "A write-capable token in a workflow reachable by untrusted input lets an attacker modify the repository.",
100
+ "Use least privilege (`contents: read`).",
101
+ )
102
+ )
103
+
104
+ # Parse jobs
105
+ for jname, job in raw_jobs.items():
106
+ if not isinstance(job, dict):
107
+ continue
108
+
109
+ ujob = UnifiedJob(name=jname)
110
+ runs_on = job.get("runs-on")
111
+ ro = " ".join(map(str, runs_on)) if isinstance(runs_on, list) else str(runs_on or "")
112
+ ujob.runs_on = ro
113
+
114
+ if "self-hosted" in ro and pr_trigger:
115
+ pipeline.findings.append(
116
+ self._create_finding(
117
+ "GHA006",
118
+ f"Job '{jname}' runs untrusted pull-request code on a self-hosted runner",
119
+ "HIGH",
120
+ file_path,
121
+ self._find_line(lines, "self-hosted"),
122
+ f"runs-on: {ro}",
123
+ jname,
124
+ "Self-hosted runners persist state and often have network access to internal systems; a malicious PR can pivot from them.",
125
+ "Use ephemeral GitHub-hosted runners for pull_request workflows, or require approval for outside contributors.",
126
+ )
127
+ )
128
+
129
+ if job.get("secrets") == "inherit":
130
+ pipeline.findings.append(
131
+ self._create_finding(
132
+ "GHA005",
133
+ f"Job '{jname}' passes all secrets to a reusable workflow",
134
+ "MEDIUM",
135
+ file_path,
136
+ self._find_line(lines, "secrets: inherit"),
137
+ "secrets: inherit",
138
+ jname,
139
+ "Every repository secret is exposed to the called workflow.",
140
+ "Pass only the specific secrets required.",
141
+ evidence_strength="medium",
142
+ )
143
+ )
144
+
145
+ # Reusable workflow
146
+ if isinstance(job.get("uses"), str):
147
+ ref = parse_action_ref(job["uses"])
148
+ if ref and ref.get("kind") == "action":
149
+ pipeline.external_dependencies.append(
150
+ {**ref, "file": file_path, "line": self._find_line(lines, job["uses"]), "job": jname, "reusable_workflow": True}
151
+ )
152
+
153
+ # Steps
154
+ steps = job.get("steps") or []
155
+ for st_ in steps:
156
+ if not isinstance(st_, dict):
157
+ continue
158
+
159
+ uses = st_.get("uses")
160
+ run = st_.get("run")
161
+ withd = st_.get("with") or {}
162
+
163
+ ustep = UnifiedStep(
164
+ name=st_.get("name", ""),
165
+ command=run if isinstance(run, str) else None,
166
+ uses=uses if isinstance(uses, str) else None,
167
+ with_args=withd if isinstance(withd, dict) else {},
168
+ )
169
+ ujob.steps.append(ustep)
170
+
171
+ # Process uses:
172
+ if isinstance(uses, str):
173
+ ref = parse_action_ref(uses)
174
+ ln = self._find_line(lines, uses)
175
+ if ref:
176
+ pipeline.external_dependencies.append({**ref, "file": file_path, "line": ln, "job": jname})
177
+
178
+ # Docker container used as action
179
+ if ref.get("kind") == "docker":
180
+ pipeline.container_images.append(
181
+ self._normalize_image_dict(uses.replace("docker://", ""), file_path, ln, jname)
182
+ )
183
+
184
+ if ref.get("kind") == "action" and not ref.get("pinned"):
185
+ branchy = ref["ref"] in ("main", "master", "latest", "develop", "dev", "trunk")
186
+ sev = "HIGH" if branchy else ("LOW" if ref.get("first_party") else "MEDIUM")
187
+ pipeline.findings.append(
188
+ self._create_finding(
189
+ "GHA001",
190
+ f"Action '{ref['name']}' is not pinned to a commit SHA",
191
+ sev,
192
+ file_path,
193
+ ln,
194
+ f"uses: {uses}",
195
+ uses,
196
+ ("The reference is a moving branch: " if branchy else "Tags can be moved or re-pointed: ")
197
+ + "a compromised upstream changes what your pipeline runs.",
198
+ f"Pin to the full 40-character commit SHA: `uses: {ref['name']}@<sha> # {ref['ref']}`.",
199
+ references=["https://docs.github.com/actions/security-guides/security-hardening-for-github-actions#using-third-party-actions"],
200
+ third_party=not ref.get("first_party"),
201
+ )
202
+ )
203
+
204
+ if ref.get("kind") == "action" and ref["name"].lower() in DEPRECATED_BELOW:
205
+ mm = re.match(r"^v?(\d+)", ref["ref"] or "")
206
+ if mm and int(mm.group(1)) < DEPRECATED_BELOW[ref["name"].lower()]:
207
+ pipeline.findings.append(
208
+ self._create_finding(
209
+ "GHA012",
210
+ f"Action '{ref['name']}@{ref['ref']}' is an outdated major version",
211
+ "MEDIUM",
212
+ file_path,
213
+ ln,
214
+ f"uses: {uses}",
215
+ uses + "#outdated",
216
+ "This major runs on an end-of-life Node.js runtime or was deprecated/shut down by GitHub.",
217
+ f"Upgrade to {ref['name']}@v{DEPRECATED_BELOW[ref['name'].lower()]} or newer.",
218
+ evidence_strength="medium",
219
+ )
220
+ )
221
+
222
+ # Check out of untrusted PR in privileged workflow
223
+ if "checkout" in uses:
224
+ r = str(withd.get("ref", ""))
225
+ if ("pull_request.head" in r or "head_ref" in r or "workflow_run.head" in r) and (
226
+ triggers_set & {"pull_request_target", "workflow_run"}
227
+ ):
228
+ pipeline.findings.append(
229
+ self._create_finding(
230
+ "GHA002",
231
+ f"Job '{jname}' checks out untrusted pull-request code in a privileged workflow",
232
+ "CRITICAL",
233
+ file_path,
234
+ self._find_line(lines, "ref:", max(ln - 1, 0)),
235
+ f"{', '.join(sorted(triggers_set & {'pull_request_target', 'workflow_run'}))} + checkout of PR head",
236
+ jname,
237
+ "Privileged workflows run with secrets and write tokens; checking out untrusted PR head allows arbitrary code execution.",
238
+ "Never check out PR head code in pull_request_target/workflow_run workflows.",
239
+ references=["https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/"],
240
+ )
241
+ )
242
+
243
+ # Extract docker/build-push-action
244
+ if "docker/build-push-action" in uses:
245
+ tags_raw = withd.get("tags") or withd.get("tag") or ""
246
+ first_tag = tags_raw.strip().splitlines()[0] if isinstance(tags_raw, str) and tags_raw.strip() else None
247
+ dfile = str(withd.get("file") or "Dockerfile")
248
+ ctx = str(withd.get("context") or ".")
249
+ target = str(withd.get("target")) if withd.get("target") else None
250
+ cdb = CIDockerBuild(
251
+ dockerfile_path=dfile,
252
+ context_path=ctx,
253
+ image_tag=first_tag,
254
+ target_stage=target,
255
+ builder_tool="docker/build-push-action",
256
+ ci_file=file_path,
257
+ ci_job=jname,
258
+ line=ln,
259
+ )
260
+ ujob.docker_builds.append(cdb)
261
+ pipeline.docker_builds.append(cdb)
262
+
263
+ # Process run:
264
+ if isinstance(run, str):
265
+ ln = self._find_line(lines, run.strip().splitlines()[0][:60]) if run.strip() else 1
266
+
267
+ # Script injection
268
+ for m in INJECTABLE.finditer(run):
269
+ if INJECTABLE_FIELDS.search(m.group(0)):
270
+ pipeline.findings.append(
271
+ self._create_finding(
272
+ "GHA003",
273
+ "Script injection: untrusted event data is expanded inside a `run` step",
274
+ "HIGH",
275
+ file_path,
276
+ ln,
277
+ m.group(0),
278
+ m.group(0),
279
+ "The expression is substituted into the shell script before execution, allowing shell command injection.",
280
+ 'Pass the value via environment variable (`env: VAL: ${{ ... }}`) and reference "$VAL".',
281
+ references=["https://securitylab.github.com/resources/github-actions-untrusted-input/"],
282
+ )
283
+ )
284
+ break
285
+
286
+ if PIPE_TO_SHELL.search(run):
287
+ pipeline.findings.append(
288
+ self._create_finding(
289
+ "GHA007",
290
+ "Remote script is piped into a shell in a workflow step",
291
+ "HIGH",
292
+ file_path,
293
+ ln,
294
+ run.strip().splitlines()[0],
295
+ "curl|sh",
296
+ "Runs whatever the remote server returns with the workflow's permissions and secrets.",
297
+ "Download, verify checksum/signature, then run.",
298
+ )
299
+ )
300
+
301
+ if INSECURE.search(run):
302
+ pipeline.findings.append(
303
+ self._create_finding(
304
+ "GHA008",
305
+ "TLS verification disabled in a workflow step",
306
+ "MEDIUM",
307
+ file_path,
308
+ ln,
309
+ run.strip().splitlines()[0],
310
+ "insecure",
311
+ "Allows tampering of downloaded tools and artifacts in transit.",
312
+ "Remove the insecure flag.",
313
+ )
314
+ )
315
+
316
+ if re.search(r"::(set-env|add-path)\b", run):
317
+ pipeline.findings.append(
318
+ self._create_finding(
319
+ "GHA009",
320
+ "Deprecated, injectable `set-env`/`add-path` workflow command",
321
+ "HIGH",
322
+ file_path,
323
+ ln,
324
+ run.strip().splitlines()[0],
325
+ "set-env",
326
+ "These commands were disabled because untrusted output can overwrite environment variables.",
327
+ "Write to $GITHUB_ENV or $GITHUB_PATH instead.",
328
+ )
329
+ )
330
+
331
+ if re.search(r"echo\s+[\"']?\$\{\{\s*secrets\.", run):
332
+ pipeline.findings.append(
333
+ self._create_finding(
334
+ "GHA010",
335
+ "A secret is echoed in a run step",
336
+ "MEDIUM",
337
+ file_path,
338
+ ln,
339
+ "echo ${{ secrets.* }}",
340
+ "secret echo",
341
+ "Secrets printed to logs can leak through build log retention or forks.",
342
+ "Never print secrets.",
343
+ evidence_strength="medium",
344
+ )
345
+ )
346
+
347
+ # Extract docker build CLI commands
348
+ builds = self._extract_docker_build_from_shell(run, file_path, jname, ln)
349
+ ujob.docker_builds.extend(builds)
350
+ pipeline.docker_builds.extend(builds)
351
+
352
+ pipeline.jobs[jname] = ujob
353
+
354
+ # Scan for committed secrets
355
+ pipeline.findings.extend(self._scan_secret_literals(lines, file_path))
356
+ return pipeline
@@ -0,0 +1,268 @@
1
+ """GitLab CI/CD pipeline adapter."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Any, Optional
6
+
7
+ import yaml
8
+
9
+ from pipeline_analysis.ci_adapters.base import BaseCIAdapter
10
+ from pipeline_analysis.ci_models import CIDockerBuild, UnifiedJob, UnifiedPipeline, UnifiedStep
11
+ from pipeline_analysis.dockerfile import INSECURE, PIPE_TO_SHELL
12
+ from pipeline_analysis.models import PipelineFinding
13
+
14
+ GITLAB_CI_RE = re.compile(r"(^|/)\.gitlab-ci\.ya?ml$", re.IGNORECASE)
15
+ RESERVED_TOP_KEYS = {
16
+ "stages",
17
+ "variables",
18
+ "include",
19
+ "default",
20
+ "workflow",
21
+ "image",
22
+ "services",
23
+ "before_script",
24
+ "after_script",
25
+ "cache",
26
+ "types",
27
+ }
28
+ UNTRUSTED_GITLAB_VARS = re.compile(
29
+ r"\$(?:\{)?(?:CI_MERGE_REQUEST_(?:TITLE|DESCRIPTION|SOURCE_BRANCH_NAME)|"
30
+ r"CI_COMMIT_(?:MESSAGE|TITLE|DESCRIPTION|TAG|REF_NAME)|CI_EXTERNAL_PULL_REQUEST_\w+)(?:\})?",
31
+ re.IGNORECASE,
32
+ )
33
+
34
+
35
+ class GitLabCIAdapter(BaseCIAdapter):
36
+ """Adapter for GitLab CI/CD pipelines (.gitlab-ci.yml)."""
37
+
38
+ @property
39
+ def platform_id(self) -> str:
40
+ return "gitlab_ci"
41
+
42
+ @property
43
+ def platform_name(self) -> str:
44
+ return "GitLab CI"
45
+
46
+ def can_handle(self, file_path: str) -> bool:
47
+ norm = file_path.replace("\\", "/")
48
+ return bool(GITLAB_CI_RE.search(norm))
49
+
50
+ def analyze(self, text: str, file_path: str) -> UnifiedPipeline:
51
+ pipeline = UnifiedPipeline(platform=self.platform_id, file_path=file_path)
52
+ lines = text.splitlines()
53
+
54
+ try:
55
+ data = yaml.safe_load(text)
56
+ except Exception as e:
57
+ pipeline.parse_success = False
58
+ pipeline.error_message = str(e)
59
+ return pipeline
60
+
61
+ if not isinstance(data, dict):
62
+ pipeline.parse_success = False
63
+ pipeline.error_message = "Root must be a YAML mapping"
64
+ return pipeline
65
+
66
+ pipeline.raw_parsed = data
67
+
68
+ # Stages
69
+ stages = data.get("stages")
70
+ if isinstance(stages, list):
71
+ pipeline.stages = [str(s) for s in stages]
72
+
73
+ # Top-level image and services
74
+ top_image = data.get("image")
75
+ if isinstance(top_image, (str, dict)):
76
+ raw_img = top_image if isinstance(top_image, str) else str(top_image.get("name", ""))
77
+ if raw_img and "$" not in raw_img:
78
+ ln = self._find_line(lines, "image:")
79
+ im_dict = self._normalize_image_dict(raw_img, file_path, ln, "global")
80
+ pipeline.container_images.append(im_dict)
81
+ if not im_dict.get("digest") and im_dict.get("tag") in (None, "latest"):
82
+ pipeline.findings.append(
83
+ self._create_finding(
84
+ "GL001",
85
+ "Default GitLab CI image is not pinned",
86
+ "MEDIUM",
87
+ file_path,
88
+ ln,
89
+ f"image: {raw_img}",
90
+ raw_img,
91
+ "Using an unpinned or latest tag allows unexpected upstream image changes.",
92
+ "Pin an explicit version tag and sha256 digest: `image: myimage:1.2.0@sha256:...`.",
93
+ )
94
+ )
95
+
96
+ # Include directives
97
+ includes = data.get("include")
98
+ if includes:
99
+ inc_list = includes if isinstance(includes, list) else [includes]
100
+ for inc in inc_list:
101
+ pipeline.external_dependencies.append({"kind": "include", "data": inc, "file": file_path})
102
+ if isinstance(inc, dict) and inc.get("remote"):
103
+ remote_url = str(inc["remote"])
104
+ if remote_url.startswith("http://"):
105
+ ln = self._find_line(lines, remote_url)
106
+ pipeline.findings.append(
107
+ self._create_finding(
108
+ "GL003",
109
+ "GitLab CI includes remote template over plain HTTP",
110
+ "HIGH",
111
+ file_path,
112
+ ln,
113
+ f"remote: {remote_url}",
114
+ "http-include",
115
+ "Unencrypted template downloads can be intercepted and modified in transit.",
116
+ "Change remote URL to use HTTPS and verify template integrity.",
117
+ )
118
+ )
119
+
120
+ # Iterate jobs
121
+ for key, val in data.items():
122
+ if key in RESERVED_TOP_KEYS or key.startswith("."):
123
+ continue
124
+ if not isinstance(val, dict):
125
+ continue
126
+
127
+ jname = key
128
+ ujob = UnifiedJob(name=jname, stage=str(val.get("stage", "default")))
129
+
130
+ # Job image
131
+ job_img = val.get("image")
132
+ if isinstance(job_img, (str, dict)):
133
+ raw_jimg = job_img if isinstance(job_img, str) else str(job_img.get("name", ""))
134
+ if raw_jimg and "$" not in raw_jimg:
135
+ ln = self._find_line(lines, raw_jimg)
136
+ im_dict = self._normalize_image_dict(raw_jimg, file_path, ln, jname)
137
+ pipeline.container_images.append(im_dict)
138
+ ujob.container_image = raw_jimg
139
+ if not im_dict.get("digest") and im_dict.get("tag") in (None, "latest"):
140
+ pipeline.findings.append(
141
+ self._create_finding(
142
+ "GL001",
143
+ f"Job '{jname}' uses an unpinned container image",
144
+ "MEDIUM",
145
+ file_path,
146
+ ln,
147
+ f"image: {raw_jimg}",
148
+ raw_jimg,
149
+ "Floating or latest tags may silently pull modified upstream layers.",
150
+ "Pin an explicit version and sha256 digest.",
151
+ )
152
+ )
153
+
154
+ # Services (e.g. docker:dind)
155
+ services = val.get("services") or []
156
+ if isinstance(services, list):
157
+ for s in services:
158
+ s_name = s if isinstance(s, str) else (s.get("name", "") if isinstance(s, dict) else "")
159
+ if s_name:
160
+ ujob.services.append(s_name)
161
+ ln = self._find_line(lines, s_name)
162
+ if "docker:dind" in s_name or (isinstance(s, dict) and s.get("privileged") is True):
163
+ pipeline.findings.append(
164
+ self._create_finding(
165
+ "GL002",
166
+ f"Job '{jname}' uses privileged Docker-in-Docker service",
167
+ "MEDIUM",
168
+ file_path,
169
+ ln,
170
+ f"services: {s_name}",
171
+ "docker:dind",
172
+ "Privileged DinD gives the container host-level capabilities, increasing the risk of container breakout.",
173
+ "Prefer rootless container build tools like Kaniko or Buildah.",
174
+ evidence_strength="medium",
175
+ )
176
+ )
177
+
178
+ # Scripts
179
+ script_blocks: list[str] = []
180
+ for field_name in ("before_script", "script", "after_script"):
181
+ cmds = val.get(field_name) or []
182
+ if isinstance(cmds, list):
183
+ for cmd in cmds:
184
+ if isinstance(cmd, str):
185
+ script_blocks.append(cmd)
186
+ ustep = UnifiedStep(name=f"{field_name}_step", command=cmd)
187
+ ujob.steps.append(ustep)
188
+ elif isinstance(cmds, str):
189
+ script_blocks.append(cmds)
190
+ ujob.steps.append(UnifiedStep(name=field_name, command=cmds))
191
+
192
+ combined_script = "\n".join(script_blocks)
193
+
194
+ # Check script-level rules
195
+ for cmd in script_blocks:
196
+ ln = self._find_line(lines, cmd[:60])
197
+
198
+ if PIPE_TO_SHELL.search(cmd):
199
+ pipeline.findings.append(
200
+ self._create_finding(
201
+ "GL004",
202
+ f"Remote script piped into shell in job '{jname}'",
203
+ "HIGH",
204
+ file_path,
205
+ ln,
206
+ cmd,
207
+ "curl|sh",
208
+ "Executes arbitrary remote script with the runner job's tokens and privileges.",
209
+ "Download to disk, verify a pinned cryptographic hash or signature, and execute.",
210
+ )
211
+ )
212
+
213
+ if INSECURE.search(cmd):
214
+ pipeline.findings.append(
215
+ self._create_finding(
216
+ "GL005",
217
+ f"TLS verification disabled in job '{jname}'",
218
+ "MEDIUM",
219
+ file_path,
220
+ ln,
221
+ cmd,
222
+ "insecure",
223
+ "Disabling TLS verification leaves network traffic open to man-in-the-middle tampering.",
224
+ "Remove `--insecure` or `GIT_SSL_NO_VERIFY` flags.",
225
+ )
226
+ )
227
+
228
+ for m in UNTRUSTED_GITLAB_VARS.finditer(cmd):
229
+ pipeline.findings.append(
230
+ self._create_finding(
231
+ "GL006",
232
+ f"Untrusted GitLab CI variable expanded directly in script in job '{jname}'",
233
+ "HIGH",
234
+ file_path,
235
+ ln,
236
+ cmd,
237
+ m.group(0),
238
+ "User-controlled merge request titles or commit messages expanded inside bash steps enable command injection.",
239
+ "Store the variable into an environment variable or escape it securely.",
240
+ )
241
+ )
242
+ break
243
+
244
+ if re.search(r"echo\s+.*CI_JOB_TOKEN", cmd, re.IGNORECASE):
245
+ pipeline.findings.append(
246
+ self._create_finding(
247
+ "GL007",
248
+ f"CI_JOB_TOKEN appears to be printed to logs in job '{jname}'",
249
+ "MEDIUM",
250
+ file_path,
251
+ ln,
252
+ cmd,
253
+ "token-echo",
254
+ "Printing job tokens to logs exposes them in build artifacts and job outputs.",
255
+ "Mask or omit token printing from shell scripts.",
256
+ )
257
+ )
258
+
259
+ # Extract Docker / Kaniko / Buildah builds
260
+ builds = self._extract_docker_build_from_shell(combined_script, file_path, jname)
261
+ ujob.docker_builds.extend(builds)
262
+ pipeline.docker_builds.extend(builds)
263
+
264
+ pipeline.jobs[jname] = ujob
265
+
266
+ # Scan for committed secrets
267
+ pipeline.findings.extend(self._scan_secret_literals(lines, file_path))
268
+ return pipeline