mulle-roam-code 0.0.1__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 (257) hide show
  1. mulle_roam_code-0.0.1.dist-info/METADATA +1590 -0
  2. mulle_roam_code-0.0.1.dist-info/RECORD +257 -0
  3. mulle_roam_code-0.0.1.dist-info/WHEEL +5 -0
  4. mulle_roam_code-0.0.1.dist-info/entry_points.txt +3 -0
  5. mulle_roam_code-0.0.1.dist-info/licenses/LICENSE +21 -0
  6. mulle_roam_code-0.0.1.dist-info/top_level.txt +1 -0
  7. roam/__init__.py +8 -0
  8. roam/__main__.py +5 -0
  9. roam/analysis/__init__.py +1 -0
  10. roam/analysis/effects.py +639 -0
  11. roam/analysis/taint.py +689 -0
  12. roam/api.py +238 -0
  13. roam/bridges/__init__.py +3 -0
  14. roam/bridges/base.py +49 -0
  15. roam/bridges/bridge_config.py +218 -0
  16. roam/bridges/bridge_protobuf.py +352 -0
  17. roam/bridges/bridge_rest_api.py +242 -0
  18. roam/bridges/bridge_salesforce.py +198 -0
  19. roam/bridges/bridge_template.py +247 -0
  20. roam/bridges/registry.py +51 -0
  21. roam/catalog/__init__.py +0 -0
  22. roam/catalog/detectors.py +2242 -0
  23. roam/catalog/fixes.py +86 -0
  24. roam/catalog/smells.py +599 -0
  25. roam/catalog/tasks.py +1260 -0
  26. roam/cli.py +548 -0
  27. roam/commands/__init__.py +0 -0
  28. roam/commands/changed_files.py +139 -0
  29. roam/commands/cmd_adversarial.py +699 -0
  30. roam/commands/cmd_affected.py +432 -0
  31. roam/commands/cmd_affected_tests.py +375 -0
  32. roam/commands/cmd_agent_context.py +168 -0
  33. roam/commands/cmd_agent_export.py +890 -0
  34. roam/commands/cmd_agent_plan.py +315 -0
  35. roam/commands/cmd_ai_ratio.py +765 -0
  36. roam/commands/cmd_ai_readiness.py +775 -0
  37. roam/commands/cmd_alerts.py +409 -0
  38. roam/commands/cmd_annotate.py +210 -0
  39. roam/commands/cmd_api_changes.py +796 -0
  40. roam/commands/cmd_api_drift.py +781 -0
  41. roam/commands/cmd_attest.py +913 -0
  42. roam/commands/cmd_auth_gaps.py +799 -0
  43. roam/commands/cmd_bisect.py +216 -0
  44. roam/commands/cmd_breaking.py +464 -0
  45. roam/commands/cmd_budget.py +413 -0
  46. roam/commands/cmd_bus_factor.py +403 -0
  47. roam/commands/cmd_capsule.py +275 -0
  48. roam/commands/cmd_check_rules.py +574 -0
  49. roam/commands/cmd_clean.py +147 -0
  50. roam/commands/cmd_closure.py +294 -0
  51. roam/commands/cmd_clusters.py +457 -0
  52. roam/commands/cmd_codeowners.py +600 -0
  53. roam/commands/cmd_complexity.py +364 -0
  54. roam/commands/cmd_config.py +310 -0
  55. roam/commands/cmd_context.py +1151 -0
  56. roam/commands/cmd_conventions.py +697 -0
  57. roam/commands/cmd_coupling.py +462 -0
  58. roam/commands/cmd_coverage_gaps.py +638 -0
  59. roam/commands/cmd_cut.py +235 -0
  60. roam/commands/cmd_dark_matter.py +127 -0
  61. roam/commands/cmd_dashboard.py +365 -0
  62. roam/commands/cmd_dead.py +1585 -0
  63. roam/commands/cmd_debt.py +731 -0
  64. roam/commands/cmd_deps.py +121 -0
  65. roam/commands/cmd_describe.py +959 -0
  66. roam/commands/cmd_dev_profile.py +580 -0
  67. roam/commands/cmd_diagnose.py +377 -0
  68. roam/commands/cmd_diff.py +633 -0
  69. roam/commands/cmd_digest.py +214 -0
  70. roam/commands/cmd_doc_staleness.py +334 -0
  71. roam/commands/cmd_docs_coverage.py +193 -0
  72. roam/commands/cmd_doctor.py +319 -0
  73. roam/commands/cmd_drift.py +377 -0
  74. roam/commands/cmd_duplicates.py +559 -0
  75. roam/commands/cmd_effects.py +362 -0
  76. roam/commands/cmd_endpoints.py +768 -0
  77. roam/commands/cmd_entry_points.py +358 -0
  78. roam/commands/cmd_fan.py +311 -0
  79. roam/commands/cmd_file.py +334 -0
  80. roam/commands/cmd_fingerprint.py +172 -0
  81. roam/commands/cmd_fitness.py +723 -0
  82. roam/commands/cmd_fn_coupling.py +295 -0
  83. roam/commands/cmd_forecast.py +366 -0
  84. roam/commands/cmd_grep.py +282 -0
  85. roam/commands/cmd_guard.py +434 -0
  86. roam/commands/cmd_health.py +922 -0
  87. roam/commands/cmd_hooks.py +458 -0
  88. roam/commands/cmd_hotspots.py +606 -0
  89. roam/commands/cmd_impact.py +228 -0
  90. roam/commands/cmd_index.py +102 -0
  91. roam/commands/cmd_ingest_trace.py +143 -0
  92. roam/commands/cmd_init.py +166 -0
  93. roam/commands/cmd_intent.py +459 -0
  94. roam/commands/cmd_invariants.py +301 -0
  95. roam/commands/cmd_layers.py +387 -0
  96. roam/commands/cmd_map.py +275 -0
  97. roam/commands/cmd_math.py +213 -0
  98. roam/commands/cmd_mcp_setup.py +135 -0
  99. roam/commands/cmd_metrics.py +663 -0
  100. roam/commands/cmd_migration_safety.py +712 -0
  101. roam/commands/cmd_minimap.py +519 -0
  102. roam/commands/cmd_missing_index.py +885 -0
  103. roam/commands/cmd_module.py +204 -0
  104. roam/commands/cmd_mutate.py +400 -0
  105. roam/commands/cmd_n1.py +967 -0
  106. roam/commands/cmd_onboard.py +740 -0
  107. roam/commands/cmd_orchestrate.py +180 -0
  108. roam/commands/cmd_orphan_routes.py +754 -0
  109. roam/commands/cmd_over_fetch.py +633 -0
  110. roam/commands/cmd_owner.py +299 -0
  111. roam/commands/cmd_partition.py +714 -0
  112. roam/commands/cmd_path_coverage.py +564 -0
  113. roam/commands/cmd_patterns.py +689 -0
  114. roam/commands/cmd_plan.py +616 -0
  115. roam/commands/cmd_plan_refactor.py +432 -0
  116. roam/commands/cmd_pr_diff.py +292 -0
  117. roam/commands/cmd_pr_risk.py +677 -0
  118. roam/commands/cmd_preflight.py +706 -0
  119. roam/commands/cmd_relate.py +405 -0
  120. roam/commands/cmd_report.py +304 -0
  121. roam/commands/cmd_reset.py +117 -0
  122. roam/commands/cmd_risk.py +533 -0
  123. roam/commands/cmd_rules.py +319 -0
  124. roam/commands/cmd_safe_delete.py +224 -0
  125. roam/commands/cmd_safe_zones.py +295 -0
  126. roam/commands/cmd_schema.py +166 -0
  127. roam/commands/cmd_search.py +295 -0
  128. roam/commands/cmd_search_semantic.py +101 -0
  129. roam/commands/cmd_secrets.py +636 -0
  130. roam/commands/cmd_semantic_diff.py +538 -0
  131. roam/commands/cmd_simulate.py +296 -0
  132. roam/commands/cmd_simulate_departure.py +632 -0
  133. roam/commands/cmd_sketch.py +160 -0
  134. roam/commands/cmd_smells.py +179 -0
  135. roam/commands/cmd_snapshot.py +50 -0
  136. roam/commands/cmd_spectral.py +183 -0
  137. roam/commands/cmd_split.py +432 -0
  138. roam/commands/cmd_suggest_refactoring.py +486 -0
  139. roam/commands/cmd_suggest_reviewers.py +491 -0
  140. roam/commands/cmd_supply_chain.py +831 -0
  141. roam/commands/cmd_symbol.py +135 -0
  142. roam/commands/cmd_syntax_check.py +301 -0
  143. roam/commands/cmd_test_gaps.py +574 -0
  144. roam/commands/cmd_testmap.py +308 -0
  145. roam/commands/cmd_tour.py +377 -0
  146. roam/commands/cmd_trace.py +304 -0
  147. roam/commands/cmd_trend.py +461 -0
  148. roam/commands/cmd_trends.py +929 -0
  149. roam/commands/cmd_understand.py +763 -0
  150. roam/commands/cmd_uses.py +170 -0
  151. roam/commands/cmd_verify.py +812 -0
  152. roam/commands/cmd_verify_imports.py +435 -0
  153. roam/commands/cmd_vibe_check.py +932 -0
  154. roam/commands/cmd_visualize.py +361 -0
  155. roam/commands/cmd_vuln_map.py +139 -0
  156. roam/commands/cmd_vuln_reach.py +289 -0
  157. roam/commands/cmd_vulns.py +414 -0
  158. roam/commands/cmd_watch.py +759 -0
  159. roam/commands/cmd_weather.py +118 -0
  160. roam/commands/cmd_why.py +325 -0
  161. roam/commands/cmd_ws.py +755 -0
  162. roam/commands/cmd_xlang.py +170 -0
  163. roam/commands/context_helpers.py +1137 -0
  164. roam/commands/gate_presets.py +222 -0
  165. roam/commands/graph_helpers.py +93 -0
  166. roam/commands/metrics_history.py +298 -0
  167. roam/commands/next_steps.py +107 -0
  168. roam/commands/resolve.py +302 -0
  169. roam/competitor_site_data.py +2229 -0
  170. roam/coverage_reports.py +462 -0
  171. roam/db/__init__.py +0 -0
  172. roam/db/connection.py +359 -0
  173. roam/db/queries.py +151 -0
  174. roam/db/schema.py +335 -0
  175. roam/exit_codes.py +100 -0
  176. roam/graph/__init__.py +43 -0
  177. roam/graph/anomaly.py +493 -0
  178. roam/graph/builder.py +61 -0
  179. roam/graph/clusters.py +286 -0
  180. roam/graph/cycles.py +210 -0
  181. roam/graph/dark_matter.py +207 -0
  182. roam/graph/diff.py +467 -0
  183. roam/graph/fingerprint.py +297 -0
  184. roam/graph/layers.py +134 -0
  185. roam/graph/pagerank.py +171 -0
  186. roam/graph/partition.py +437 -0
  187. roam/graph/pathfinding.py +119 -0
  188. roam/graph/propagation.py +208 -0
  189. roam/graph/simulate.py +286 -0
  190. roam/graph/spectral.py +260 -0
  191. roam/index/__init__.py +5 -0
  192. roam/index/complexity.py +1108 -0
  193. roam/index/discovery.py +338 -0
  194. roam/index/file_roles.py +586 -0
  195. roam/index/git_stats.py +577 -0
  196. roam/index/incremental.py +75 -0
  197. roam/index/indexer.py +1191 -0
  198. roam/index/parser.py +461 -0
  199. roam/index/relations.py +537 -0
  200. roam/index/symbols.py +71 -0
  201. roam/index/test_conventions.py +508 -0
  202. roam/languages/__init__.py +21 -0
  203. roam/languages/apex_lang.py +241 -0
  204. roam/languages/aura_lang.py +228 -0
  205. roam/languages/base.py +111 -0
  206. roam/languages/c_lang.py +458 -0
  207. roam/languages/csharp_lang.py +1215 -0
  208. roam/languages/foxpro_lang.py +1554 -0
  209. roam/languages/generic_lang.py +702 -0
  210. roam/languages/go_lang.py +392 -0
  211. roam/languages/hcl_lang.py +398 -0
  212. roam/languages/java_lang.py +418 -0
  213. roam/languages/javascript_lang.py +799 -0
  214. roam/languages/kotlin_lang.py +147 -0
  215. roam/languages/objc_lang.py +401 -0
  216. roam/languages/php_lang.py +696 -0
  217. roam/languages/python_lang.py +850 -0
  218. roam/languages/registry.py +283 -0
  219. roam/languages/ruby_lang.py +429 -0
  220. roam/languages/rust_lang.py +545 -0
  221. roam/languages/sfxml_lang.py +276 -0
  222. roam/languages/swift_lang.py +173 -0
  223. roam/languages/typescript_lang.py +323 -0
  224. roam/languages/visualforce_lang.py +151 -0
  225. roam/languages/yaml_lang.py +566 -0
  226. roam/mcp_server.py +4794 -0
  227. roam/output/__init__.py +0 -0
  228. roam/output/formatter.py +557 -0
  229. roam/output/mermaid.py +62 -0
  230. roam/output/sarif.py +897 -0
  231. roam/output/schema_registry.py +57 -0
  232. roam/plugins.py +208 -0
  233. roam/refactor/__init__.py +0 -0
  234. roam/refactor/codegen.py +106 -0
  235. roam/refactor/transforms.py +711 -0
  236. roam/rules/__init__.py +0 -0
  237. roam/rules/ast_match.py +238 -0
  238. roam/rules/builtin.py +617 -0
  239. roam/rules/dataflow.py +515 -0
  240. roam/rules/engine.py +943 -0
  241. roam/runtime/__init__.py +3 -0
  242. roam/runtime/hotspots.py +138 -0
  243. roam/runtime/trace_ingest.py +535 -0
  244. roam/search/__init__.py +1 -0
  245. roam/search/framework_packs.py +673 -0
  246. roam/search/index_embeddings.py +732 -0
  247. roam/search/onnx_embeddings.py +233 -0
  248. roam/search/tfidf.py +355 -0
  249. roam/security/__init__.py +1 -0
  250. roam/security/vuln_reach.py +246 -0
  251. roam/security/vuln_store.py +334 -0
  252. roam/surface_counts.py +158 -0
  253. roam/workspace/__init__.py +3 -0
  254. roam/workspace/aggregator.py +426 -0
  255. roam/workspace/api_scanner.py +538 -0
  256. roam/workspace/config.py +95 -0
  257. roam/workspace/db.py +136 -0
