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
@@ -0,0 +1,636 @@
1
+ """Scan for hardcoded secrets, API keys, tokens, and passwords."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ import re
8
+ from collections import Counter
9
+ from pathlib import Path
10
+
11
+ import click
12
+
13
+ from roam.commands.resolve import ensure_index
14
+ from roam.db.connection import find_project_root, open_db
15
+ from roam.output.formatter import format_table, json_envelope, to_json
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Secret patterns — compiled once at module level for performance
19
+ # ---------------------------------------------------------------------------
20
+
21
+ _SECRET_PATTERN_DEFS: list[dict] = [
22
+ # --- API Keys ---
23
+ {"name": "AWS Access Key", "pattern": r"AKIA[0-9A-Z]{16}", "severity": "high"},
24
+ {
25
+ "name": "AWS Secret Key",
26
+ "pattern": r"(?i)aws_secret_access_key\s*[=:]\s*['\"]?[A-Za-z0-9/+=]{40}",
27
+ "severity": "high",
28
+ },
29
+ {"name": "GitHub Token", "pattern": r"gh[pousr]_[A-Za-z0-9_]{36,255}", "severity": "high"},
30
+ {
31
+ "name": "GitHub Personal Access Token (classic)",
32
+ "pattern": r"ghp_[A-Za-z0-9]{36}",
33
+ "severity": "high",
34
+ },
35
+ {"name": "GitLab Token", "pattern": r"glpat-[A-Za-z0-9\-]{20,}", "severity": "high"},
36
+ {
37
+ "name": "Slack Bot Token",
38
+ "pattern": r"xoxb-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}",
39
+ "severity": "high",
40
+ },
41
+ {
42
+ "name": "Slack Webhook",
43
+ "pattern": r"https://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[a-zA-Z0-9]+",
44
+ "severity": "medium",
45
+ },
46
+ {"name": "Stripe Secret Key", "pattern": r"sk_live_[0-9a-zA-Z]{24,}", "severity": "high"},
47
+ {"name": "Stripe Publishable Key", "pattern": r"pk_live_[0-9a-zA-Z]{24,}", "severity": "low"},
48
+ {"name": "Google API Key", "pattern": r"AIza[0-9A-Za-z\-_]{35}", "severity": "high"},
49
+ {
50
+ "name": "Google OAuth Secret",
51
+ "pattern": r"(?i)client_secret.*['\"][A-Za-z0-9\-_]{24}['\"]",
52
+ "severity": "high",
53
+ },
54
+ {
55
+ "name": "Heroku API Key",
56
+ "pattern": r"(?i)heroku.*['\"][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['\"]",
57
+ "severity": "high",
58
+ },
59
+ {"name": "NPM Token", "pattern": r"npm_[A-Za-z0-9]{36}", "severity": "high"},
60
+ {"name": "PyPI Token", "pattern": r"pypi-[A-Za-z0-9\-_]{100,}", "severity": "high"},
61
+ {
62
+ "name": "SendGrid API Key",
63
+ "pattern": r"SG\.[A-Za-z0-9\-_]{22}\.[A-Za-z0-9\-_]{43}",
64
+ "severity": "high",
65
+ },
66
+ {"name": "Twilio API Key", "pattern": r"SK[0-9a-fA-F]{32}", "severity": "medium"},
67
+ {"name": "Mailgun API Key", "pattern": r"key-[0-9a-zA-Z]{32}", "severity": "high"},
68
+ # --- Generic Secrets ---
69
+ {
70
+ "name": "Private Key",
71
+ "pattern": r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",
72
+ "severity": "high",
73
+ },
74
+ {
75
+ "name": "Generic Password Assignment",
76
+ "pattern": r"(?i)(?:password|passwd|pwd)\s*[=:]\s*['\"][^\s'\"]{8,}['\"]",
77
+ "severity": "medium",
78
+ },
79
+ {
80
+ "name": "Generic Secret Assignment",
81
+ "pattern": r"(?i)(?:secret|token|api_key|apikey|access_key)\s*[=:]\s*['\"][^\s'\"]{8,}['\"]",
82
+ "severity": "medium",
83
+ },
84
+ {
85
+ "name": "Generic Bearer Token",
86
+ "pattern": r"(?i)bearer\s+[a-zA-Z0-9\-_.~+/]+=*",
87
+ "severity": "medium",
88
+ },
89
+ {
90
+ "name": "JWT Token",
91
+ "pattern": r"eyJ[A-Za-z0-9\-_]+\.eyJ[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_.+/=]+",
92
+ "severity": "medium",
93
+ },
94
+ {
95
+ "name": "Base64 Encoded Secret",
96
+ "pattern": r"(?i)(?:secret|password|token).*base64.*[A-Za-z0-9+/]{40,}={0,2}",
97
+ "severity": "low",
98
+ },
99
+ # --- Database ---
100
+ {
101
+ "name": "Database Connection String",
102
+ "pattern": r"(?i)(?:mysql|postgres|postgresql|mongodb|redis)://[^\s'\"]{10,}",
103
+ "severity": "high",
104
+ },
105
+ # --- High Entropy String (post-filtered by Shannon entropy) ---
106
+ {
107
+ "name": "High Entropy String",
108
+ "pattern": r"(?i)(?:key|secret|token|password|api_key|apikey|access_key|auth)\s*[=:]\s*['\"]([A-Za-z0-9+/=\-_]{20,})['\"]",
109
+ "severity": "low",
110
+ },
111
+ ]
112
+
113
+ # Compile all regexes once
114
+ _COMPILED_PATTERNS: list[dict] = []
115
+ for _pdef in _SECRET_PATTERN_DEFS:
116
+ _COMPILED_PATTERNS.append(
117
+ {
118
+ "name": _pdef["name"],
119
+ "regex": re.compile(_pdef["pattern"]),
120
+ "severity": _pdef["severity"],
121
+ }
122
+ )
123
+
124
+ # Severity ordering for filtering
125
+ _SEVERITY_RANK = {"high": 3, "medium": 2, "low": 1}
126
+
127
+ # Words in a line that indicate example/placeholder values (case-insensitive)
128
+ _PLACEHOLDER_WORDS = frozenset(
129
+ {
130
+ "example",
131
+ "placeholder",
132
+ "changeme",
133
+ "your_",
134
+ "xxx",
135
+ "dummy",
136
+ "fake",
137
+ "sample",
138
+ "todo",
139
+ "fixme",
140
+ "replace_me",
141
+ "insert_",
142
+ "your-",
143
+ "<your",
144
+ "xxxxxx",
145
+ }
146
+ )
147
+
148
+ # Directories to always skip during scanning
149
+ _SKIP_DIRS = frozenset(
150
+ {
151
+ ".git",
152
+ "node_modules",
153
+ "vendor",
154
+ "__pycache__",
155
+ ".tox",
156
+ ".mypy_cache",
157
+ ".pytest_cache",
158
+ ".ruff_cache",
159
+ "venv",
160
+ ".venv",
161
+ "env",
162
+ ".env",
163
+ "dist",
164
+ "build",
165
+ ".eggs",
166
+ ".next",
167
+ ".nuxt",
168
+ ".roam",
169
+ }
170
+ )
171
+
172
+ # Binary file extensions to skip
173
+ _BINARY_EXTENSIONS = frozenset(
174
+ {
175
+ ".png",
176
+ ".jpg",
177
+ ".jpeg",
178
+ ".gif",
179
+ ".bmp",
180
+ ".ico",
181
+ ".svg",
182
+ ".webp",
183
+ ".woff",
184
+ ".woff2",
185
+ ".ttf",
186
+ ".eot",
187
+ ".otf",
188
+ ".zip",
189
+ ".tar",
190
+ ".gz",
191
+ ".bz2",
192
+ ".xz",
193
+ ".7z",
194
+ ".rar",
195
+ ".exe",
196
+ ".dll",
197
+ ".so",
198
+ ".dylib",
199
+ ".o",
200
+ ".a",
201
+ ".lib",
202
+ ".pyc",
203
+ ".pyo",
204
+ ".class",
205
+ ".jar",
206
+ ".db",
207
+ ".sqlite",
208
+ ".sqlite3",
209
+ ".pdf",
210
+ ".doc",
211
+ ".docx",
212
+ ".xls",
213
+ ".xlsx",
214
+ ".mp3",
215
+ ".mp4",
216
+ ".wav",
217
+ ".avi",
218
+ ".mov",
219
+ ".bin",
220
+ ".dat",
221
+ ".pak",
222
+ ".wasm",
223
+ }
224
+ )
225
+
226
+ # ---------------------------------------------------------------------------
227
+ # Environment-variable patterns — lines matching these are NOT hardcoded
228
+ # ---------------------------------------------------------------------------
229
+
230
+ _ENV_VAR_INDICATORS = (
231
+ "os.environ",
232
+ "process.env",
233
+ "config.get(",
234
+ "getenv(",
235
+ "ENV[",
236
+ "env.",
237
+ "Config.",
238
+ "settings.",
239
+ )
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # Test/fixture/docs path patterns — suppressed by default
243
+ # ---------------------------------------------------------------------------
244
+
245
+ _TEST_DIR_SEGMENTS = frozenset(
246
+ {
247
+ "tests",
248
+ "test",
249
+ "__tests__",
250
+ "spec",
251
+ "fixtures",
252
+ "docs",
253
+ "examples",
254
+ }
255
+ )
256
+
257
+ # File-level patterns (basename matching)
258
+ _TEST_FILE_RE = re.compile(
259
+ r"^test_.*|.*_test\.[^.]+$",
260
+ re.IGNORECASE,
261
+ )
262
+
263
+ _DOC_EXTENSIONS = frozenset({".md", ".rst", ".txt"})
264
+
265
+ # ---------------------------------------------------------------------------
266
+ # Per-finding remediation suggestions
267
+ # ---------------------------------------------------------------------------
268
+
269
+ _REMEDIATION: dict[str, str] = {
270
+ "AWS Access Key": "Use os.environ['AWS_ACCESS_KEY_ID'] or AWS Secrets Manager",
271
+ "AWS Secret Key": "Use os.environ['AWS_SECRET_ACCESS_KEY'] or AWS Secrets Manager",
272
+ "GitHub Token": "Use os.environ['GITHUB_TOKEN'] or GitHub Actions secrets",
273
+ "GitHub Personal Access Token (classic)": "Use os.environ['GITHUB_TOKEN'] or GitHub Actions secrets",
274
+ "GitLab Token": "Use os.environ['GITLAB_TOKEN'] or CI/CD variables",
275
+ "Slack Bot Token": "Use os.environ['SLACK_BOT_TOKEN'] or Slack app config",
276
+ "Slack Webhook": "Use os.environ['SLACK_WEBHOOK_URL'] or secrets manager",
277
+ "Stripe Secret Key": "Use os.environ['STRIPE_SECRET_KEY'] or secrets manager",
278
+ "Stripe Publishable Key": "Publishable keys are public; verify this is intentional",
279
+ "Google API Key": "Use os.environ['GOOGLE_API_KEY'] or secrets manager",
280
+ "Google OAuth Secret": "Use os.environ['GOOGLE_CLIENT_SECRET'] or secrets manager",
281
+ "Heroku API Key": "Use os.environ['HEROKU_API_KEY'] or Heroku config vars",
282
+ "NPM Token": "Use .npmrc with env var: //registry.npmjs.org/:_authToken=${NPM_TOKEN}",
283
+ "PyPI Token": "Use keyring or TWINE_PASSWORD env var",
284
+ "SendGrid API Key": "Use os.environ['SENDGRID_API_KEY'] or secrets manager",
285
+ "Twilio API Key": "Use os.environ['TWILIO_API_KEY'] or secrets manager",
286
+ "Mailgun API Key": "Use os.environ['MAILGUN_API_KEY'] or secrets manager",
287
+ "Private Key": "Store in a secure key vault, not in source code",
288
+ "Generic Password Assignment": "Move to environment variable or secrets manager",
289
+ "Generic Secret Assignment": "Move to environment variable or secrets manager",
290
+ "Generic Bearer Token": "Generate tokens at runtime, don't hardcode",
291
+ "JWT Token": "Generate tokens at runtime, don't hardcode",
292
+ "Base64 Encoded Secret": "Move to environment variable or secrets manager",
293
+ "Database Connection String": "Use connection pool with env-var DSN",
294
+ "High Entropy String": "If this is a real secret, move to environment variable",
295
+ }
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # Shannon entropy helper
300
+ # ---------------------------------------------------------------------------
301
+
302
+
303
+ def _shannon_entropy(s: str) -> float:
304
+ """Calculate Shannon entropy in bits per character."""
305
+ if not s:
306
+ return 0.0
307
+ freq = Counter(s)
308
+ length = len(s)
309
+ return -sum((c / length) * math.log2(c / length) for c in freq.values())
310
+
311
+
312
+ # Minimum entropy threshold for "High Entropy String" findings
313
+ _ENTROPY_THRESHOLD = 4.5
314
+
315
+
316
+ def _is_binary(file_path: str) -> bool:
317
+ """Check if a file is likely binary by extension."""
318
+ _, ext = os.path.splitext(file_path)
319
+ return ext.lower() in _BINARY_EXTENSIONS
320
+
321
+
322
+ def _in_skip_dir(rel_path: str) -> bool:
323
+ """Check if a relative path is under a directory that should be skipped."""
324
+ parts = rel_path.replace("\\", "/").split("/")
325
+ return any(p in _SKIP_DIRS for p in parts)
326
+
327
+
328
+ def _is_placeholder_line(line: str) -> bool:
329
+ """Check if a line contains placeholder/example indicators."""
330
+ lower = line.lower()
331
+ return any(word in lower for word in _PLACEHOLDER_WORDS)
332
+
333
+
334
+ def _is_env_var_line(line: str) -> bool:
335
+ """Check if a line reads a value from an environment variable or config.
336
+
337
+ These are legitimate patterns, not hardcoded secrets.
338
+ """
339
+ return any(indicator in line for indicator in _ENV_VAR_INDICATORS)
340
+
341
+
342
+ def _is_test_or_doc_path(rel_path: str) -> bool:
343
+ """Check if a relative path belongs to test, fixture, or docs directories.
344
+
345
+ Returns True if the file should be suppressed (test/fixture/docs).
346
+ """
347
+ normed = rel_path.replace("\\", "/")
348
+ parts = normed.split("/")
349
+ basename = parts[-1] if parts else ""
350
+
351
+ # Check directory segments
352
+ for part in parts[:-1]: # exclude the filename itself
353
+ if part in _TEST_DIR_SEGMENTS:
354
+ return True
355
+
356
+ # Check filename patterns
357
+ if _TEST_FILE_RE.match(basename):
358
+ return True
359
+
360
+ # Check doc extensions
361
+ _, ext = os.path.splitext(basename)
362
+ if ext.lower() in _DOC_EXTENSIONS:
363
+ return True
364
+
365
+ return False
366
+
367
+
368
+ def mask_secret(matched_text: str) -> str:
369
+ """Mask a matched secret value for safe display.
370
+
371
+ Shows first 4 chars + "..." + last 4 chars for values >= 12 chars.
372
+ Shows first 4 chars + "..." for shorter values.
373
+ Never shows the full secret.
374
+ """
375
+ if len(matched_text) <= 8:
376
+ return matched_text[:4] + "..."
377
+ if len(matched_text) >= 12:
378
+ return matched_text[:4] + "..." + matched_text[-4:]
379
+ return matched_text[:4] + "..."
380
+
381
+
382
+ def scan_file(file_path: str, patterns: list[dict] | None = None, min_severity: str = "all") -> list[dict]:
383
+ """Scan a single file for secret patterns.
384
+
385
+ Returns a list of finding dicts with keys:
386
+ file, line, severity, pattern_name, matched_text (masked), remediation
387
+ """
388
+ if patterns is None:
389
+ patterns = _COMPILED_PATTERNS
390
+
391
+ min_rank = 0 if min_severity == "all" else _SEVERITY_RANK.get(min_severity, 0)
392
+
393
+ findings: list[dict] = []
394
+ try:
395
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
396
+ for line_num, line in enumerate(f, start=1):
397
+ # Skip lines that look like examples or placeholders
398
+ if _is_placeholder_line(line):
399
+ continue
400
+ # Skip lines that read from environment variables / config
401
+ if _is_env_var_line(line):
402
+ continue
403
+ for pat in patterns:
404
+ if _SEVERITY_RANK.get(pat["severity"], 0) < min_rank:
405
+ continue
406
+ match = pat["regex"].search(line)
407
+ if match:
408
+ # For High Entropy String, apply entropy threshold
409
+ if pat["name"] == "High Entropy String":
410
+ # Use group(1) if available (the captured value),
411
+ # otherwise use the full match
412
+ value = match.group(1) if match.lastindex else match.group()
413
+ if _shannon_entropy(value) < _ENTROPY_THRESHOLD:
414
+ continue
415
+ findings.append(
416
+ {
417
+ "file": file_path,
418
+ "line": line_num,
419
+ "severity": pat["severity"],
420
+ "pattern_name": pat["name"],
421
+ "matched_text": mask_secret(match.group()),
422
+ "remediation": _REMEDIATION.get(
423
+ pat["name"], "Move to environment variable or secrets manager"
424
+ ),
425
+ }
426
+ )
427
+ except (OSError, UnicodeDecodeError):
428
+ pass
429
+
430
+ return findings
431
+
432
+
433
+ def scan_project(
434
+ project_root: Path,
435
+ min_severity: str = "all",
436
+ use_index: bool = True,
437
+ include_tests: bool = False,
438
+ ) -> list[dict]:
439
+ """Scan all indexed files in a project for secrets.
440
+
441
+ If use_index is True, reads file paths from the roam index DB.
442
+ Otherwise falls back to walking the filesystem.
443
+
444
+ When include_tests is False (the default), files in test, fixture,
445
+ docs, and example directories are suppressed.
446
+
447
+ Returns a list of finding dicts sorted by severity (high first),
448
+ then file path, then line number.
449
+ """
450
+ root = Path(project_root).resolve()
451
+
452
+ if use_index:
453
+ try:
454
+ with open_db(readonly=True) as conn:
455
+ rows = conn.execute("SELECT path FROM files").fetchall()
456
+ file_paths = [row["path"] for row in rows]
457
+ except Exception:
458
+ file_paths = _walk_for_files(root)
459
+ else:
460
+ file_paths = _walk_for_files(root)
461
+
462
+ all_findings: list[dict] = []
463
+ for rel_path in file_paths:
464
+ if _is_binary(rel_path):
465
+ continue
466
+ if _in_skip_dir(rel_path):
467
+ continue
468
+ # Suppress test/fixture/docs files unless --include-tests
469
+ if not include_tests and _is_test_or_doc_path(rel_path):
470
+ continue
471
+
472
+ full_path = root / rel_path
473
+ if not full_path.is_file():
474
+ continue
475
+
476
+ file_findings = scan_file(str(full_path), min_severity=min_severity)
477
+ # Store relative path in findings for cleaner output
478
+ for f in file_findings:
479
+ f["file"] = rel_path
480
+ all_findings.extend(file_findings)
481
+
482
+ # Sort: high severity first, then by file path, then line number
483
+ all_findings.sort(key=lambda f: (-_SEVERITY_RANK.get(f["severity"], 0), f["file"], f["line"]))
484
+ return all_findings
485
+
486
+
487
+ def _walk_for_files(root: Path) -> list[str]:
488
+ """Walk the filesystem to find scannable files (fallback)."""
489
+ result: list[str] = []
490
+ for dirpath, dirnames, filenames in os.walk(root):
491
+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS]
492
+ for fname in filenames:
493
+ full = os.path.join(dirpath, fname)
494
+ try:
495
+ rel = os.path.relpath(full, root).replace("\\", "/")
496
+ except (ValueError, OSError):
497
+ continue
498
+ result.append(rel)
499
+ return result
500
+
501
+
502
+ @click.command("secrets")
503
+ @click.option(
504
+ "--severity",
505
+ type=click.Choice(["all", "high", "medium", "low"]),
506
+ default="all",
507
+ help="Show only findings at or above this severity level",
508
+ )
509
+ @click.option("--fail-on-found", is_flag=True, help="Exit with code 5 if any secrets are found (for CI)")
510
+ @click.option(
511
+ "--include-tests",
512
+ is_flag=True,
513
+ default=False,
514
+ help="Include test files, fixtures, docs, and examples in scan",
515
+ )
516
+ @click.pass_context
517
+ def secrets(ctx, severity, fail_on_found, include_tests):
518
+ """Scan for hardcoded secrets, API keys, tokens, and passwords."""
519
+ json_mode = ctx.obj.get("json") if ctx.obj else False
520
+ sarif_mode = ctx.obj.get("sarif") if ctx.obj else False
521
+ token_budget = ctx.obj.get("budget", 0) if ctx.obj else 0
522
+ ensure_index()
523
+
524
+ project_root = find_project_root()
525
+ findings = scan_project(project_root, min_severity=severity, include_tests=include_tests)
526
+
527
+ # Compute summary stats
528
+ total = len(findings)
529
+ files_affected = len({f["file"] for f in findings})
530
+ by_severity = {"high": 0, "medium": 0, "low": 0}
531
+ for f in findings:
532
+ by_severity[f["severity"]] = by_severity.get(f["severity"], 0) + 1
533
+
534
+ if total == 0:
535
+ verdict = "No secrets found"
536
+ else:
537
+ parts = []
538
+ if by_severity["high"]:
539
+ parts.append(f"{by_severity['high']} high")
540
+ if by_severity["medium"]:
541
+ parts.append(f"{by_severity['medium']} medium")
542
+ if by_severity["low"]:
543
+ parts.append(f"{by_severity['low']} low")
544
+ sev_str = ", ".join(parts)
545
+ verdict = f"{total} secrets found in {files_affected} files ({sev_str})"
546
+
547
+ # --- SARIF output ---
548
+ if sarif_mode:
549
+ from roam.output.sarif import secrets_to_sarif, write_sarif
550
+
551
+ sarif = secrets_to_sarif(findings)
552
+ click.echo(write_sarif(sarif))
553
+ if fail_on_found and total > 0:
554
+ from roam.exit_codes import GateFailureError
555
+
556
+ raise GateFailureError(verdict)
557
+ return
558
+
559
+ # --- JSON output ---
560
+ if json_mode:
561
+ envelope = json_envelope(
562
+ "secrets",
563
+ summary={
564
+ "verdict": verdict,
565
+ "total_findings": total,
566
+ "files_affected": files_affected,
567
+ "by_severity": by_severity,
568
+ },
569
+ budget=token_budget,
570
+ findings=[
571
+ {
572
+ "file": f["file"],
573
+ "line": f["line"],
574
+ "severity": f["severity"],
575
+ "pattern": f["pattern_name"],
576
+ "matched_text": f["matched_text"],
577
+ "remediation": f.get("remediation", ""),
578
+ }
579
+ for f in findings
580
+ ],
581
+ )
582
+ click.echo(to_json(envelope))
583
+ if fail_on_found and total > 0:
584
+ from roam.exit_codes import GateFailureError
585
+
586
+ raise GateFailureError(verdict)
587
+ return
588
+
589
+ # --- Text output ---
590
+ click.echo(f"VERDICT: {verdict}")
591
+ click.echo()
592
+
593
+ if findings:
594
+ rows = []
595
+ for f in findings:
596
+ loc_str = f"{f['file']}:{f['line']}"
597
+ sev = f["severity"].upper()
598
+ rows.append([loc_str, sev, f["pattern_name"], f["matched_text"]])
599
+
600
+ click.echo(
601
+ format_table(
602
+ ["Location", "Severity", "Pattern", "Match"],
603
+ rows,
604
+ )
605
+ )
606
+ click.echo()
607
+ click.echo(f" {total} secrets, {files_affected} files, {by_severity['high']} high severity")
608
+ click.echo()
609
+
610
+ # Per-finding remediation
611
+ seen_patterns: set[str] = set()
612
+ remediation_lines: list[str] = []
613
+ for f in findings:
614
+ pname = f["pattern_name"]
615
+ if pname not in seen_patterns:
616
+ seen_patterns.add(pname)
617
+ hint = f.get("remediation", _REMEDIATION.get(pname, ""))
618
+ if hint:
619
+ remediation_lines.append(f" - {pname}: {hint}")
620
+
621
+ click.echo(" Recommendations:")
622
+ click.echo(" - Move secrets to environment variables or a secrets manager")
623
+ click.echo(" - Add .env to .gitignore")
624
+ click.echo(" - Consider using git-secrets or pre-commit hooks to prevent future leaks")
625
+ if remediation_lines:
626
+ click.echo()
627
+ click.echo(" Per-pattern guidance:")
628
+ for line in remediation_lines:
629
+ click.echo(line)
630
+ else:
631
+ click.echo(" No hardcoded secrets detected.")
632
+
633
+ if fail_on_found and total > 0:
634
+ from roam.exit_codes import GateFailureError
635
+
636
+ raise GateFailureError(verdict)