timecs 2.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 (94) hide show
  1. app.py +3014 -0
  2. ast_scanner.py +36187 -0
  3. banner.py +146 -0
  4. ci_reporter.py +570 -0
  5. cli.py +2347 -0
  6. config_loader.py +307 -0
  7. cross_file_engine.py +1781 -0
  8. delivery_models.py +145 -0
  9. delivery_repository.py +78 -0
  10. diff_scan.py +127 -0
  11. durable_delivery_sink.py +103 -0
  12. event_bus.py +155 -0
  13. event_publisher.py +345 -0
  14. event_taxonomy.py +313 -0
  15. function_summarizer.py +354 -0
  16. html_auditor.py +274 -0
  17. iac_auditor.py +400 -0
  18. in_app_adapter.py +115 -0
  19. js_scanner.py +895 -0
  20. manifest_parser.py +960 -0
  21. master_rules_bank.py +389 -0
  22. notification_models.py +346 -0
  23. notification_policy.py +309 -0
  24. notification_repository.py +118 -0
  25. notification_routes.py +394 -0
  26. notification_service.py +199 -0
  27. osv_client.py +437 -0
  28. remediation/__init__.py +39 -0
  29. remediation/base.py +102 -0
  30. remediation/contracts.py +196 -0
  31. remediation/cwe1188_binding.py +78 -0
  32. remediation/cwe1336_jinja.py +91 -0
  33. remediation/cwe22_path_traversal.py +348 -0
  34. remediation/cwe295_ssl.py +87 -0
  35. remediation/cwe327_weak_hash.py +78 -0
  36. remediation/cwe377_tempfile.py +77 -0
  37. remediation/cwe489_debug.py +80 -0
  38. remediation/cwe502_yaml.py +89 -0
  39. remediation/cwe614_cookie.py +91 -0
  40. remediation/cwe78_cmdi.py +415 -0
  41. remediation/cwe798_credentials.py +153 -0
  42. remediation/cwe89_sqli.py +425 -0
  43. remediation/cwe916_password_hash.py +131 -0
  44. remediation/cwe95_eval.py +77 -0
  45. remediation/dispatcher.py +114 -0
  46. remediation/orchestrator.py +541 -0
  47. remediation/patch_engine.py +213 -0
  48. remediation/verification.py +253 -0
  49. rule_engine.py +1535 -0
  50. sarif_adapter.py +719 -0
  51. sarif_exporter.py +88 -0
  52. sca_reachability/__init__.py +28 -0
  53. sca_reachability/ast_analyzer.py +366 -0
  54. sca_reachability/call_graph.py +203 -0
  55. sca_reachability/contracts.py +365 -0
  56. sca_reachability/dist_import_map.py +46 -0
  57. sca_reachability/engine.py +603 -0
  58. sca_reachability/resolver.py +169 -0
  59. scanners/__init__.py +70 -0
  60. scanners/container_scanner.py +323 -0
  61. scanners/cve_index.py +521 -0
  62. scanners/iac_scanner.py +328 -0
  63. scanners/sbom.py +183 -0
  64. scanners/sca_scanner.py +667 -0
  65. scanners/secret_scanner.py +345 -0
  66. scanners/yaml_lite.py +217 -0
  67. secret_filters.py +435 -0
  68. secret_scanner.py +943 -0
  69. sqlite_delivery_repository.py +277 -0
  70. sqlite_notification_repository.py +441 -0
  71. ssrf_guard.py +276 -0
  72. staged_scanner.py +492 -0
  73. suppression_resolver.py +282 -0
  74. symbol_indexer.py +424 -0
  75. tcs/__init__.py +1 -0
  76. tcs/analysis/__init__.py +1 -0
  77. tcs/analysis/def_use.py +408 -0
  78. tcs/analysis/function_contracts.py +290 -0
  79. tcs/parallel_analyzer.py +276 -0
  80. tcs/parallel_scanner.py +630 -0
  81. tcs/treesitter_packer.py +1446 -0
  82. tcs_cli.py +2086 -0
  83. tcs_config.py +218 -0
  84. tcs_gui.py +2123 -0
  85. timecs-2.0.0.dist-info/METADATA +142 -0
  86. timecs-2.0.0.dist-info/RECORD +94 -0
  87. timecs-2.0.0.dist-info/WHEEL +5 -0
  88. timecs-2.0.0.dist-info/entry_points.txt +4 -0
  89. timecs-2.0.0.dist-info/licenses/LICENSE +201 -0
  90. timecs-2.0.0.dist-info/top_level.txt +49 -0
  91. version_matcher.py +934 -0
  92. webhook_adapter.py +495 -0
  93. webhook_client.py +483 -0
  94. webhook_formatters.py +245 -0
