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,118 @@
1
+ """
2
+ TimeCodeSecurity Notification Repository Interface.
3
+
4
+ Defines the abstract multi-tenant contract for notification persistence,
5
+ querying, deduplication, and read-state management.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from abc import ABC, abstractmethod
11
+ from datetime import datetime
12
+ from typing import List, Optional, Union
13
+
14
+ from notification_models import Notification, NotificationCreate, RecipientScope
15
+
16
+
17
+ class NotificationRepository(ABC):
18
+ """
19
+ Abstract interface for notification storage.
20
+ Enforces tenant isolation across all query and mutation methods.
21
+ """
22
+
23
+ @abstractmethod
24
+ def create(self, payload: Union[NotificationCreate, dict]) -> Notification:
25
+ """
26
+ Idempotently creates a notification record.
27
+ If a notification with identical dedupe identity
28
+ (organization_id, scope_target, dedupe_key, type) already exists,
29
+ returns the existing record without duplicate row insertion.
30
+ """
31
+ pass
32
+
33
+ @abstractmethod
34
+ def get_by_id(
35
+ self,
36
+ notification_id: int,
37
+ organization_id: int,
38
+ user_id: Optional[int] = None,
39
+ ) -> Optional[Notification]:
40
+ """
41
+ Retrieves a notification by ID enforcing strict tenant and user boundary.
42
+ - Requires organization_id.
43
+ - If user_id is provided, returns the notification if it is USER-scoped
44
+ for that user OR if it is ORGANIZATION-scoped.
45
+ - If user_id is None, returns the notification only if it is ORGANIZATION-scoped.
46
+ - Returns None if not found or unauthorized.
47
+ """
48
+ pass
49
+
50
+ @abstractmethod
51
+ def list_notifications(
52
+ self,
53
+ organization_id: int,
54
+ user_id: Optional[int] = None,
55
+ recipient_scope: Optional[Union[RecipientScope, str]] = None,
56
+ unread_only: bool = False,
57
+ limit: int = 50,
58
+ offset: int = 0,
59
+ ) -> List[Notification]:
60
+ """
61
+ Lists notifications ordered chronologically by created_at DESC.
62
+ - Requires organization_id.
63
+ - Respects user/organization boundaries and unread filtering.
64
+ """
65
+ pass
66
+
67
+ @abstractmethod
68
+ def count_unread(
69
+ self,
70
+ organization_id: int,
71
+ user_id: Optional[int] = None,
72
+ recipient_scope: Optional[Union[RecipientScope, str]] = None,
73
+ ) -> int:
74
+ """
75
+ Counts unread notifications matching the requested tenant and recipient scope.
76
+ """
77
+ pass
78
+
79
+ @abstractmethod
80
+ def mark_read(
81
+ self,
82
+ notification_id: int,
83
+ organization_id: int,
84
+ user_id: Optional[int] = None,
85
+ read_at: Optional[datetime] = None,
86
+ ) -> bool:
87
+ """
88
+ Marks a single notification as read, enforcing:
89
+ is_read = True and read_at is set atomically.
90
+ Returns True if updated (or already read), False if not found/unauthorized.
91
+ """
92
+ pass
93
+
94
+ @abstractmethod
95
+ def mark_all_read(
96
+ self,
97
+ organization_id: int,
98
+ user_id: Optional[int] = None,
99
+ read_at: Optional[datetime] = None,
100
+ ) -> int:
101
+ """
102
+ Marks all unread notifications matching the tenant/user scope as read in a single atomic transaction.
103
+ Returns the count of updated records.
104
+ """
105
+ pass
106
+
107
+ @abstractmethod
108
+ def exists_by_dedupe_key(
109
+ self,
110
+ dedupe_key: str,
111
+ organization_id: int,
112
+ user_id: Optional[int] = None,
113
+ type: Optional[str] = None,
114
+ ) -> bool:
115
+ """
116
+ Checks whether a notification matching the semantic dedupe identity already exists.
117
+ """
118
+ pass
notification_routes.py ADDED
@@ -0,0 +1,394 @@
1
+ """
2
+ TimeCodeSecurity Notification & Delivery REST API Routes.
3
+
4
+ Exposes authenticated multi-tenant endpoints for:
5
+ - Listing in-app notifications
6
+ - Querying unread counts
7
+ - Marking notifications as read/unread
8
+ - Marking all notifications as read
9
+ - Querying delivery audit logs (Admin only)
10
+
11
+ Invariants:
12
+ - All routes require authentication via JWT Bearer token or API key.
13
+ - Strict multi-tenant isolation: queries are bounded by user's organization_id.
14
+ - Cross-tenant access returns HTTP 404 to prevent resource enumeration.
15
+ - Delivery audit inspection is strictly restricted to users with org_role == 'admin' (HTTP 403 otherwise).
16
+ - Deterministic pagination: ORDER BY created_at DESC, id DESC.
17
+ - UTC ISO-8601 serialized timestamps.
18
+ - Zero raw secrets, payload bodies, or target IPs exposed in public responses.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import datetime
24
+ import logging
25
+ from typing import Any, Dict, List, Optional
26
+
27
+ from fastapi import APIRouter, Depends, Header, HTTPException, Query
28
+ from pydantic import BaseModel, Field
29
+ from sqlalchemy.orm import Session
30
+
31
+ from delivery_models import DeliveryAuditLogRead
32
+ from sqlite_delivery_repository import SqliteDeliveryRepository
33
+ from sqlite_notification_repository import SqliteNotificationRepository
34
+
35
+ logger = logging.getLogger("tcs.notification_routes")
36
+
37
+ router = APIRouter(prefix="/api/notifications", tags=["Notifications"])
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # DTOs
42
+ # ---------------------------------------------------------------------------
43
+
44
+ class NotificationReadResponse(BaseModel):
45
+ id: int
46
+ organization_id: int
47
+ user_id: Optional[int] = None
48
+ recipient_scope: str
49
+ event_id: str
50
+ scan_id: Optional[str] = None
51
+ channel: str
52
+ severity: str
53
+ title: str
54
+ message: str
55
+ link: Optional[str] = None
56
+ is_read: bool
57
+ read_at: Optional[str] = None
58
+ created_at: str
59
+
60
+ class Config:
61
+ from_attributes = True
62
+ orm_mode = True
63
+
64
+
65
+ class NotificationListResponse(BaseModel):
66
+ items: List[NotificationReadResponse]
67
+ total: int
68
+ limit: int
69
+ offset: int
70
+
71
+
72
+ class UnreadCountResponse(BaseModel):
73
+ unread_count: int
74
+
75
+
76
+ class MarkReadRequest(BaseModel):
77
+ is_read: bool = True
78
+
79
+
80
+ class MarkAllReadResponse(BaseModel):
81
+ marked_count: int
82
+ updated_at: str
83
+
84
+
85
+ class DeliveryAuditListResponse(BaseModel):
86
+ items: List[DeliveryAuditLogRead]
87
+ total: int
88
+ limit: int
89
+ offset: int
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Dependencies & Helpers
94
+ # ---------------------------------------------------------------------------
95
+
96
+ def get_db_session():
97
+ """Provides a transactional database session from application infrastructure."""
98
+ from app import SessionLocal
99
+ db = SessionLocal()
100
+ try:
101
+ yield db
102
+ finally:
103
+ db.close()
104
+
105
+
106
+ async def get_authenticated_user(
107
+ authorization: Optional[str] = Header(None),
108
+ db: Session = Depends(get_db_session),
109
+ ) -> Any:
110
+ """
111
+ Authenticates requests via Bearer JWT or TCS API key.
112
+ Enforces authentication failure semantics (HTTP 401).
113
+ """
114
+ if not authorization or not authorization.startswith("Bearer "):
115
+ raise HTTPException(status_code=401, detail="Unauthorized")
116
+
117
+ token = authorization.split(" ")[1]
118
+ from app import User, SECRET_KEY
119
+ import jwt
120
+
121
+ if token.startswith("tcs_"):
122
+ user = db.query(User).filter(User.api_key == token).first()
123
+ if not user:
124
+ raise HTTPException(status_code=401, detail="Invalid API Key")
125
+ return user
126
+
127
+ try:
128
+ payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
129
+ email = payload.get("sub")
130
+ except Exception:
131
+ raise HTTPException(status_code=401, detail="Invalid token")
132
+
133
+ if not email:
134
+ raise HTTPException(status_code=401, detail="Invalid token subject")
135
+
136
+ user = db.query(User).filter(User.email == email).first()
137
+ if not user:
138
+ raise HTTPException(status_code=401, detail="User not found")
139
+ return user
140
+
141
+
142
+ def get_effective_org_id(user: Any) -> int:
143
+ """Resolves the user's organization ID, defaulting to user ID for individual accounts."""
144
+ org_id = getattr(user, "org_id", None)
145
+ if org_id is not None and isinstance(org_id, int) and org_id > 0:
146
+ return org_id
147
+ # Fallback to user ID if no explicit organization is configured
148
+ return int(user.id)
149
+
150
+
151
+ def serialize_notification(n: Any) -> NotificationReadResponse:
152
+ """Serializes a Notification SQLAlchemy entity into safe DTO."""
153
+ created_at_str = (
154
+ n.created_at.replace(tzinfo=datetime.timezone.utc).isoformat()
155
+ if n.created_at and n.created_at.tzinfo is None
156
+ else n.created_at.isoformat() if n.created_at else None
157
+ )
158
+ read_at_str = (
159
+ n.read_at.replace(tzinfo=datetime.timezone.utc).isoformat()
160
+ if n.read_at and n.read_at.tzinfo is None
161
+ else n.read_at.isoformat() if n.read_at else None
162
+ )
163
+ return NotificationReadResponse(
164
+ id=n.id,
165
+ organization_id=n.organization_id,
166
+ user_id=n.user_id,
167
+ recipient_scope=n.recipient_scope,
168
+ event_id=n.event_id,
169
+ scan_id=n.scan_id,
170
+ channel=getattr(n, "channel", "IN_APP"),
171
+ severity=getattr(n, "severity", "INFO"),
172
+ title=n.title,
173
+ message=n.message,
174
+ link=n.link,
175
+ is_read=bool(n.is_read),
176
+ read_at=read_at_str,
177
+ created_at=created_at_str,
178
+ )
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # Endpoints
183
+ # ---------------------------------------------------------------------------
184
+
185
+ @router.get("", response_model=NotificationListResponse)
186
+ def list_notifications(
187
+ limit: int = Query(50, ge=1, le=100),
188
+ offset: int = Query(0, ge=0),
189
+ unread_only: bool = Query(False),
190
+ channel: Optional[str] = Query(None),
191
+ severity: Optional[str] = Query(None),
192
+ user: Any = Depends(get_authenticated_user),
193
+ db: Session = Depends(get_db_session),
194
+ ):
195
+ """
196
+ Lists in-app notifications for the authenticated user and organization.
197
+ Ordered deterministically by created_at DESC, id DESC.
198
+ """
199
+ try:
200
+ if not isinstance(limit, int):
201
+ limit = getattr(limit, "default", 50)
202
+ if not isinstance(offset, int):
203
+ offset = getattr(offset, "default", 0)
204
+ if not isinstance(channel, str):
205
+ channel = None
206
+ if not isinstance(severity, str):
207
+ severity = None
208
+
209
+ org_id = get_effective_org_id(user)
210
+ repo = SqliteNotificationRepository(session=db)
211
+ items = repo.list_notifications(
212
+ organization_id=org_id,
213
+ user_id=user.id,
214
+ unread_only=unread_only,
215
+ limit=limit,
216
+ offset=offset,
217
+ )
218
+
219
+ if channel:
220
+ items = [i for i in items if getattr(i, "channel", None) == channel]
221
+ if severity:
222
+ items = [i for i in items if getattr(i, "severity", None) == severity]
223
+
224
+ # Total count matching tenant and recipient scope
225
+ total = repo.count_unread(organization_id=org_id, user_id=user.id) if unread_only else len(items)
226
+
227
+ return NotificationListResponse(
228
+ items=[serialize_notification(i) for i in items],
229
+ total=total,
230
+ limit=limit,
231
+ offset=offset,
232
+ )
233
+ except HTTPException:
234
+ raise
235
+ except Exception as exc:
236
+ logger.error("Error listing notifications: %s", exc)
237
+ raise HTTPException(status_code=500, detail="Internal database operation failed")
238
+
239
+
240
+ @router.get("/unread-count", response_model=UnreadCountResponse)
241
+ def get_unread_count(
242
+ user: Any = Depends(get_authenticated_user),
243
+ db: Session = Depends(get_db_session),
244
+ ):
245
+ """Returns the total number of unread notifications visible to the authenticated user."""
246
+ try:
247
+ org_id = get_effective_org_id(user)
248
+ repo = SqliteNotificationRepository(session=db)
249
+ count = repo.count_unread(organization_id=org_id, user_id=user.id)
250
+ return UnreadCountResponse(unread_count=count)
251
+ except HTTPException:
252
+ raise
253
+ except Exception as exc:
254
+ logger.error("Error fetching unread count: %s", exc)
255
+ raise HTTPException(status_code=500, detail="Internal database operation failed")
256
+
257
+
258
+ @router.patch("/{id}/read", response_model=NotificationReadResponse)
259
+ def mark_notification_read(
260
+ id: int,
261
+ payload: MarkReadRequest = MarkReadRequest(),
262
+ user: Any = Depends(get_authenticated_user),
263
+ db: Session = Depends(get_db_session),
264
+ ):
265
+ """
266
+ Marks a single notification as read or unread.
267
+ Enforces strict tenant isolation; cross-tenant requests return HTTP 404.
268
+ """
269
+ try:
270
+ org_id = get_effective_org_id(user)
271
+ repo = SqliteNotificationRepository(session=db)
272
+ notif = repo.get_by_id(notification_id=id, organization_id=org_id, user_id=user.id)
273
+ if notif is None:
274
+ # Prevent ID enumeration across tenants: return 404
275
+ raise HTTPException(status_code=404, detail="Notification not found")
276
+
277
+ now_utc = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
278
+ if payload.is_read:
279
+ repo.mark_read(
280
+ notification_id=id,
281
+ organization_id=org_id,
282
+ user_id=user.id,
283
+ read_at=now_utc,
284
+ )
285
+ else:
286
+ notif.is_read = False
287
+ notif.read_at = None
288
+ db.commit()
289
+
290
+ db.refresh(notif)
291
+ return serialize_notification(notif)
292
+ except HTTPException:
293
+ raise
294
+ except Exception as exc:
295
+ logger.error("Error marking notification read status: %s", exc)
296
+ raise HTTPException(status_code=500, detail="Internal database operation failed")
297
+
298
+
299
+ @router.post("/mark-all-read", response_model=MarkAllReadResponse)
300
+ def mark_all_notifications_read(
301
+ user: Any = Depends(get_authenticated_user),
302
+ db: Session = Depends(get_db_session),
303
+ ):
304
+ """Marks all visible unread notifications in the tenant as read."""
305
+ try:
306
+ org_id = get_effective_org_id(user)
307
+ repo = SqliteNotificationRepository(session=db)
308
+ now_utc = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
309
+ marked_count = repo.mark_all_read(
310
+ organization_id=org_id,
311
+ user_id=user.id,
312
+ read_at=now_utc,
313
+ )
314
+ return MarkAllReadResponse(
315
+ marked_count=marked_count,
316
+ updated_at=now_utc.replace(tzinfo=datetime.timezone.utc).isoformat(),
317
+ )
318
+ except HTTPException:
319
+ raise
320
+ except Exception as exc:
321
+ logger.error("Error marking all notifications read: %s", exc)
322
+ raise HTTPException(status_code=500, detail="Internal database operation failed")
323
+
324
+
325
+ @router.get("/deliveries", response_model=DeliveryAuditListResponse)
326
+ def list_delivery_audits(
327
+ limit: int = Query(50, ge=1, le=100),
328
+ offset: int = Query(0, ge=0),
329
+ status: Optional[str] = Query(None),
330
+ user: Any = Depends(get_authenticated_user),
331
+ db: Session = Depends(get_db_session),
332
+ ):
333
+ """
334
+ Lists webhook delivery audit logs for the authenticated organization.
335
+ RESTRICTED: Only users with org_role == 'admin' may access this endpoint.
336
+ Non-admin users receive HTTP 403 Forbidden.
337
+ """
338
+ try:
339
+ org_role = getattr(user, "org_role", "member")
340
+ if org_role != "admin":
341
+ raise HTTPException(
342
+ status_code=403,
343
+ detail="Administrator privileges required to view delivery audit records",
344
+ )
345
+
346
+ if not isinstance(limit, int):
347
+ limit = getattr(limit, "default", 50)
348
+ if not isinstance(offset, int):
349
+ offset = getattr(offset, "default", 0)
350
+ if not isinstance(status, str):
351
+ status = None
352
+
353
+ org_id = get_effective_org_id(user)
354
+ repo = SqliteDeliveryRepository(session=db)
355
+ items, total = repo.list(
356
+ organization_id=org_id,
357
+ status=status,
358
+ limit=limit,
359
+ offset=offset,
360
+ )
361
+
362
+ read_items = [
363
+ DeliveryAuditLogRead(
364
+ id=i.id,
365
+ organization_id=i.organization_id,
366
+ event_id=i.event_id,
367
+ scan_id=i.scan_id,
368
+ idempotency_key=i.idempotency_key,
369
+ channel=i.channel,
370
+ status=i.status,
371
+ status_code=i.status_code,
372
+ attempts=i.attempts,
373
+ duration_ms=i.duration_ms,
374
+ error_message=i.error_message,
375
+ created_at=(
376
+ i.created_at.replace(tzinfo=datetime.timezone.utc).isoformat()
377
+ if i.created_at and i.created_at.tzinfo is None
378
+ else i.created_at.isoformat() if i.created_at else ""
379
+ ),
380
+ )
381
+ for i in items
382
+ ]
383
+
384
+ return DeliveryAuditListResponse(
385
+ items=read_items,
386
+ total=total,
387
+ limit=limit,
388
+ offset=offset,
389
+ )
390
+ except HTTPException:
391
+ raise
392
+ except Exception as exc:
393
+ logger.error("Error listing delivery audit records: %s", exc)
394
+ raise HTTPException(status_code=500, detail="Internal database operation failed")