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
webhook_client.py ADDED
@@ -0,0 +1,483 @@
1
+ """
2
+ TimeCodeSecurity Pinned-IP HTTPS Webhook Client.
3
+
4
+ Defines:
5
+ - DeliveryStatus: 16 discrete delivery outcome classifications.
6
+ - WebhookAuthConfig: Configuration-only secret token model.
7
+ - PinnedIPHTTPSConnection: Custom HTTPSConnection preventing DNS rebinding
8
+ by connecting directly to validated IP while preserving TLS SNI.
9
+ - WebhookClient: Outbound delivery transport enforcing strict TLS,
10
+ 10.0s monotonic deadline checks, bounded retries, and error sanitization.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import hmac
17
+ import http.client
18
+ import logging
19
+ import socket
20
+ import ssl
21
+ import time
22
+ import urllib.parse
23
+ from dataclasses import dataclass
24
+ from enum import Enum
25
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
26
+
27
+ from ssrf_guard import DNSResolutionError, SSRFGuard, SSRFValidationError, SSRFValidationResult
28
+
29
+ logger = logging.getLogger("tcs.webhook_client")
30
+
31
+ MAX_ERROR_MESSAGE_LENGTH = 512
32
+ DEFAULT_RETRY_BACKOFF_SECONDS: float = 1.0
33
+ MAX_DELIVERY_ATTEMPTS: int = 2
34
+
35
+
36
+ class DeliveryStatus(str, Enum):
37
+ """Refined 16-state delivery outcome classification."""
38
+ SUCCESS = "SUCCESS"
39
+ SSRF_BLOCKED = "SSRF_BLOCKED"
40
+ DNS_RESOLUTION_FAILED = "DNS_RESOLUTION_FAILED"
41
+ CONNECTION_TIMEOUT = "CONNECTION_TIMEOUT"
42
+ READ_TIMEOUT = "READ_TIMEOUT"
43
+ TLS_ERROR = "TLS_ERROR"
44
+ CONNECTION_REFUSED = "CONNECTION_REFUSED"
45
+ HTTP_CLIENT_ERROR = "HTTP_CLIENT_ERROR"
46
+ HTTP_RATE_LIMITED = "HTTP_RATE_LIMITED"
47
+ HTTP_SERVER_ERROR = "HTTP_SERVER_ERROR"
48
+ REDIRECT_BLOCKED = "REDIRECT_BLOCKED"
49
+ PAYLOAD_TOO_LARGE = "PAYLOAD_TOO_LARGE"
50
+ QUEUE_OVERFLOW = "QUEUE_OVERFLOW"
51
+ PAYLOAD_INVALID = "PAYLOAD_INVALID"
52
+ SHUTDOWN_ABORTED = "SHUTDOWN_ABORTED"
53
+ INTERNAL_ERROR = "INTERNAL_ERROR"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class WebhookAuthConfig:
58
+ """
59
+ Configuration-only authentication credentials.
60
+ Strict invariant: secret_token MUST NEVER appear in SecurityDomainEvent,
61
+ NotificationIntent, payload bodies, DeliveryResult, logs, or error messages.
62
+ """
63
+ secret_token: Optional[str] = None
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class ClientExecutionResult:
68
+ """Internal delivery outcome returned by WebhookClient."""
69
+ success: bool
70
+ status: DeliveryStatus
71
+ status_code: Optional[int]
72
+ error_message: Optional[str]
73
+ duration_ms: float
74
+ attempts: int
75
+ target_ip: Optional[str] = None
76
+
77
+
78
+ class PinnedIPHTTPSConnection(http.client.HTTPSConnection):
79
+ """
80
+ HTTPSConnection that binds directly to a pre-validated IP address,
81
+ preventing DNS rebinding (TOCTOU) attacks while retaining the original
82
+ hostname for TLS SNI and X.509 certificate verification.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ target_ip: str,
88
+ hostname: str,
89
+ port: int = 443,
90
+ timeout: float = 3.0,
91
+ ssl_context: Optional[ssl.SSLContext] = None,
92
+ socket_factory: Optional[Callable[..., socket.socket]] = None,
93
+ ) -> None:
94
+ super().__init__(host=hostname, port=port, timeout=timeout)
95
+ self.target_ip = target_ip
96
+ self.original_hostname = hostname
97
+
98
+ if ssl_context is None:
99
+ ctx = ssl.create_default_context()
100
+ ctx.verify_mode = ssl.CERT_REQUIRED
101
+ ctx.check_hostname = True
102
+ self.ssl_context = ctx
103
+ else:
104
+ # Enforce TLS security invariants: NEVER CERT_NONE, NEVER check_hostname=False
105
+ if ssl_context.verify_mode == ssl.CERT_NONE:
106
+ raise ValueError("Insecure TLS configuration: CERT_NONE is strictly forbidden.")
107
+ if not ssl_context.check_hostname:
108
+ raise ValueError("Insecure TLS configuration: check_hostname=False is strictly forbidden.")
109
+ self.ssl_context = ssl_context
110
+
111
+ self.socket_factory = socket_factory or socket.create_connection
112
+
113
+ def connect(self) -> None:
114
+ """
115
+ Connects TCP directly to target_ip without secondary DNS query,
116
+ then performs TLS handshake validating original_hostname.
117
+ """
118
+ raw_sock = self.socket_factory(
119
+ (self.target_ip, self.port),
120
+ timeout=self.timeout
121
+ )
122
+ self.sock = self.ssl_context.wrap_socket(
123
+ raw_sock,
124
+ server_hostname=self.original_hostname
125
+ )
126
+
127
+
128
+ def compute_webhook_signature(secret_token: str, payload_bytes: bytes) -> str:
129
+ """
130
+ Computes HMAC-SHA256 signature over the EXACT transmitted UTF-8 payload bytes.
131
+ """
132
+ return hmac.new(
133
+ secret_token.encode("utf-8"),
134
+ payload_bytes,
135
+ hashlib.sha256
136
+ ).hexdigest()
137
+
138
+
139
+ class WebhookClient:
140
+ """
141
+ Hardened outbound HTTP client for webhook delivery.
142
+ Enforces 10.0s monotonic deadline checks across all deadline-aware phases,
143
+ SSRF validation, pinned IP TLS, redirect blocking, and retry policies.
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ ssrf_guard: Optional[SSRFGuard] = None,
149
+ clock: Callable[[], float] = time.monotonic,
150
+ sleep_fn: Callable[[float], None] = time.sleep,
151
+ socket_factory: Optional[Callable[..., socket.socket]] = None,
152
+ ssl_context: Optional[ssl.SSLContext] = None,
153
+ http_connection_factory: Optional[Callable[..., http.client.HTTPSConnection]] = None,
154
+ ) -> None:
155
+ self._ssrf_guard = ssrf_guard or SSRFGuard()
156
+ self._clock = clock
157
+ self._sleep_fn = sleep_fn
158
+ self._socket_factory = socket_factory
159
+ self._ssl_context = ssl_context
160
+ self._http_connection_factory = http_connection_factory
161
+
162
+ def send(
163
+ self,
164
+ url: str,
165
+ payload_bytes: bytes,
166
+ auth_config: Optional[WebhookAuthConfig] = None,
167
+ idempotency_key: str = "",
168
+ ) -> ClientExecutionResult:
169
+ """
170
+ Executes outbound HTTPS delivery adhering to all Phase 15C security invariants.
171
+ Enforces monotonic deadline, pinned IP connection, strict TLS, and bounded retries.
172
+ """
173
+ start_time = self._clock()
174
+ overall_deadline = start_time + 10.0
175
+
176
+ def remaining_deadline() -> float:
177
+ rem = overall_deadline - self._clock()
178
+ return rem
179
+
180
+ # 1. Monotonic Deadline Check: before DNS
181
+ if remaining_deadline() <= 0:
182
+ return ClientExecutionResult(
183
+ success=False,
184
+ status=DeliveryStatus.CONNECTION_TIMEOUT,
185
+ status_code=None,
186
+ error_message="overall deadline exceeded before DNS resolution",
187
+ duration_ms=0.0,
188
+ attempts=0,
189
+ )
190
+
191
+ # 2. SSRF Validation & Deterministic IP Pinning
192
+ try:
193
+ ssrf_res = self._ssrf_guard.validate_url(url)
194
+ except DNSResolutionError as exc:
195
+ return ClientExecutionResult(
196
+ success=False,
197
+ status=DeliveryStatus.DNS_RESOLUTION_FAILED,
198
+ status_code=None,
199
+ error_message=str(exc)[:MAX_ERROR_MESSAGE_LENGTH],
200
+ duration_ms=(self._clock() - start_time) * 1000.0,
201
+ attempts=0,
202
+ )
203
+ except SSRFValidationError as exc:
204
+ return ClientExecutionResult(
205
+ success=False,
206
+ status=DeliveryStatus.SSRF_BLOCKED,
207
+ status_code=None,
208
+ error_message=str(exc)[:MAX_ERROR_MESSAGE_LENGTH],
209
+ duration_ms=(self._clock() - start_time) * 1000.0,
210
+ attempts=0,
211
+ )
212
+ except Exception as exc:
213
+ return ClientExecutionResult(
214
+ success=False,
215
+ status=DeliveryStatus.SSRF_BLOCKED,
216
+ status_code=None,
217
+ error_message=f"SSRF validation exception: {exc}"[:MAX_ERROR_MESSAGE_LENGTH],
218
+ duration_ms=(self._clock() - start_time) * 1000.0,
219
+ attempts=0,
220
+ )
221
+
222
+ target_ip = ssrf_res.target_ip
223
+ hostname = ssrf_res.hostname
224
+ port = ssrf_res.port
225
+
226
+ # 3. Monotonic Deadline Check: after DNS
227
+ if remaining_deadline() <= 0:
228
+ return ClientExecutionResult(
229
+ success=False,
230
+ status=DeliveryStatus.CONNECTION_TIMEOUT,
231
+ status_code=None,
232
+ error_message="overall deadline exceeded after DNS resolution",
233
+ duration_ms=(self._clock() - start_time) * 1000.0,
234
+ attempts=0,
235
+ target_ip=target_ip,
236
+ )
237
+
238
+ # Prepare request URI and headers
239
+ parsed = urllib.parse.urlsplit(url)
240
+ path = parsed.path or "/"
241
+ if parsed.query:
242
+ path = f"{path}?{parsed.query}"
243
+
244
+ headers: Dict[str, str] = {
245
+ "Content-Type": "application/json; charset=utf-8",
246
+ "User-Agent": "TimeCodeSecurity-Webhook-Delivery/1.0",
247
+ "Content-Length": str(len(payload_bytes)),
248
+ }
249
+ if idempotency_key:
250
+ headers["Idempotency-Key"] = idempotency_key
251
+
252
+ if auth_config and auth_config.secret_token:
253
+ sig = compute_webhook_signature(auth_config.secret_token, payload_bytes)
254
+ headers["X-TIMECODESECURITY-Signature"] = f"sha256={sig}"
255
+
256
+ attempts = 0
257
+ max_attempts = 2
258
+
259
+ while attempts < max_attempts:
260
+ attempts += 1
261
+
262
+ # 4. Monotonic Deadline Check: before connect
263
+ rem = remaining_deadline()
264
+ if rem <= 0:
265
+ return ClientExecutionResult(
266
+ success=False,
267
+ status=DeliveryStatus.CONNECTION_TIMEOUT,
268
+ status_code=None,
269
+ error_message="overall deadline exceeded before connect",
270
+ duration_ms=(self._clock() - start_time) * 1000.0,
271
+ attempts=attempts,
272
+ target_ip=target_ip,
273
+ )
274
+
275
+ connect_timeout = min(3.0, rem)
276
+
277
+ conn: Optional[Union[PinnedIPHTTPSConnection, http.client.HTTPSConnection]] = None
278
+ try:
279
+ if self._http_connection_factory is not None:
280
+ conn = self._http_connection_factory(
281
+ target_ip=target_ip,
282
+ hostname=hostname,
283
+ port=port,
284
+ timeout=connect_timeout,
285
+ )
286
+ else:
287
+ conn = PinnedIPHTTPSConnection(
288
+ target_ip=target_ip,
289
+ hostname=hostname,
290
+ port=port,
291
+ timeout=connect_timeout,
292
+ ssl_context=self._ssl_context,
293
+ socket_factory=self._socket_factory,
294
+ )
295
+
296
+ # Connect phase
297
+ conn.connect()
298
+
299
+ # 5. Monotonic Deadline Check: before read
300
+ rem = remaining_deadline()
301
+ if rem <= 0:
302
+ return ClientExecutionResult(
303
+ success=False,
304
+ status=DeliveryStatus.READ_TIMEOUT,
305
+ status_code=None,
306
+ error_message="overall deadline exceeded before read",
307
+ duration_ms=(self._clock() - start_time) * 1000.0,
308
+ attempts=attempts,
309
+ target_ip=target_ip,
310
+ )
311
+
312
+ read_timeout = min(5.0, rem)
313
+ conn.sock.settimeout(read_timeout)
314
+
315
+ # Send request
316
+ conn.request("POST", path, body=payload_bytes, headers=headers)
317
+ resp = conn.getresponse()
318
+ status_code = resp.status
319
+
320
+ # Read response safely (bounded, discard raw content)
321
+ resp.read(1024)
322
+
323
+ # 6. Evaluate HTTP Response
324
+ # Redirects: Strictly disabled
325
+ if status_code in (301, 302, 303, 307, 308):
326
+ return ClientExecutionResult(
327
+ success=False,
328
+ status=DeliveryStatus.REDIRECT_BLOCKED,
329
+ status_code=status_code,
330
+ error_message="HTTP redirect blocked",
331
+ duration_ms=(self._clock() - start_time) * 1000.0,
332
+ attempts=attempts,
333
+ target_ip=target_ip,
334
+ )
335
+
336
+ # Success: 200-299
337
+ if 200 <= status_code < 300:
338
+ return ClientExecutionResult(
339
+ success=True,
340
+ status=DeliveryStatus.SUCCESS,
341
+ status_code=status_code,
342
+ error_message=None,
343
+ duration_ms=(self._clock() - start_time) * 1000.0,
344
+ attempts=attempts,
345
+ target_ip=target_ip,
346
+ )
347
+
348
+ # Rate Limited: 429
349
+ if status_code == 429:
350
+ retry_after_hdr = resp.getheader("Retry-After")
351
+ should_retry = False
352
+ retry_delay = 0.0
353
+
354
+ if retry_after_hdr:
355
+ try:
356
+ val = int(retry_after_hdr.strip())
357
+ if 0 < val <= 2:
358
+ should_retry = True
359
+ retry_delay = float(val)
360
+ except (ValueError, TypeError):
361
+ should_retry = False
362
+
363
+ if should_retry and attempts < max_attempts:
364
+ # Check deadline before retry sleep
365
+ if remaining_deadline() > (retry_delay + 0.5):
366
+ self._sleep_fn(retry_delay)
367
+ continue
368
+
369
+ return ClientExecutionResult(
370
+ success=False,
371
+ status=DeliveryStatus.HTTP_RATE_LIMITED,
372
+ status_code=status_code,
373
+ error_message="HTTP 429",
374
+ duration_ms=(self._clock() - start_time) * 1000.0,
375
+ attempts=attempts,
376
+ target_ip=target_ip,
377
+ )
378
+
379
+ # Client Errors: 400-499 (except 429) -> Zero retries
380
+ if 400 <= status_code < 500:
381
+ return ClientExecutionResult(
382
+ success=False,
383
+ status=DeliveryStatus.HTTP_CLIENT_ERROR,
384
+ status_code=status_code,
385
+ error_message=f"HTTP {status_code}",
386
+ duration_ms=(self._clock() - start_time) * 1000.0,
387
+ attempts=attempts,
388
+ target_ip=target_ip,
389
+ )
390
+
391
+ # Server Errors: 500-599
392
+ if 500 <= status_code < 600:
393
+ if attempts < max_attempts:
394
+ backoff = DEFAULT_RETRY_BACKOFF_SECONDS
395
+ if remaining_deadline() > backoff:
396
+ self._sleep_fn(backoff)
397
+ continue
398
+
399
+ return ClientExecutionResult(
400
+ success=False,
401
+ status=DeliveryStatus.HTTP_SERVER_ERROR,
402
+ status_code=status_code,
403
+ error_message=f"HTTP {status_code}",
404
+ duration_ms=(self._clock() - start_time) * 1000.0,
405
+ attempts=attempts,
406
+ target_ip=target_ip,
407
+ )
408
+
409
+ # Unexpected status code
410
+ return ClientExecutionResult(
411
+ success=False,
412
+ status=DeliveryStatus.HTTP_SERVER_ERROR,
413
+ status_code=status_code,
414
+ error_message=f"HTTP {status_code}",
415
+ duration_ms=(self._clock() - start_time) * 1000.0,
416
+ attempts=attempts,
417
+ target_ip=target_ip,
418
+ )
419
+
420
+ except (socket.timeout, TimeoutError):
421
+ if attempts < max_attempts and remaining_deadline() > DEFAULT_RETRY_BACKOFF_SECONDS:
422
+ self._sleep_fn(DEFAULT_RETRY_BACKOFF_SECONDS)
423
+ continue
424
+ return ClientExecutionResult(
425
+ success=False,
426
+ status=DeliveryStatus.CONNECTION_TIMEOUT,
427
+ status_code=None,
428
+ error_message="connect timeout",
429
+ duration_ms=(self._clock() - start_time) * 1000.0,
430
+ attempts=attempts,
431
+ target_ip=target_ip,
432
+ )
433
+
434
+ except ssl.SSLError:
435
+ return ClientExecutionResult(
436
+ success=False,
437
+ status=DeliveryStatus.TLS_ERROR,
438
+ status_code=None,
439
+ error_message="TLS verification failed",
440
+ duration_ms=(self._clock() - start_time) * 1000.0,
441
+ attempts=attempts,
442
+ target_ip=target_ip,
443
+ )
444
+
445
+ except ConnectionRefusedError:
446
+ return ClientExecutionResult(
447
+ success=False,
448
+ status=DeliveryStatus.CONNECTION_REFUSED,
449
+ status_code=None,
450
+ error_message="connection refused",
451
+ duration_ms=(self._clock() - start_time) * 1000.0,
452
+ attempts=attempts,
453
+ target_ip=target_ip,
454
+ )
455
+
456
+ except Exception as exc:
457
+ return ClientExecutionResult(
458
+ success=False,
459
+ status=DeliveryStatus.INTERNAL_ERROR,
460
+ status_code=None,
461
+ error_message=f"Delivery error: {exc}"[:MAX_ERROR_MESSAGE_LENGTH],
462
+ duration_ms=(self._clock() - start_time) * 1000.0,
463
+ attempts=attempts,
464
+ target_ip=target_ip,
465
+ )
466
+
467
+ finally:
468
+ if conn:
469
+ try:
470
+ conn.close()
471
+ except Exception:
472
+ pass
473
+
474
+ # If exhausted attempts
475
+ return ClientExecutionResult(
476
+ success=False,
477
+ status=DeliveryStatus.HTTP_SERVER_ERROR,
478
+ status_code=None,
479
+ error_message="Maximum delivery attempts exceeded",
480
+ duration_ms=(self._clock() - start_time) * 1000.0,
481
+ attempts=attempts,
482
+ target_ip=target_ip,
483
+ )