ci_reporter.py ADDED
@@ -0,0 +1,570 @@
1
+ """
2
+ TimeCodeSecurity CI/CD Reporter & GitHub Step Summary Engine.
3
+ Converts unified TimeCodeSecurity scan results (SAST, SCA, Secrets) into safe, deterministic
4
+ GitHub Actions workflow commands (::error, ::warning) and Markdown step summaries.
5
+
6
+ Invariants:
7
+ - 100% pure formatting; zero network I/O; zero file side-effects.
8
+ - Injection-immune workflow commands with strict percent-encoding of control characters.
9
+ - Zero raw secret exposure: only masked values and redacted contexts are serialized.
10
+ - Never False Clean: SCA UNRESOLVED states are explicitly preserved and surfaced.
11
+ - Deterministic byte-for-byte output via strict multi-attribute sorting.
12
+ """
13
+
14
+ import re
15
+ from typing import Dict, List, Any, Optional, Tuple
16
+
17
+
18
+ __all__ = [
19
+ "escape_property_value",
20
+ "escape_message_data",
21
+ "format_github_annotation",
22
+ "format_github_annotations",
23
+ "generate_annotations",
24
+ "generate_step_summary",
25
+ "sanitize_symbol_display",
26
+ "write_step_summary",
27
+ ]
28
+
29
+
30
+ # Canonical display labels for secret types
31
+ _SECRET_TYPE_LABELS: Dict[str, str] = {
32
+ "aws_access_key": "AWS Access Key",
33
+ "github_token": "GitHub Token",
34
+ "slack_token": "Slack Token",
35
+ "stripe_key": "Stripe API Key",
36
+ "private_key": "Private Key",
37
+ "database_connection_string": "Database Connection String",
38
+ }
39
+
40
+
41
+ def escape_property_value(val: Any) -> str:
42
+ """
43
+ Escapes a property value (file, title, line, col, etc.) for GitHub Actions workflow commands.
44
+
45
+ GitHub Actions workflow command specification requires:
46
+ % -> %25
47
+ \\r -> %0D
48
+ \\n -> %0A
49
+ : -> %3A
50
+ , -> %2C
51
+
52
+ Encoding % first is required to prevent double-encoding.
53
+ Strictly neutralizes CRLF injection across all property parameters.
54
+ """
55
+ if val is None:
56
+ return ""
57
+ s = str(val)
58
+ return (
59
+ s.replace("%", "%25")
60
+ .replace("\r", "%0D")
61
+ .replace("\n", "%0A")
62
+ .replace(":", "%3A")
63
+ .replace(",", "%2C")
64
+ )
65
+
66
+
67
+ def escape_message_data(val: Any) -> str:
68
+ """
69
+ Escapes message text for GitHub Actions workflow commands.
70
+
71
+ GitHub Actions workflow command specification requires:
72
+ % -> %25
73
+ \\r -> %0D
74
+ \\n -> %0A
75
+
76
+ Strictly ensures the message remains on a single line and cannot inject new commands.
77
+ """
78
+ if val is None:
79
+ return ""
80
+ s = str(val)
81
+ return (
82
+ s.replace("%", "%25")
83
+ .replace("\r", "%0D")
84
+ .replace("\n", "%0A")
85
+ )
86
+
87
+
88
+ def _normalize_path(path: Any) -> str:
89
+ """Normalizes file paths by converting backslashes to forward slashes and stripping redundant prefixes."""
90
+ if not path:
91
+ return ""
92
+ norm = str(path).replace("\\", "/")
93
+ if norm.startswith("./"):
94
+ norm = norm[2:]
95
+ return norm
96
+
97
+
98
+ def _extract_int_coord(val: Any) -> Optional[int]:
99
+ """Extracts a valid 1-based coordinate integer, or returns None if missing/0/invalid."""
100
+ if val is None:
101
+ return None
102
+ try:
103
+ iv = int(val)
104
+ return iv if iv > 0 else None
105
+ except (ValueError, TypeError):
106
+ return None
107
+
108
+
109
+ def format_github_annotation(
110
+ level: str,
111
+ message: str,
112
+ file_path: Optional[str] = None,
113
+ line: Optional[int] = None,
114
+ col: Optional[int] = None,
115
+ end_line: Optional[int] = None,
116
+ end_col: Optional[int] = None,
117
+ title: Optional[str] = None,
118
+ ) -> str:
119
+ """
120
+ Constructs a single safe GitHub Actions workflow command line.
121
+
122
+ Format:
123
+ ::(error|warning|notice) file=...,line=...,col=...,title=...::message
124
+ """
125
+ cmd_level = level.lower()
126
+ if cmd_level not in ("error", "warning", "notice"):
127
+ cmd_level = "warning"
128
+
129
+ props: List[str] = []
130
+ if file_path:
131
+ norm_file = _normalize_path(file_path)
132
+ if norm_file:
133
+ props.append(f"file={escape_property_value(norm_file)}")
134
+
135
+ line_val = _extract_int_coord(line)
136
+ if line_val is not None:
137
+ props.append(f"line={line_val}")
138
+
139
+ col_val = _extract_int_coord(col)
140
+ if col_val is not None:
141
+ props.append(f"col={col_val}")
142
+
143
+ end_line_val = _extract_int_coord(end_line)
144
+ if end_line_val is not None:
145
+ props.append(f"endLine={end_line_val}")
146
+
147
+ end_col_val = _extract_int_coord(end_col)
148
+ if end_col_val is not None:
149
+ props.append(f"endColumn={end_col_val}")
150
+
151
+ if title:
152
+ props.append(f"title={escape_property_value(title)}")
153
+
154
+ prop_str = f" {','.join(props)}" if props else ""
155
+ escaped_msg = escape_message_data(message)
156
+
157
+ return f"::{cmd_level}{prop_str}::{escaped_msg}"
158
+
159
+
160
+ # A sink's resolved name is prefixed with its path-derived module, so an untrimmed Windows
161
+ # scan root reaches a PR comment as
162
+ # `C:.Users.me.Temp.tmp.ab12cd.target.app.models.login.objects.raw`. Three trailing segments
163
+ # still qualify a real call such as `PIL.ImageMath.eval`. Every channel that renders a sink
164
+ # name (CI annotations, step summary, cli.py JSON report, GUI dataflow trace) goes through
165
+ # this rule so the same finding reads identically everywhere.
166
+ _TARGET_DISPLAY_SEGMENTS = 3
167
+ _SYMBOL_NOISE_TOKENS = frozenset({"tmp", "temp"})
168
+
169
+
170
+ def sanitize_symbol_display(symbol: Any) -> str:
171
+ """Reduce a resolved sink name to the call chain a reviewer can act on."""
172
+ text = str(symbol)
173
+ segments = [
174
+ part for part in re.split(r"[.:]", text)
175
+ if part and part.lower() not in _SYMBOL_NOISE_TOKENS
176
+ ]
177
+ return ".".join(segments[-_TARGET_DISPLAY_SEGMENTS:]) if segments else text
178
+
179
+
180
+ def _format_sast_annotation(finding: Dict[str, Any]) -> Tuple[Tuple[str, int, int, int, str], str]:
181
+ """Formats a SAST finding into a GitHub Actions annotation with sorting tuple."""
182
+ cwe = finding.get("cwe") or "CWE-UNKNOWN"
183
+ sev = str(finding.get("severity") or "HIGH").upper()
184
+ level = "error" if sev in ("CRITICAL", "HIGH") else "warning"
185
+
186
+ file_path = finding.get("file") or ""
187
+ line = _extract_int_coord(finding.get("line_number"))
188
+ col = _extract_int_coord(finding.get("column_start"))
189
+
190
+ raw_cat = finding.get("category") or ""
191
+ cat_label = raw_cat.replace("_", " ").title() if raw_cat else ""
192
+ title = f"{cwe} ({cat_label})" if cat_label else cwe
193
+
194
+ # Extract informative message
195
+ sink_sym = sanitize_symbol_display(finding.get("sink_symbol")) if finding.get("sink_symbol") else ""
196
+ trace_summary = finding.get("flow_trace_summary")
197
+ code_snip = finding.get("code_snippet")
198
+
199
+ if trace_summary:
200
+ msg = trace_summary
201
+ elif sink_sym:
202
+ msg = f"Untrusted input reaches dangerous sink '{sink_sym}'"
203
+ elif code_snip:
204
+ msg = f"Vulnerable code pattern: {code_snip.strip()}"
205
+ else:
206
+ msg = f"{cwe} security vulnerability detected"
207
+
208
+ sort_key = (_normalize_path(file_path), line or 0, col or 0, 1, cwe)
209
+ ann = format_github_annotation(
210
+ level=level,
211
+ message=msg,
212
+ file_path=file_path,
213
+ line=line,
214
+ col=col,
215
+ title=title,
216
+ )
217
+ return sort_key, ann
218
+
219
+
220
+ def _format_sca_annotation(finding: Any) -> Tuple[Tuple[str, int, int, int, str], str]:
221
+ """Formats an SCA finding into a GitHub Actions annotation with sorting tuple."""
222
+ # Support dict or dataclass
223
+ if hasattr(finding, "to_dict"):
224
+ sf = finding.to_dict()
225
+ elif isinstance(finding, dict):
226
+ sf = finding
227
+ else:
228
+ sf = getattr(finding, "__dict__", {})
229
+
230
+ pkg = sf.get("package_name") or "unknown-package"
231
+ vuln_id = sf.get("vulnerability_id") or "SCA-ADVISORY"
232
+ status = str(sf.get("status") or "POTENTIAL").upper()
233
+ sev = str(sf.get("severity") or "UNKNOWN").upper()
234
+ manifest = sf.get("manifest_source") or ""
235
+ line = _extract_int_coord(sf.get("line_number"))
236
+
237
+ installed_ver = sf.get("installed_version")
238
+ req_spec = sf.get("requested_specifier")
239
+ fixed_ver = sf.get("fixed_version")
240
+ summary = sf.get("summary")
241
+
242
+ ver_desc = installed_ver or req_spec or "unspecified"
243
+
244
+ if status == "UNRESOLVED":
245
+ level = "warning"
246
+ title = f"SCA Unresolved ({pkg})" if pkg != "unknown-package" else "SCA Unresolved"
247
+ msg = summary or f"Vulnerability data could not be verified for package '{pkg}'"
248
+ else:
249
+ level = "error" if sev in ("CRITICAL", "HIGH") else "warning"
250
+ title = f"SCA ({vuln_id})"
251
+ fixed_part = f"; fixed in {fixed_ver}" if fixed_ver else ""
252
+ msg = f"{pkg} {ver_desc} is affected ({vuln_id}){fixed_part}"
253
+
254
+ sort_key = (_normalize_path(manifest), line or 0, 0, 2, vuln_id)
255
+ ann = format_github_annotation(
256
+ level=level,
257
+ message=msg,
258
+ file_path=manifest,
259
+ line=line,
260
+ title=title,
261
+ )
262
+ return sort_key, ann
263
+
264
+
265
+ def _format_secret_annotation(finding: Any) -> Tuple[Tuple[str, int, int, int, str], str]:
266
+ """Formats a Secret finding into a safe, non-leaking GitHub Actions annotation with sorting tuple."""
267
+ # Support dict or dataclass
268
+ if hasattr(finding, "to_dict"):
269
+ sec = finding.to_dict()
270
+ elif isinstance(finding, dict):
271
+ sec = finding
272
+ else:
273
+ sec = getattr(finding, "__dict__", {})
274
+
275
+ sec_type = sec.get("secret_type") or "secret"
276
+ label = _SECRET_TYPE_LABELS.get(sec_type, sec_type.replace("_", " ").title())
277
+ masked_val = sec.get("masked_value") or "********"
278
+
279
+ file_path = sec.get("file") or ""
280
+ line = _extract_int_coord(sec.get("line_number"))
281
+ col = _extract_int_coord(sec.get("column_start"))
282
+ end_col = _extract_int_coord(sec.get("column_end"))
283
+
284
+ # Canonical vulnerability mapping: CWE-798
285
+ title = f"CWE-798 ({label})"
286
+ # Zero raw secret exposure: only masked value is emitted
287
+ msg = f"Hardcoded {label} detected: {masked_val}"
288
+
289
+ sort_key = (_normalize_path(file_path), line or 0, col or 0, 3, sec_type)
290
+ ann = format_github_annotation(
291
+ level="error",
292
+ message=msg,
293
+ file_path=file_path,
294
+ line=line,
295
+ col=col,
296
+ end_col=end_col,
297
+ title=title,
298
+ )
299
+ return sort_key, ann
300
+
301
+
302
+ def format_github_annotations(scan_result: Dict[str, Any]) -> List[str]:
303
+ """
304
+ Converts unified TimeCodeSecurity scan results into a deterministically ordered list of
305
+ GitHub Actions workflow command annotations (::error, ::warning).
306
+
307
+ Sort order: (file, line, col, engine, rule/vuln/secret_type).
308
+ """
309
+ if not isinstance(scan_result, dict):
310
+ return []
311
+
312
+ staged_items: List[Tuple[Tuple[str, int, int, int, str], str]] = []
313
+
314
+ # 0. Parser Warnings (Syntax Errors)
315
+ syntax_errors = scan_result.get("syntax_errors", [])
316
+ if isinstance(syntax_errors, list):
317
+ for err in syntax_errors:
318
+ parts = str(err).split(":", 2)
319
+ f_err = parts[0].strip() if len(parts) > 0 else ""
320
+ line_err = _extract_int_coord(parts[1].strip()) if len(parts) > 1 else None
321
+ msg_err = f"Skipping AST analysis for unparseable file: {err}"
322
+ sort_key = (_normalize_path(f_err), line_err or 0, 0, 0, "SYNTAX_ERROR")
323
+ ann = format_github_annotation(
324
+ level="warning",
325
+ message=msg_err,
326
+ file_path=f_err,
327
+ line=line_err,
328
+ title="Syntax Warning",
329
+ )
330
+ staged_items.append((sort_key, ann))
331
+
332
+ # 1. SAST Findings
333
+ sast_findings = scan_result.get("findings", [])
334
+ if isinstance(sast_findings, list):
335
+ for f in sast_findings:
336
+ if not isinstance(f, dict):
337
+ continue
338
+ # Respect suppressed flag (omit from active annotations)
339
+ if f.get("suppressed", False):
340
+ continue
341
+ staged_items.append(_format_sast_annotation(f))
342
+
343
+ # 2. SCA Findings
344
+ sca_findings = scan_result.get("sca_findings", [])
345
+ if isinstance(sca_findings, list):
346
+ for sf in sca_findings:
347
+ staged_items.append(_format_sca_annotation(sf))
348
+
349
+ # 3. Secret Findings
350
+ secret_findings = scan_result.get("secret_findings", [])
351
+ if isinstance(secret_findings, list):
352
+ for sec in secret_findings:
353
+ staged_items.append(_format_secret_annotation(sec))
354
+
355
+ # Deterministic sort
356
+ staged_items.sort(key=lambda x: x[0])
357
+ return [item[1] for item in staged_items]
358
+
359
+
360
+ # Alias for format_github_annotations
361
+ generate_annotations = format_github_annotations
362
+
363
+
364
+ def generate_step_summary(scan_result: Dict[str, Any]) -> str:
365
+ """
366
+ Generates a deterministic Markdown summary document suitable for $GITHUB_STEP_SUMMARY.
367
+
368
+ Sections:
369
+ 1. # TimeCodeSecurity Scan (Title)
370
+ 2. Engine Status Table (SAST, SCA, Secrets)
371
+ 3. Security Metrics Table
372
+ 4. Findings Tables (SAST, SCA, Secrets) or Clean Message
373
+ """
374
+ if not isinstance(scan_result, dict):
375
+ scan_result = {}
376
+
377
+ lines: List[str] = ["# TimeCodeSecurity Scan", ""]
378
+
379
+ # ---------------------------------------------------------
380
+ # 1. Engine Status Determination
381
+ # ---------------------------------------------------------
382
+ # SAST
383
+ sast_findings = scan_result.get("findings", [])
384
+ active_sast = [f for f in sast_findings if isinstance(f, dict) and not f.get("suppressed", False)] if isinstance(sast_findings, list) else []
385
+ sast_status = "FOUND" if len(active_sast) > 0 else "CLEAN"
386
+ sast_count_str = str(len(active_sast))
387
+
388
+ # SCA
389
+ has_sca_key = "sca_findings" in scan_result
390
+ sca_findings = scan_result.get("sca_findings", []) if has_sca_key else []
391
+ if not isinstance(sca_findings, list):
392
+ sca_findings = []
393
+
394
+ if has_sca_key:
395
+ sca_unresolved_count = 0
396
+ for sf in sca_findings:
397
+ st = sf.get("status") if isinstance(sf, dict) else getattr(sf, "status", "")
398
+ if str(st).upper() == "UNRESOLVED":
399
+ sca_unresolved_count += 1
400
+
401
+ if sca_unresolved_count > 0:
402
+ sca_status = "UNRESOLVED"
403
+ elif len(sca_findings) > 0:
404
+ sca_status = "FOUND"
405
+ else:
406
+ sca_status = "CLEAN"
407
+ sca_count_str = str(len(sca_findings))
408
+ else:
409
+ sca_status = "INACTIVE"
410
+ sca_count_str = "-"
411
+ sca_unresolved_count = 0
412
+
413
+ # Secrets
414
+ has_sec_key = "secret_findings" in scan_result
415
+ sec_findings = scan_result.get("secret_findings", []) if has_sec_key else []
416
+ if not isinstance(sec_findings, list):
417
+ sec_findings = []
418
+
419
+ if has_sec_key:
420
+ sec_status = "FOUND" if len(sec_findings) > 0 else "CLEAN"
421
+ sec_count_str = str(len(sec_findings))
422
+ else:
423
+ sec_status = "INACTIVE"
424
+ sec_count_str = "-"
425
+
426
+ # Render Engine Status Table
427
+ lines.append("| Engine | Status | Findings |")
428
+ lines.append("|---|---|---:|")
429
+ lines.append(f"| SAST | {sast_status} | {sast_count_str} |")
430
+ lines.append(f"| SCA | {sca_status} | {sca_count_str} |")
431
+ lines.append(f"| Secrets | {sec_status} | {sec_count_str} |")
432
+ lines.append("")
433
+
434
+ # ---------------------------------------------------------
435
+ # 2. Security Metrics Table
436
+ # ---------------------------------------------------------
437
+ total_findings = len(active_sast) + len(sca_findings) + len(sec_findings)
438
+
439
+ lines.append("## Security Metrics")
440
+ lines.append("")
441
+ lines.append("| Metric | Value |")
442
+ lines.append("|---|---:|")
443
+ lines.append(f"| SAST findings | {len(active_sast)} |")
444
+ lines.append(f"| SCA findings | {len(sca_findings)} |")
445
+ lines.append(f"| SCA unresolved | {sca_unresolved_count} |")
446
+ lines.append(f"| Secret findings | {len(sec_findings)} |")
447
+ lines.append(f"| Total findings | {total_findings} |")
448
+ lines.append("")
449
+
450
+ # ---------------------------------------------------------
451
+ # 3. Finding Details Tables
452
+ # ---------------------------------------------------------
453
+ lines.append("## Findings")
454
+ lines.append("")
455
+
456
+ if total_findings == 0:
457
+ lines.append("*No vulnerabilities detected across active scanners.*")
458
+ lines.append("")
459
+ syntax_errors = scan_result.get("syntax_errors", [])
460
+ if isinstance(syntax_errors, list) and syntax_errors:
461
+ lines.append("### Parser Warnings")
462
+ lines.append("")
463
+ for err in syntax_errors:
464
+ lines.append(f"- ⚠️ Skipping AST analysis for unparseable file: `{err}`")
465
+ lines.append("")
466
+ return "\n".join(lines).rstrip() + "\n"
467
+
468
+ # SAST Table
469
+ if active_sast:
470
+ sorted_sast = sorted(
471
+ active_sast,
472
+ key=lambda f: (
473
+ _normalize_path(f.get("file")),
474
+ int(f.get("line_number") or 0),
475
+ int(f.get("column_start") or 0),
476
+ str(f.get("cwe", "")),
477
+ )
478
+ )
479
+ lines.append("### SAST Code Analysis")
480
+ lines.append("")
481
+ lines.append("| CWE | Severity | Location | Sink / Details |")
482
+ lines.append("|---|---|---|---|")
483
+ for f in sorted_sast:
484
+ cwe = f.get("cwe") or "CWE-UNKNOWN"
485
+ sev = str(f.get("severity") or "HIGH").upper()
486
+ loc = f"`{_normalize_path(f.get('file', ''))}:{f.get('line_number', '')}`"
487
+ sink_sym = f.get("sink_symbol")
488
+ detail = (sanitize_symbol_display(sink_sym) if sink_sym else
489
+ f.get("flow_trace_summary") or f.get("code_snippet") or "Dataflow vulnerability")
490
+ clean_detail = str(detail).replace("|", "\\|").replace("\n", " ").strip()
491
+ lines.append(f"| {cwe} | {sev} | {loc} | {clean_detail} |")
492
+ lines.append("")
493
+
494
+ # SCA Table
495
+ if sca_findings:
496
+ def _sca_sort_key(item: Any):
497
+ sf = item if isinstance(item, dict) else (item.to_dict() if hasattr(item, "to_dict") else getattr(item, "__dict__", {}))
498
+ return (
499
+ _normalize_path(sf.get("manifest_source")),
500
+ int(sf.get("line_number") or 0),
501
+ str(sf.get("package_name", "")),
502
+ str(sf.get("vulnerability_id", "")),
503
+ )
504
+
505
+ sorted_sca = sorted(sca_findings, key=_sca_sort_key)
506
+ lines.append("### SCA Dependencies")
507
+ lines.append("")
508
+ lines.append("| Package | Vulnerability | Severity | Status | Fixed Version | Manifest |")
509
+ lines.append("|---|---|---|---|---|---|")
510
+ for item in sorted_sca:
511
+ sf = item if isinstance(item, dict) else (item.to_dict() if hasattr(item, "to_dict") else getattr(item, "__dict__", {}))
512
+ pkg = sf.get("package_name") or "-"
513
+ vid = sf.get("vulnerability_id") or "-"
514
+ sev = str(sf.get("severity") or "UNKNOWN").upper()
515
+ st = str(sf.get("status") or "POTENTIAL").upper()
516
+ fixed = sf.get("fixed_version") or "-"
517
+ line_str = f":{sf.get('line_number')}" if sf.get("line_number") else ""
518
+ manifest = f"`{_normalize_path(sf.get('manifest_source', ''))}{line_str}`"
519
+ lines.append(f"| {pkg} | {vid} | {sev} | {st} | {fixed} | {manifest} |")
520
+ lines.append("")
521
+
522
+ # Secrets Table
523
+ if sec_findings:
524
+ def _sec_sort_key(item: Any):
525
+ sec = item if isinstance(item, dict) else (item.to_dict() if hasattr(item, "to_dict") else getattr(item, "__dict__", {}))
526
+ return (
527
+ _normalize_path(sec.get("file")),
528
+ int(sec.get("line_number") or 0),
529
+ int(sec.get("column_start") or 0),
530
+ str(sec.get("secret_type", "")),
531
+ )
532
+
533
+ sorted_sec = sorted(sec_findings, key=_sec_sort_key)
534
+ lines.append("### Secret Scanning (CWE-798)")
535
+ lines.append("")
536
+ lines.append("| Type | Masked Value | Location | Confidence | Detector |")
537
+ lines.append("|---|---|---|---|---|")
538
+ for item in sorted_sec:
539
+ sec = item if isinstance(item, dict) else (item.to_dict() if hasattr(item, "to_dict") else getattr(item, "__dict__", {}))
540
+ stype = sec.get("secret_type") or "secret"
541
+ label = _SECRET_TYPE_LABELS.get(stype, stype.replace("_", " ").title())
542
+ # Zero raw secret exposure: only masked value is formatted
543
+ mv = f"`{sec.get('masked_value', '********')}`"
544
+ line_str = f":{sec.get('line_number')}" if sec.get("line_number") else ""
545
+ loc = f"`{_normalize_path(sec.get('file', ''))}{line_str}`"
546
+ conf = str(sec.get("confidence") or "HIGH").upper()
547
+ det = sec.get("detector") or stype
548
+ lines.append(f"| {label} | {mv} | {loc} | {conf} | {det} |")
549
+ lines.append("")
550
+
551
+ syntax_errors = scan_result.get("syntax_errors", [])
552
+ if isinstance(syntax_errors, list) and syntax_errors:
553
+ lines.append("### Parser Warnings")
554
+ lines.append("")
555
+ for err in syntax_errors:
556
+ lines.append(f"- ⚠️ Skipping AST analysis for unparseable file: `{err}`")
557
+ lines.append("")
558
+
559
+ return "\n".join(lines).rstrip() + "\n"
560
+
561
+
562
+ def write_step_summary(scan_result: Dict[str, Any], output_stream=None) -> str:
563
+ """
564
+ Helper to render and optionally write the step summary to a stream (e.g. sys.stdout or open file).
565
+ Returns the generated Markdown string.
566
+ """
567
+ content = generate_step_summary(scan_result)
568
+ if output_stream is not None:
569
+ output_stream.write(content)
570
+ return content