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
tcs_config.py ADDED
@@ -0,0 +1,218 @@
1
+ """Root `.tcs.yaml`: repository-level path exclusions and per-rule path overrides.
2
+
3
+ Schema (only these keys; anything else is rejected so a typo cannot silently exempt a tree):
4
+
5
+ exclude_paths: ["tests/**", "docs/**"]
6
+ rules:
7
+ CWE-338:
8
+ exclude: ["**/demo/**", "**/fixtures/**"]
9
+
10
+ Matching is segment-aware: `**` spans zero or more path segments, which fnmatch cannot
11
+ express because its `*` already swallows `/`. A pattern with no `/` matches any single path
12
+ segment, mirroring `--exclude` (`tests` hits `a/tests/b.py`).
13
+
14
+ Anchored patterns are matched both against the collected path and against that path seen
15
+ from inside the scan root, so `docs/**` means the same thing whether the user runs
16
+ `scan .` or `scan target_arena` (see `without_root_prefix`).
17
+
18
+ The file is read from the working directory and only when it exists, so a scan without
19
+ `.tcs.yaml` behaves exactly as it did before this module existed.
20
+ """
21
+
22
+ from dataclasses import dataclass, field
23
+ from fnmatch import fnmatchcase
24
+ from pathlib import Path
25
+ from typing import Dict, List, Optional, Tuple
26
+
27
+ CONFIG_FILENAME = ".tcs.yaml"
28
+ _ALLOWED_TOP_LEVEL = frozenset({"exclude_paths", "rules"})
29
+ _ALLOWED_RULE_KEYS = frozenset({"exclude"})
30
+ # Patterns are declared once per config load and asked about per finding, so the
31
+ # anchored-vs-depth-free split is worth one dict keyed by the (immutable) pattern tuple.
32
+ _ANCHORED_CACHE: Dict[Tuple[str, ...], Tuple[str, ...]] = {}
33
+
34
+
35
+ def _normalize_pattern(pattern: str) -> str:
36
+ text = str(pattern).replace("\\", "/").strip()
37
+ while text.startswith("./"):
38
+ text = text[2:]
39
+ return text.strip("/")
40
+
41
+
42
+ def _segments(text: str) -> List[str]:
43
+ return [part for part in text.split("/") if part not in ("", ".")]
44
+
45
+
46
+ def _match_parts(path_parts: List[str], pattern_parts: List[str]) -> bool:
47
+ if not pattern_parts:
48
+ return not path_parts
49
+ head = pattern_parts[0]
50
+ if head == "**":
51
+ return _match_parts(path_parts, pattern_parts[1:]) or (
52
+ bool(path_parts) and _match_parts(path_parts[1:], pattern_parts))
53
+ if not path_parts:
54
+ return False
55
+ if not fnmatchcase(path_parts[0], head):
56
+ return False
57
+ return _match_parts(path_parts[1:], pattern_parts[1:])
58
+
59
+
60
+ def path_matches(path_key: str, pattern: str) -> bool:
61
+ """True when `path_key` is selected by one `.tcs.yaml` glob."""
62
+ normalized = _normalize_pattern(pattern)
63
+ if not normalized:
64
+ return False
65
+ parts = _segments(str(path_key).replace("\\", "/"))
66
+ if "/" not in normalized:
67
+ return any(fnmatchcase(part, normalized) for part in parts)
68
+ return _match_parts(parts, _segments(normalized))
69
+
70
+
71
+ def without_root_prefix(path_key: str, root: Optional[str]) -> str:
72
+ """`path_key` with the scan root's own segments removed.
73
+
74
+ Keys reach here carrying the root the user typed: scanning `target_arena` yields
75
+ `target_arena/tests/x.py`, so a pattern anchored on the repository layout (`tests/**`,
76
+ `docs/**`) matches nothing and the exclusion the user wrote is silently ignored --
77
+ which overstates coverage exactly like a missed finding. Stripping the root makes an
78
+ anchored pattern mean what it says at any invocation depth.
79
+
80
+ Returns the key unchanged when there is no root, when the root is `.` , or when the key
81
+ does not start with it, so this can only ever shorten a key, never invent segments.
82
+ """
83
+ key = str(path_key).replace("\\", "/")
84
+ root_parts = _segments(_normalize_pattern(str(root or "")))
85
+ if not root_parts:
86
+ return key
87
+ parts = _segments(key)
88
+ if parts[:len(root_parts)] != root_parts:
89
+ return key
90
+ return "/".join(parts[len(root_parts):])
91
+
92
+
93
+ def anchored_patterns(patterns: Tuple[str, ...]) -> Tuple[str, ...]:
94
+ """The subset of `patterns` whose result can change when the root prefix is removed.
95
+
96
+ A pattern with no `/` matches any single segment, so it hits the stripped key only by
97
+ hitting the raw one. A pattern that opens with `**/` already tries every starting
98
+ segment, so the extra prefix cannot hide it either. Only an anchored pattern
99
+ (`tests/**`) distinguishes the two spellings, and testing just those keeps the second
100
+ pass proportional to the anchored rules a repository actually declares.
101
+ """
102
+ cache_key = patterns if isinstance(patterns, tuple) else tuple(patterns)
103
+ cached = _ANCHORED_CACHE.get(cache_key)
104
+ if cached is not None:
105
+ return cached
106
+ selected = tuple(pattern for pattern in cache_key
107
+ if "/" in (text := _normalize_pattern(pattern))
108
+ and not text.startswith("**/"))
109
+ _ANCHORED_CACHE[cache_key] = selected
110
+ return selected
111
+
112
+
113
+ def normalize_rule_id(value: str) -> Optional[str]:
114
+ text = str(value).strip().upper()
115
+ if text.startswith("CWE-") and text[4:].isdigit():
116
+ return text
117
+ if text.startswith("CWE") and text[3:].strip("-").isdigit():
118
+ return f"CWE-{text[3:].strip('-')}"
119
+ if text.isdigit():
120
+ return f"CWE-{text}"
121
+ return None
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class TcsConfig:
126
+ exclude_paths: Tuple[str, ...] = ()
127
+ rule_excludes: Dict[str, Tuple[str, ...]] = field(default_factory=dict)
128
+
129
+ def excludes_path(self, path_key: str, root: Optional[str] = None) -> bool:
130
+ return self._selects(self.exclude_paths, path_key, root)
131
+
132
+ def rule_excluded(self, cwe: str, path_key: str,
133
+ root: Optional[str] = None) -> bool:
134
+ return self._selects(self.rule_excludes.get(str(cwe).upper()), path_key, root)
135
+
136
+ @staticmethod
137
+ def _selects(patterns, path_key: str, root: Optional[str]) -> bool:
138
+ """True when one glob selects this path, seen from the working directory or from
139
+ inside the scan root.
140
+
141
+ Both spellings are tried so a pattern that names the root (`arena/docs/**`) keeps
142
+ working while an anchored in-root pattern (`docs/**`) stops being ignored when the
143
+ scan is aimed at a subdirectory -- a silently-ignored exclusion overstates coverage
144
+ exactly like a missed finding. Selection stays monotone: a path selected before is
145
+ still selected, and the stripped key is derived once per call, only when the prefix
146
+ really matches.
147
+ """
148
+ if not patterns:
149
+ return False
150
+ key = str(path_key)
151
+ if any(path_matches(key, pattern) for pattern in patterns):
152
+ return True
153
+ if not root:
154
+ return False
155
+ anchored = anchored_patterns(patterns)
156
+ if not anchored:
157
+ return False
158
+ stripped = without_root_prefix(key, root)
159
+ if stripped == key or not stripped:
160
+ return False
161
+ return any(path_matches(stripped, pattern) for pattern in anchored)
162
+
163
+
164
+ def _string_list(value, where: str) -> Tuple[str, ...]:
165
+ if value is None:
166
+ return ()
167
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
168
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: {where} must be a list of strings")
169
+ return tuple(item for item in value if item.strip())
170
+
171
+
172
+ def load_config(directory: Optional[Path] = None) -> Optional[TcsConfig]:
173
+ """Return the parsed `.tcs.yaml` in `directory`, or None when the file is absent.
174
+
175
+ A malformed file raises ValueError: an exclusion the user wrote but the scanner
176
+ ignored would overstate coverage, which is the same harm as a missed finding.
177
+ """
178
+ base = Path(directory) if directory is not None else Path.cwd()
179
+ path = base / CONFIG_FILENAME
180
+ if not path.is_file():
181
+ return None
182
+ try:
183
+ import yaml
184
+ except ImportError as exc:
185
+ raise ValueError(f"{CONFIG_FILENAME} present but PyYAML is not installed") from exc
186
+
187
+ try:
188
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
189
+ except yaml.YAMLError as exc:
190
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: {exc}") from exc
191
+
192
+ if data is None:
193
+ data = {}
194
+ if not isinstance(data, dict):
195
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: top level must be a mapping")
196
+ unknown = sorted(set(data) - _ALLOWED_TOP_LEVEL)
197
+ if unknown:
198
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: unknown key(s) {unknown}")
199
+
200
+ exclude_paths = _string_list(data.get("exclude_paths"), "exclude_paths")
201
+
202
+ rules_raw = data.get("rules") or {}
203
+ if not isinstance(rules_raw, dict):
204
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: rules must be a mapping")
205
+ rule_excludes: Dict[str, Tuple[str, ...]] = {}
206
+ for rule_id, body in rules_raw.items():
207
+ cwe = normalize_rule_id(rule_id)
208
+ if cwe is None:
209
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: {rule_id!r} is not a CWE id")
210
+ if not isinstance(body, dict):
211
+ raise ValueError(f"Invalid {CONFIG_FILENAME}: rules.{rule_id} must be a mapping")
212
+ unknown_rule = sorted(set(body) - _ALLOWED_RULE_KEYS)
213
+ if unknown_rule:
214
+ raise ValueError(
215
+ f"Invalid {CONFIG_FILENAME}: unknown key(s) {unknown_rule} under rules.{rule_id}")
216
+ rule_excludes[cwe] = _string_list(body.get("exclude"), f"rules.{rule_id}.exclude")
217
+
218
+ return TcsConfig(exclude_paths=exclude_paths, rule_excludes=rule_excludes)