roam/analysis/taint.py ADDED
@@ -0,0 +1,689 @@
1
+ """Inter-procedural taint analysis for roam-code.
2
+
3
+ Computes per-function taint summaries (which parameters flow to return
4
+ values or dangerous sinks) and then propagates those summaries across
5
+ the call graph to find cross-function source-to-sink flows.
6
+
7
+ The analysis is deliberately lightweight: intra-procedural tracking is
8
+ line-by-line string matching (no full SSA), while inter-procedural
9
+ propagation walks call-graph edges up to a configurable depth.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Data structures
21
+ # ---------------------------------------------------------------------------
22
+
23
+
24
+ @dataclass
25
+ class TaintSummary:
26
+ """Per-function summary of taint flow behaviour."""
27
+
28
+ symbol_id: int
29
+ param_taints_return: dict[int, bool] = field(default_factory=dict)
30
+ param_to_sink: dict[int, list[str]] = field(default_factory=dict)
31
+ return_from_source: bool = False
32
+ direct_sources: list[str] = field(default_factory=list)
33
+ direct_sinks: list[str] = field(default_factory=list)
34
+ is_sanitizer: bool = False
35
+
36
+
37
+ @dataclass
38
+ class TaintFinding:
39
+ """A cross-function taint finding: source flows to sink across calls."""
40
+
41
+ source_symbol_id: int
42
+ sink_symbol_id: int
43
+ source_type: str
44
+ sink_type: str
45
+ call_chain: list[int] = field(default_factory=list)
46
+ confidence: float = 0.8
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Default source / sink / sanitizer patterns
51
+ # ---------------------------------------------------------------------------
52
+
53
+ _DEFAULT_SOURCES = (
54
+ "input(",
55
+ "request.args",
56
+ "request.form",
57
+ "request.get",
58
+ "request.GET",
59
+ "request.POST",
60
+ "sys.argv",
61
+ "os.environ",
62
+ "query_params",
63
+ "params.get",
64
+ "req.body",
65
+ "req.params",
66
+ "req.query",
67
+ "document.location",
68
+ "window.location",
69
+ "process.env",
70
+ "Scanner(System.in",
71
+ "BufferedReader(",
72
+ "getParameter(",
73
+ "getQueryString(",
74
+ "getHeader(",
75
+ )
76
+
77
+ _DEFAULT_SINKS = (
78
+ "eval(",
79
+ "exec(",
80
+ "os.system(",
81
+ "subprocess.run(",
82
+ "subprocess.popen(",
83
+ "pickle.loads(",
84
+ "yaml.load(",
85
+ "Function(",
86
+ "innerHTML",
87
+ "document.write(",
88
+ "cursor.execute(",
89
+ ".execute(",
90
+ "render_template_string(",
91
+ "send_file(",
92
+ "redirect(",
93
+ "open(",
94
+ "Runtime.exec(",
95
+ "ProcessBuilder(",
96
+ "child_process.exec(",
97
+ "shell_exec(",
98
+ )
99
+
100
+ _SANITIZER_NAMES = frozenset(
101
+ {
102
+ "escape",
103
+ "sanitize",
104
+ "validate",
105
+ "encode",
106
+ "clean",
107
+ "filter",
108
+ "strip",
109
+ "purify",
110
+ "quote",
111
+ "parameterize",
112
+ "bleach",
113
+ "markupsafe",
114
+ "html_escape",
115
+ "urlencode",
116
+ "escape_string",
117
+ "sqlquote",
118
+ }
119
+ )
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # Helpers
123
+ # ---------------------------------------------------------------------------
124
+
125
+ _IDENT_RE = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\b")
126
+
127
+ _ASSIGN_PATTERNS = (
128
+ re.compile(r"^\s*(?:let|const|var)\s+([A-Za-z_][A-Za-z0-9_]*)\s*="),
129
+ re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(?!=)"),
130
+ re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*[\+\-\*/%]="),
131
+ )
132
+
133
+ _IGNORED_PARAMS = {"_", "self", "cls", "this"}
134
+
135
+
136
+ def _detect_sanitizer(name: str, qualified_name: str | None = None) -> bool:
137
+ """Return True if the symbol name suggests a sanitizer function."""
138
+ lower = (name or "").lower()
139
+ qn = (qualified_name or "").lower()
140
+ return any(s in lower or s in qn for s in _SANITIZER_NAMES)
141
+
142
+
143
+ def _parse_param_names(signature: str | None) -> list[str]:
144
+ """Extract parameter names from a signature string like ``def foo(a, b=1)``."""
145
+ if not signature:
146
+ return []
147
+ m = re.search(r"\(([^)]*)\)", signature)
148
+ if not m:
149
+ return []
150
+ params_str = m.group(1).strip()
151
+ if not params_str:
152
+ return []
153
+
154
+ depth = 0
155
+ current: list[str] = []
156
+ parts: list[str] = []
157
+ for ch in params_str:
158
+ if ch in "([{<":
159
+ depth += 1
160
+ current.append(ch)
161
+ elif ch in ")]}>":
162
+ depth -= 1
163
+ current.append(ch)
164
+ elif ch == "," and depth == 0:
165
+ parts.append("".join(current).strip())
166
+ current = []
167
+ else:
168
+ current.append(ch)
169
+ if current:
170
+ parts.append("".join(current).strip())
171
+
172
+ names: list[str] = []
173
+ for part in parts:
174
+ token = part
175
+ while token.startswith("*"):
176
+ token = token[1:]
177
+ token = token.split(":", 1)[0].split("=", 1)[0].strip()
178
+ if token and token not in _IGNORED_PARAMS:
179
+ names.append(token)
180
+ return names
181
+
182
+
183
+ def _read_body_lines(conn, symbol_id: int, project_root: Path) -> tuple[list[str], str | None, int]:
184
+ """Read body lines for a symbol from disk.
185
+
186
+ Returns ``(body_lines, signature, line_start)`` where *body_lines*
187
+ excludes the declaration line itself.
188
+ """
189
+ row = conn.execute(
190
+ """
191
+ SELECT s.line_start, s.line_end, s.signature,
192
+ f.path AS file_path
193
+ FROM symbols s
194
+ JOIN files f ON s.file_id = f.id
195
+ WHERE s.id = ?
196
+ """,
197
+ (symbol_id,),
198
+ ).fetchone()
199
+ if row is None:
200
+ return [], None, 0
201
+
202
+ ls = row["line_start"] or 1
203
+ le = row["line_end"] or ls
204
+ rel_path = row["file_path"] or ""
205
+ full_path = project_root / rel_path
206
+ try:
207
+ text = full_path.read_text(encoding="utf-8", errors="replace")
208
+ except Exception:
209
+ return [], row["signature"], ls
210
+
211
+ all_lines = text.splitlines()
212
+ # body_lines: everything after declaration line
213
+ body = all_lines[ls : min(le, len(all_lines))]
214
+ return body, row["signature"], ls
215
+
216
+
217
+ # ---------------------------------------------------------------------------
218
+ # Intra-procedural variable taint tracking
219
+ # ---------------------------------------------------------------------------
220
+
221
+
222
+ def _track_variable_taint(
223
+ body_lines: list[str],
224
+ param_names: list[str],
225
+ sources: tuple[str, ...],
226
+ sinks: tuple[str, ...],
227
+ sanitizer_names: frozenset[str],
228
+ ) -> dict:
229
+ """Line-by-line variable taint tracking within a single function.
230
+
231
+ Returns a dict with keys:
232
+ param_taints_return: {param_idx: True/False}
233
+ param_to_sink: {param_idx: [sink_pattern, ...]}
234
+ return_from_source: bool
235
+ direct_sources: [source_pattern, ...]
236
+ direct_sinks: [sink_pattern, ...]
237
+ """
238
+ # tainted_vars maps variable name -> set of taint origins
239
+ # An origin is either ("param", idx) or ("source", pattern_str)
240
+ tainted_vars: dict[str, set[tuple[str, int | str]]] = {}
241
+
242
+ # Initialise params as tainted
243
+ for idx, pname in enumerate(param_names):
244
+ tainted_vars[pname] = {("param", idx)}
245
+
246
+ param_taints_return: dict[int, bool] = {}
247
+ param_to_sink: dict[int, list[str]] = {}
248
+ return_from_source = False
249
+ found_sources: list[str] = []
250
+ found_sinks: list[str] = []
251
+
252
+ for raw_line in body_lines:
253
+ line = raw_line.strip()
254
+ line_lower = line.lower()
255
+
256
+ # ---- Check for sanitizer calls clearing taint ----
257
+ is_sanitize_line = False
258
+ for sname in sanitizer_names:
259
+ if sname in line_lower:
260
+ is_sanitize_line = True
261
+ break
262
+
263
+ # ---- Check for assignment ----
264
+ assigned_var: str | None = None
265
+ for pat in _ASSIGN_PATTERNS:
266
+ m = pat.search(line)
267
+ if m:
268
+ assigned_var = m.group(1).strip()
269
+ break
270
+
271
+ # ---- Determine taint of the right-hand side ----
272
+ rhs = line
273
+ if assigned_var and "=" in rhs:
274
+ eq_idx = rhs.index("=")
275
+ rhs = rhs[eq_idx + 1 :]
276
+
277
+ rhs_taint: set[tuple[str, int | str]] = set()
278
+
279
+ # Check if RHS references a source
280
+ for src in sources:
281
+ if src.lower() in rhs.lower():
282
+ rhs_taint.add(("source", src))
283
+ if src not in found_sources:
284
+ found_sources.append(src)
285
+ break
286
+
287
+ # Check if RHS references tainted variables
288
+ rhs_idents = set(_IDENT_RE.findall(rhs))
289
+ for ident in rhs_idents:
290
+ if ident in tainted_vars:
291
+ rhs_taint.update(tainted_vars[ident])
292
+
293
+ # If this is a sanitizer call, kill the taint
294
+ if is_sanitize_line and assigned_var:
295
+ tainted_vars.pop(assigned_var, None)
296
+ elif assigned_var and rhs_taint:
297
+ tainted_vars[assigned_var] = rhs_taint
298
+ elif assigned_var:
299
+ # Clean assignment — clear any previous taint
300
+ tainted_vars.pop(assigned_var, None)
301
+
302
+ # ---- Check return statements ----
303
+ if line.startswith("return ") or line == "return":
304
+ return_idents = set(_IDENT_RE.findall(line[6:]))
305
+ for ident in return_idents:
306
+ if ident in tainted_vars:
307
+ for origin in tainted_vars[ident]:
308
+ if origin[0] == "param":
309
+ param_taints_return[origin[1]] = True
310
+ elif origin[0] == "source":
311
+ return_from_source = True
312
+
313
+ # ---- Check sink calls ----
314
+ for sink in sinks:
315
+ if sink.lower() in line_lower:
316
+ if sink not in found_sinks:
317
+ found_sinks.append(sink)
318
+ # Find tainted args flowing into this sink
319
+ sink_idents = set(_IDENT_RE.findall(line))
320
+ for ident in sink_idents:
321
+ if ident in tainted_vars:
322
+ for origin in tainted_vars[ident]:
323
+ if origin[0] == "param":
324
+ pidx = origin[1]
325
+ if pidx not in param_to_sink:
326
+ param_to_sink[pidx] = []
327
+ if sink not in param_to_sink[pidx]:
328
+ param_to_sink[pidx].append(sink)
329
+ break
330
+
331
+ return {
332
+ "param_taints_return": param_taints_return,
333
+ "param_to_sink": param_to_sink,
334
+ "return_from_source": return_from_source,
335
+ "direct_sources": found_sources,
336
+ "direct_sinks": found_sinks,
337
+ }
338
+
339
+
340
+ def compute_intra_summary(
341
+ conn,
342
+ symbol_id: int,
343
+ body_lines: list[str],
344
+ signature: str | None,
345
+ param_names: list[str],
346
+ sources: tuple[str, ...],
347
+ sinks: tuple[str, ...],
348
+ ) -> TaintSummary:
349
+ """Compute intra-procedural taint summary for a single symbol."""
350
+ # Fetch name for sanitizer detection
351
+ row = conn.execute(
352
+ "SELECT name, qualified_name FROM symbols WHERE id = ?",
353
+ (symbol_id,),
354
+ ).fetchone()
355
+ sym_name = row["name"] if row else ""
356
+ sym_qname = row["qualified_name"] if row else None
357
+
358
+ is_sanitizer = _detect_sanitizer(sym_name, sym_qname)
359
+
360
+ if not body_lines:
361
+ return TaintSummary(
362
+ symbol_id=symbol_id,
363
+ is_sanitizer=is_sanitizer,
364
+ )
365
+
366
+ result = _track_variable_taint(
367
+ body_lines,
368
+ param_names,
369
+ sources,
370
+ sinks,
371
+ _SANITIZER_NAMES,
372
+ )
373
+
374
+ return TaintSummary(
375
+ symbol_id=symbol_id,
376
+ param_taints_return=result["param_taints_return"],
377
+ param_to_sink=result["param_to_sink"],
378
+ return_from_source=result["return_from_source"],
379
+ direct_sources=result["direct_sources"],
380
+ direct_sinks=result["direct_sinks"],
381
+ is_sanitizer=is_sanitizer,
382
+ )
383
+
384
+
385
+ # ---------------------------------------------------------------------------
386
+ # Batch intra-procedural analysis
387
+ # ---------------------------------------------------------------------------
388
+
389
+
390
+ def compute_all_summaries(
391
+ conn,
392
+ root: Path,
393
+ *,
394
+ sources: tuple[str, ...] | None = None,
395
+ sinks: tuple[str, ...] | None = None,
396
+ ) -> dict[int, TaintSummary]:
397
+ """Compute intra-procedural taint summaries for all functions/methods."""
398
+ src = sources or _DEFAULT_SOURCES
399
+ snk = sinks or _DEFAULT_SINKS
400
+
401
+ rows = conn.execute(
402
+ """
403
+ SELECT s.id, s.signature, s.line_start, s.line_end,
404
+ s.name, s.qualified_name,
405
+ f.path AS file_path
406
+ FROM symbols s
407
+ JOIN files f ON s.file_id = f.id
408
+ WHERE s.kind IN ('function', 'method', 'constructor')
409
+ AND s.line_start IS NOT NULL
410
+ AND s.line_end IS NOT NULL
411
+ ORDER BY f.path, s.line_start
412
+ """
413
+ ).fetchall()
414
+
415
+ summaries: dict[int, TaintSummary] = {}
416
+ file_cache: dict[str, list[str]] = {}
417
+
418
+ for row in rows:
419
+ sym_id = row["id"]
420
+ rel_path = row["file_path"] or ""
421
+ ls = row["line_start"] or 1
422
+ le = row["line_end"] or ls
423
+ signature = row["signature"]
424
+ sym_name = row["name"] or ""
425
+ sym_qname = row["qualified_name"]
426
+
427
+ # Read file (cached)
428
+ all_lines = file_cache.get(rel_path)
429
+ if all_lines is None:
430
+ full_path = root / rel_path
431
+ try:
432
+ text = full_path.read_text(encoding="utf-8", errors="replace")
433
+ except Exception:
434
+ all_lines = []
435
+ else:
436
+ all_lines = text.splitlines()
437
+ file_cache[rel_path] = all_lines
438
+
439
+ # Body lines (after declaration line)
440
+ body = all_lines[ls : min(le, len(all_lines))] if all_lines else []
441
+
442
+ param_names = _parse_param_names(signature)
443
+ is_sanitizer = _detect_sanitizer(sym_name, sym_qname)
444
+
445
+ if not body:
446
+ summaries[sym_id] = TaintSummary(symbol_id=sym_id, is_sanitizer=is_sanitizer)
447
+ continue
448
+
449
+ result = _track_variable_taint(body, param_names, src, snk, _SANITIZER_NAMES)
450
+
451
+ summaries[sym_id] = TaintSummary(
452
+ symbol_id=sym_id,
453
+ param_taints_return=result["param_taints_return"],
454
+ param_to_sink=result["param_to_sink"],
455
+ return_from_source=result["return_from_source"],
456
+ direct_sources=result["direct_sources"],
457
+ direct_sinks=result["direct_sinks"],
458
+ is_sanitizer=is_sanitizer,
459
+ )
460
+
461
+ return summaries
462
+
463
+
464
+ # ---------------------------------------------------------------------------
465
+ # Inter-procedural propagation
466
+ # ---------------------------------------------------------------------------
467
+
468
+
469
+ def propagate_taint(
470
+ conn,
471
+ summaries: dict[int, TaintSummary],
472
+ G,
473
+ *,
474
+ max_depth: int = 5,
475
+ ) -> list[TaintFinding]:
476
+ """Propagate taint across call-graph edges.
477
+
478
+ For each call edge (caller -> callee):
479
+ - If caller passes a tainted arg to callee and callee.param_to_sink[i]
480
+ exists, record a cross-function finding.
481
+ - If callee.param_taints_return[i], the call result inherits taint.
482
+ - If callee is a sanitizer, taint dies.
483
+ """
484
+ # Build adjacency from edges table for call edges
485
+ call_edges: dict[int, list[int]] = {}
486
+ rows = conn.execute("SELECT source_id, target_id FROM edges WHERE kind = 'calls'").fetchall()
487
+ for row in rows:
488
+ src = row["source_id"]
489
+ tgt = row["target_id"]
490
+ call_edges.setdefault(src, []).append(tgt)
491
+
492
+ findings: list[TaintFinding] = []
493
+ visited_pairs: set[tuple[int, int, int]] = set() # (source_sym, sink_sym, depth)
494
+
495
+ def _propagate(
496
+ origin_sym: int,
497
+ current_sym: int,
498
+ taint_origins: set[tuple[str, int | str]],
499
+ chain: list[int],
500
+ depth: int,
501
+ ):
502
+ if depth > max_depth:
503
+ return
504
+
505
+ callees = call_edges.get(current_sym, [])
506
+ for callee_id in callees:
507
+ callee_summary = summaries.get(callee_id)
508
+ if callee_summary is None:
509
+ continue
510
+
511
+ # If callee is a sanitizer, taint dies
512
+ if callee_summary.is_sanitizer:
513
+ continue
514
+
515
+ new_chain = chain + [callee_id]
516
+ pair_key = (origin_sym, callee_id, depth)
517
+ if pair_key in visited_pairs:
518
+ continue
519
+ visited_pairs.add(pair_key)
520
+
521
+ # Check if any taint origin is a param that flows to a sink
522
+ # in the callee (simplified: we assume arg position matches
523
+ # the taint origin param index for direct calls)
524
+ for origin in taint_origins:
525
+ if origin[0] == "param":
526
+ pidx = origin[1]
527
+ sinks_hit = callee_summary.param_to_sink.get(pidx, [])
528
+ for sink in sinks_hit:
529
+ # Get source info from the origin symbol
530
+ origin_summary = summaries.get(origin_sym)
531
+ source_type = "param"
532
+ if origin_summary and origin_summary.direct_sources:
533
+ source_type = origin_summary.direct_sources[0]
534
+ findings.append(
535
+ TaintFinding(
536
+ source_symbol_id=origin_sym,
537
+ sink_symbol_id=callee_id,
538
+ source_type=source_type,
539
+ sink_type=sink,
540
+ call_chain=[origin_sym] + new_chain,
541
+ confidence=max(0.3, 0.9 - 0.1 * depth),
542
+ )
543
+ )
544
+ elif origin[0] == "source":
545
+ # A source-tainted value is passed to callee
546
+ for pidx, sinks_hit in callee_summary.param_to_sink.items():
547
+ for sink in sinks_hit:
548
+ findings.append(
549
+ TaintFinding(
550
+ source_symbol_id=origin_sym,
551
+ sink_symbol_id=callee_id,
552
+ source_type=str(origin[1]),
553
+ sink_type=sink,
554
+ call_chain=[origin_sym] + new_chain,
555
+ confidence=max(0.3, 0.9 - 0.1 * depth),
556
+ )
557
+ )
558
+
559
+ # Propagate through callee if it returns tainted data
560
+ returned_taint: set[tuple[str, int | str]] = set()
561
+ for origin in taint_origins:
562
+ if origin[0] == "param":
563
+ pidx = origin[1]
564
+ if callee_summary.param_taints_return.get(pidx, False):
565
+ returned_taint.update(taint_origins)
566
+ elif origin[0] == "source":
567
+ if callee_summary.return_from_source:
568
+ returned_taint.add(origin)
569
+
570
+ if callee_summary.return_from_source:
571
+ for src in callee_summary.direct_sources:
572
+ returned_taint.add(("source", src))
573
+
574
+ if returned_taint:
575
+ _propagate(origin_sym, callee_id, returned_taint, new_chain, depth + 1)
576
+
577
+ # Start propagation from symbols that have source-tainted data
578
+ for sym_id, summary in summaries.items():
579
+ if summary.is_sanitizer:
580
+ continue
581
+
582
+ taint_origins: set[tuple[str, int | str]] = set()
583
+
584
+ # Source-tainted returns: the function itself produces tainted data
585
+ if summary.return_from_source:
586
+ for src in summary.direct_sources:
587
+ taint_origins.add(("source", src))
588
+
589
+ # Params that flow to sinks in callees
590
+ for pidx in summary.param_taints_return:
591
+ taint_origins.add(("param", pidx))
592
+
593
+ # Direct source-to-sink within the function: record as finding
594
+ if summary.direct_sources and summary.direct_sinks:
595
+ for src in summary.direct_sources:
596
+ for snk in summary.direct_sinks:
597
+ findings.append(
598
+ TaintFinding(
599
+ source_symbol_id=sym_id,
600
+ sink_symbol_id=sym_id,
601
+ source_type=src,
602
+ sink_type=snk,
603
+ call_chain=[sym_id],
604
+ confidence=0.9,
605
+ )
606
+ )
607
+
608
+ if taint_origins:
609
+ _propagate(sym_id, sym_id, taint_origins, [], 0)
610
+
611
+ return findings
612
+
613
+
614
+ # ---------------------------------------------------------------------------
615
+ # Storage
616
+ # ---------------------------------------------------------------------------
617
+
618
+
619
+ def store_taint_data(
620
+ conn,
621
+ summaries: dict[int, TaintSummary],
622
+ findings: list[TaintFinding],
623
+ ) -> None:
624
+ """Persist taint summaries and findings to the database."""
625
+ conn.execute("DELETE FROM taint_summaries")
626
+ conn.execute("DELETE FROM taint_findings")
627
+
628
+ summary_rows = []
629
+ for sid, s in summaries.items():
630
+ summary_rows.append(
631
+ (
632
+ sid,
633
+ json.dumps({str(k): v for k, v in s.param_taints_return.items()}),
634
+ json.dumps({str(k): v for k, v in s.param_to_sink.items()}),
635
+ 1 if s.return_from_source else 0,
636
+ json.dumps(s.direct_sources),
637
+ json.dumps(s.direct_sinks),
638
+ 1 if s.is_sanitizer else 0,
639
+ )
640
+ )
641
+ if summary_rows:
642
+ conn.executemany(
643
+ """INSERT INTO taint_summaries
644
+ (symbol_id, param_taints_return, param_to_sink,
645
+ return_from_source, direct_sources, direct_sinks, is_sanitizer)
646
+ VALUES (?, ?, ?, ?, ?, ?, ?)""",
647
+ summary_rows,
648
+ )
649
+
650
+ finding_rows = []
651
+ for f in findings:
652
+ finding_rows.append(
653
+ (
654
+ f.source_symbol_id,
655
+ f.sink_symbol_id,
656
+ f.source_type,
657
+ f.sink_type,
658
+ json.dumps(f.call_chain),
659
+ len(f.call_chain),
660
+ 0, # sanitized = False (only unsanitized are stored)
661
+ f.confidence,
662
+ )
663
+ )
664
+ if finding_rows:
665
+ conn.executemany(
666
+ """INSERT INTO taint_findings
667
+ (source_symbol_id, sink_symbol_id, source_type, sink_type,
668
+ call_chain, chain_length, sanitized, confidence)
669
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
670
+ finding_rows,
671
+ )
672
+
673
+
674
+ # ---------------------------------------------------------------------------
675
+ # Entry point (called from indexer)
676
+ # ---------------------------------------------------------------------------
677
+
678
+
679
+ def compute_and_store_taint(conn, root: Path, G=None) -> None:
680
+ """Full taint pipeline: intra-summaries, propagation, storage.
681
+
682
+ Called from the indexer after graph construction.
683
+ """
684
+ summaries = compute_all_summaries(conn, root)
685
+ if not summaries:
686
+ return
687
+
688
+ findings = propagate_taint(conn, summaries, G)
689
+ store_taint_data(conn, summaries, findings)