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
@@ -0,0 +1,277 @@
1
+ """
2
+ TimeCodeSecurity SQLite/SQLAlchemy Delivery Repository.
3
+
4
+ Concrete implementation of DeliveryRepository using SQLAlchemy and SQLite/PostgreSQL.
5
+ Enforces multi-tenant isolation, deterministic ordering, and append-only audit retention.
6
+
7
+ Invariants:
8
+ - All operations require organization_id.
9
+ - Pagination strictly orders by created_at DESC, id DESC.
10
+ - Limit is bounded between 1 and 100; offset is >= 0.
11
+ - Append-only: strictly no update or delete methods exist.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import datetime
17
+ import uuid
18
+ from contextlib import contextmanager
19
+ from typing import Any, Generator, List, Optional, Tuple, Union
20
+
21
+ from sqlalchemy import and_, event, func
22
+ from sqlalchemy.engine import Engine
23
+ from sqlalchemy.orm import Session, sessionmaker
24
+
25
+ from delivery_models import (
26
+ Base,
27
+ DeliveryAuditLog,
28
+ DeliveryAuditLogCreate,
29
+ DeliveryStatsResponse,
30
+ MAX_AUDIT_ERROR_LENGTH,
31
+ )
32
+ from delivery_repository import DeliveryRepository
33
+
34
+
35
+ def configure_sqlite_pragmas(target_engine: Engine) -> None:
36
+ """
37
+ Configures critical SQLite pragmas:
38
+ - PRAGMA foreign_keys=ON: Relational integrity.
39
+ - PRAGMA busy_timeout=5000: Prevents 'database is locked' errors during concurrency.
40
+ - PRAGMA journal_mode=WAL: Concurrency optimization.
41
+ """
42
+ if target_engine is not None and target_engine.dialect.name == "sqlite":
43
+ @event.listens_for(target_engine, "connect")
44
+ def _set_sqlite_pragmas(dbapi_connection, connection_record):
45
+ cursor = dbapi_connection.cursor()
46
+ try:
47
+ cursor.execute("PRAGMA foreign_keys=ON")
48
+ cursor.execute("PRAGMA busy_timeout=5000")
49
+ try:
50
+ cursor.execute("PRAGMA journal_mode=WAL")
51
+ except Exception:
52
+ pass
53
+ except Exception:
54
+ pass
55
+ finally:
56
+ cursor.close()
57
+
58
+
59
+ class SqliteDeliveryRepository(DeliveryRepository):
60
+ """
61
+ SQLAlchemy-backed append-only repository for delivery audit logs.
62
+ Supports dependency-injected sessions, sessionmakers, or engines.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ session: Optional[Session] = None,
68
+ session_factory: Optional[sessionmaker] = None,
69
+ engine: Optional[Engine] = None,
70
+ ) -> None:
71
+ self._session = session
72
+ self._engine = engine
73
+ self._session_factory = session_factory
74
+
75
+ if self._engine is not None:
76
+ configure_sqlite_pragmas(self._engine)
77
+ if self._session_factory is None and self._session is None:
78
+ self._session_factory = sessionmaker(
79
+ autocommit=False,
80
+ autoflush=False,
81
+ bind=self._engine,
82
+ expire_on_commit=False,
83
+ )
84
+
85
+ if self._session is None and self._session_factory is None:
86
+ try:
87
+ from app import SessionLocal, engine as app_engine
88
+ self._engine = app_engine
89
+ self._session_factory = SessionLocal
90
+ if self._engine is not None:
91
+ configure_sqlite_pragmas(self._engine)
92
+ except Exception:
93
+ pass
94
+
95
+ @contextmanager
96
+ def _session_scope(self) -> Generator[Session, None, None]:
97
+ """Provides a safe transactional session scope."""
98
+ if self._session is not None:
99
+ yield self._session
100
+ elif self._session_factory is not None:
101
+ session = self._session_factory()
102
+ try:
103
+ yield session
104
+ session.commit()
105
+ except Exception:
106
+ session.rollback()
107
+ raise
108
+ finally:
109
+ session.close()
110
+ else:
111
+ raise RuntimeError(
112
+ "No SQLAlchemy session, session_factory, or engine configured for SqliteDeliveryRepository."
113
+ )
114
+
115
+ def init_db(self) -> None:
116
+ """Initializes tables in the bound engine or session bind."""
117
+ if self._engine is not None:
118
+ Base.metadata.create_all(bind=self._engine)
119
+ elif self._session is not None:
120
+ bind = self._session.get_bind()
121
+ if bind is not None:
122
+ Base.metadata.create_all(bind=bind)
123
+
124
+ def create(self, record: Union[DeliveryAuditLogCreate, Any, dict]) -> DeliveryAuditLog:
125
+ """
126
+ Appends a new delivery audit record.
127
+ Strictly append-only; handles DeliveryResult, DeliveryAuditLogCreate, or dict.
128
+ """
129
+ if isinstance(record, dict):
130
+ delivery_id = record.get("id") or f"deliv_{uuid.uuid4().hex}"
131
+ org_id = int(record["organization_id"])
132
+ event_id = str(record["event_id"])
133
+ scan_id = record.get("scan_id")
134
+ idempotency_key = str(record["idempotency_key"])
135
+ channel = str(record.get("channel", "WEBHOOK"))
136
+ status = record["status"]
137
+ status_code = record.get("status_code")
138
+ attempts = int(record.get("attempts", 1))
139
+ duration_ms = float(record.get("duration_ms", 0.0))
140
+ error_message = record.get("error_message")
141
+ created_at = record.get("created_at")
142
+ else:
143
+ delivery_id = getattr(record, "id", None) or f"deliv_{uuid.uuid4().hex}"
144
+ org_id = int(getattr(record, "organization_id"))
145
+ event_id = str(getattr(record, "event_id"))
146
+ scan_id = getattr(record, "scan_id", None)
147
+ idempotency_key = str(getattr(record, "idempotency_key"))
148
+ channel = str(getattr(record, "channel", "WEBHOOK"))
149
+ status = getattr(record, "status")
150
+ status_code = getattr(record, "status_code", None)
151
+ attempts = int(getattr(record, "attempts", 1))
152
+ duration_ms = float(getattr(record, "duration_ms", 0.0))
153
+ error_message = getattr(record, "error_message", None)
154
+ created_at = getattr(record, "created_at", None)
155
+
156
+ if hasattr(status, "value"):
157
+ status_str = status.value
158
+ else:
159
+ status_str = str(status)
160
+
161
+ if error_message and len(error_message) > MAX_AUDIT_ERROR_LENGTH:
162
+ error_message = error_message[:MAX_AUDIT_ERROR_LENGTH]
163
+
164
+ if created_at is None:
165
+ created_at = datetime.datetime.now(datetime.timezone.utc)
166
+ elif created_at.tzinfo is not None:
167
+ created_at = created_at.astimezone(datetime.timezone.utc).replace(tzinfo=None)
168
+
169
+ audit_entry = DeliveryAuditLog(
170
+ id=delivery_id,
171
+ organization_id=org_id,
172
+ event_id=event_id,
173
+ scan_id=scan_id,
174
+ idempotency_key=idempotency_key,
175
+ channel=channel,
176
+ status=status_str,
177
+ status_code=status_code,
178
+ attempts=attempts,
179
+ duration_ms=duration_ms,
180
+ error_message=error_message,
181
+ created_at=created_at,
182
+ )
183
+
184
+ with self._session_scope() as session:
185
+ session.add(audit_entry)
186
+ session.flush()
187
+ return audit_entry
188
+
189
+ def get_by_id(
190
+ self,
191
+ delivery_id: str,
192
+ organization_id: int,
193
+ ) -> Optional[DeliveryAuditLog]:
194
+ """
195
+ Retrieves a delivery audit log enforcing organization scoping.
196
+ Returns None if not found or unauthorized.
197
+ """
198
+ with self._session_scope() as session:
199
+ return (
200
+ session.query(DeliveryAuditLog)
201
+ .filter(
202
+ DeliveryAuditLog.id == delivery_id,
203
+ DeliveryAuditLog.organization_id == organization_id,
204
+ )
205
+ .first()
206
+ )
207
+
208
+ def list(
209
+ self,
210
+ organization_id: int,
211
+ status: Optional[str] = None,
212
+ limit: int = 50,
213
+ offset: int = 0,
214
+ ) -> Tuple[List[DeliveryAuditLog], int]:
215
+ """
216
+ Lists delivery audit logs with deterministic ordering:
217
+ ORDER BY created_at DESC, id DESC.
218
+ """
219
+ clamped_limit = max(1, min(100, int(limit)))
220
+ clamped_offset = max(0, int(offset))
221
+
222
+ with self._session_scope() as session:
223
+ query = session.query(DeliveryAuditLog).filter(
224
+ DeliveryAuditLog.organization_id == organization_id
225
+ )
226
+ if status:
227
+ query = query.filter(DeliveryAuditLog.status == status)
228
+
229
+ total_count = query.count()
230
+ items = (
231
+ query.order_by(
232
+ DeliveryAuditLog.created_at.desc(),
233
+ DeliveryAuditLog.id.desc(),
234
+ )
235
+ .offset(clamped_offset)
236
+ .limit(clamped_limit)
237
+ .all()
238
+ )
239
+ return items, total_count
240
+
241
+ def get_stats(
242
+ self,
243
+ organization_id: int,
244
+ since: Optional[datetime.datetime] = None,
245
+ ) -> DeliveryStatsResponse:
246
+ """
247
+ Computes delivery metrics for an organization.
248
+ """
249
+ with self._session_scope() as session:
250
+ query = session.query(DeliveryAuditLog).filter(
251
+ DeliveryAuditLog.organization_id == organization_id
252
+ )
253
+ if since:
254
+ if since.tzinfo is not None:
255
+ since_utc = since.astimezone(datetime.timezone.utc).replace(tzinfo=None)
256
+ else:
257
+ since_utc = since
258
+ query = query.filter(DeliveryAuditLog.created_at >= since_utc)
259
+
260
+ total = query.count()
261
+ success_count = query.filter(DeliveryAuditLog.status == "SUCCESS").count()
262
+ failure_count = total - success_count
263
+
264
+ avg_dur = (
265
+ session.query(func.avg(DeliveryAuditLog.duration_ms))
266
+ .filter(DeliveryAuditLog.organization_id == organization_id)
267
+ .scalar()
268
+ or 0.0
269
+ )
270
+
271
+ return DeliveryStatsResponse(
272
+ organization_id=organization_id,
273
+ total_deliveries=total,
274
+ success_count=success_count,
275
+ failure_count=failure_count,
276
+ average_duration_ms=float(avg_dur),
277
+ )