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.
- app.py +3014 -0
- ast_scanner.py +36187 -0
- banner.py +146 -0
- ci_reporter.py +570 -0
- cli.py +2347 -0
- config_loader.py +307 -0
- cross_file_engine.py +1781 -0
- delivery_models.py +145 -0
- delivery_repository.py +78 -0
- diff_scan.py +127 -0
- durable_delivery_sink.py +103 -0
- event_bus.py +155 -0
- event_publisher.py +345 -0
- event_taxonomy.py +313 -0
- function_summarizer.py +354 -0
- html_auditor.py +274 -0
- iac_auditor.py +400 -0
- in_app_adapter.py +115 -0
- js_scanner.py +895 -0
- manifest_parser.py +960 -0
- master_rules_bank.py +389 -0
- notification_models.py +346 -0
- notification_policy.py +309 -0
- notification_repository.py +118 -0
- notification_routes.py +394 -0
- notification_service.py +199 -0
- osv_client.py +437 -0
- remediation/__init__.py +39 -0
- remediation/base.py +102 -0
- remediation/contracts.py +196 -0
- remediation/cwe1188_binding.py +78 -0
- remediation/cwe1336_jinja.py +91 -0
- remediation/cwe22_path_traversal.py +348 -0
- remediation/cwe295_ssl.py +87 -0
- remediation/cwe327_weak_hash.py +78 -0
- remediation/cwe377_tempfile.py +77 -0
- remediation/cwe489_debug.py +80 -0
- remediation/cwe502_yaml.py +89 -0
- remediation/cwe614_cookie.py +91 -0
- remediation/cwe78_cmdi.py +415 -0
- remediation/cwe798_credentials.py +153 -0
- remediation/cwe89_sqli.py +425 -0
- remediation/cwe916_password_hash.py +131 -0
- remediation/cwe95_eval.py +77 -0
- remediation/dispatcher.py +114 -0
- remediation/orchestrator.py +541 -0
- remediation/patch_engine.py +213 -0
- remediation/verification.py +253 -0
- rule_engine.py +1535 -0
- sarif_adapter.py +719 -0
- sarif_exporter.py +88 -0
- sca_reachability/__init__.py +28 -0
- sca_reachability/ast_analyzer.py +366 -0
- sca_reachability/call_graph.py +203 -0
- sca_reachability/contracts.py +365 -0
- sca_reachability/dist_import_map.py +46 -0
- sca_reachability/engine.py +603 -0
- sca_reachability/resolver.py +169 -0
- scanners/__init__.py +70 -0
- scanners/container_scanner.py +323 -0
- scanners/cve_index.py +521 -0
- scanners/iac_scanner.py +328 -0
- scanners/sbom.py +183 -0
- scanners/sca_scanner.py +667 -0
- scanners/secret_scanner.py +345 -0
- scanners/yaml_lite.py +217 -0
- secret_filters.py +435 -0
- secret_scanner.py +943 -0
- sqlite_delivery_repository.py +277 -0
- sqlite_notification_repository.py +441 -0
- ssrf_guard.py +276 -0
- staged_scanner.py +492 -0
- suppression_resolver.py +282 -0
- symbol_indexer.py +424 -0
- tcs/__init__.py +1 -0
- tcs/analysis/__init__.py +1 -0
- tcs/analysis/def_use.py +408 -0
- tcs/analysis/function_contracts.py +290 -0
- tcs/parallel_analyzer.py +276 -0
- tcs/parallel_scanner.py +630 -0
- tcs/treesitter_packer.py +1446 -0
- tcs_cli.py +2086 -0
- tcs_config.py +218 -0
- tcs_gui.py +2123 -0
- timecs-2.0.0.dist-info/METADATA +142 -0
- timecs-2.0.0.dist-info/RECORD +94 -0
- timecs-2.0.0.dist-info/WHEEL +5 -0
- timecs-2.0.0.dist-info/entry_points.txt +4 -0
- timecs-2.0.0.dist-info/licenses/LICENSE +201 -0
- timecs-2.0.0.dist-info/top_level.txt +49 -0
- version_matcher.py +934 -0
- webhook_adapter.py +495 -0
- webhook_client.py +483 -0
- webhook_formatters.py +245 -0
iac_auditor.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""Infrastructure-as-Code security auditor for TimeCodeSecurity.
|
|
2
|
+
|
|
3
|
+
Zero-dependency, deterministic analysis of two IaC artefact families:
|
|
4
|
+
|
|
5
|
+
* Dockerfiles -- CWE-250 / CWE-269 when a container's run instruction executes
|
|
6
|
+
without a preceding non-root ``USER`` instruction.
|
|
7
|
+
* GitHub Actions workflows -- one CWE-1357 finding per remote action step that is
|
|
8
|
+
referenced by a mutable tag or branch instead of an immutable commit SHA, carrying
|
|
9
|
+
CWE-353 in its metadata because the unpinned reference *is* the missing integrity
|
|
10
|
+
check and the two ids describe the same line of the same file.
|
|
11
|
+
|
|
12
|
+
Findings are derived from parsed instruction nodes and structured ``uses:``
|
|
13
|
+
references. There is no whole-file pattern matching and no path allow-listing.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from ast_scanner import (
|
|
23
|
+
GITHUB_OFFICIAL_ACTIONS,
|
|
24
|
+
DOCKER_OFFICIAL_ACTIONS,
|
|
25
|
+
TrustedPublisherPolicy,
|
|
26
|
+
)
|
|
27
|
+
except ImportError:
|
|
28
|
+
GITHUB_OFFICIAL_ACTIONS = ( # type: ignore[misc]
|
|
29
|
+
"actions/checkout",
|
|
30
|
+
"actions/setup-python",
|
|
31
|
+
"actions/setup-node",
|
|
32
|
+
"actions/setup-go",
|
|
33
|
+
"actions/setup-java",
|
|
34
|
+
"actions/upload-artifact",
|
|
35
|
+
"actions/download-artifact",
|
|
36
|
+
"actions/cache",
|
|
37
|
+
"actions/github-script",
|
|
38
|
+
"actions/stale",
|
|
39
|
+
"actions/labeler",
|
|
40
|
+
)
|
|
41
|
+
DOCKER_OFFICIAL_ACTIONS = ( # type: ignore[misc]
|
|
42
|
+
"docker/setup-buildx-action",
|
|
43
|
+
"docker/login-action",
|
|
44
|
+
"docker/build-push-action",
|
|
45
|
+
"docker/metadata-action",
|
|
46
|
+
)
|
|
47
|
+
class TrustedPublisherPolicy: # type: ignore[no-redef]
|
|
48
|
+
POLICY_VERSION: str = "2.0.0"
|
|
49
|
+
GITHUB_OFFICIAL = GITHUB_OFFICIAL_ACTIONS
|
|
50
|
+
DOCKER_OFFICIAL = DOCKER_OFFICIAL_ACTIONS
|
|
51
|
+
TRUSTED_PUBLISHERS = frozenset(GITHUB_OFFICIAL_ACTIONS + DOCKER_OFFICIAL_ACTIONS)
|
|
52
|
+
_TRUSTED_LOWER = frozenset(a.lower() for a in GITHUB_OFFICIAL_ACTIONS + DOCKER_OFFICIAL_ACTIONS)
|
|
53
|
+
COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
|
54
|
+
SEMVER_TAG_RE = re.compile(r"^v?\d+(?:\.\d+)*(?:-[a-zA-Z0-9.]+)?$")
|
|
55
|
+
MUTABLE_BRANCHES = frozenset({"main", "master", "dev", "develop", "trunk", "latest", "nightly", "beta", "alpha"})
|
|
56
|
+
LOCAL_ACTION_PREFIXES: Tuple[str, ...] = ("./", "../", "/", ".github/", "docker://")
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def is_trusted_publisher(cls, action_name: str) -> bool:
|
|
60
|
+
norm = str(action_name).strip().rstrip("/").lower()
|
|
61
|
+
return norm in cls._TRUSTED_LOWER
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def is_local_action(cls, action_name: str) -> bool:
|
|
65
|
+
norm = str(action_name).strip().lower()
|
|
66
|
+
return norm.startswith(cls.LOCAL_ACTION_PREFIXES)
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def is_commit_sha(cls, reference: str) -> bool:
|
|
70
|
+
return bool(cls.COMMIT_SHA_RE.match(str(reference).strip()))
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def is_semver_tag(cls, reference: str) -> bool:
|
|
74
|
+
return bool(cls.SEMVER_TAG_RE.match(str(reference).strip()))
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def is_mutable_branch(cls, reference: str) -> bool:
|
|
78
|
+
return str(reference).strip().lower() in cls.MUTABLE_BRANCHES
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def evaluate(cls, action_name: str, reference: str) -> Tuple[str, Optional[str], Optional[str]]:
|
|
82
|
+
ref = str(reference).strip()
|
|
83
|
+
act = str(action_name).strip()
|
|
84
|
+
act_lower = act.rstrip("/").lower()
|
|
85
|
+
if cls.is_commit_sha(ref):
|
|
86
|
+
return ("SEALED_IMMUTABLE_PIN", None, None)
|
|
87
|
+
if cls.is_local_action(act_lower):
|
|
88
|
+
return ("REPOSITORY_INTERNAL_ACTION", None, None)
|
|
89
|
+
is_trusted = act_lower in cls._TRUSTED_LOWER
|
|
90
|
+
is_semver = cls.is_semver_tag(ref)
|
|
91
|
+
is_branch = cls.is_mutable_branch(ref)
|
|
92
|
+
if is_trusted:
|
|
93
|
+
if is_semver:
|
|
94
|
+
return ("TRUSTED_PUBLISHER_MUTABLE_REF", "LOW", "TRUSTED_PUBLISHER_MUTABLE_REF")
|
|
95
|
+
return ("TRUSTED_PUBLISHER_MUTABLE_BRANCH", "MEDIUM", "TRUSTED_PUBLISHER_MUTABLE_BRANCH")
|
|
96
|
+
severity = "HIGH" if (is_branch or not is_semver) else "MEDIUM"
|
|
97
|
+
return ("UNTRUSTED_THIRD_PARTY_MUTABLE_REF", severity, "UNTRUSTED_THIRD_PARTY_MUTABLE_REF")
|
|
98
|
+
|
|
99
|
+
# ── Dockerfile ────────────────────────────────────────────────────────────
|
|
100
|
+
RUN_INSTRUCTIONS = frozenset({"CMD", "ENTRYPOINT"})
|
|
101
|
+
# Values that keep the process running with full privileges.
|
|
102
|
+
ROOT_USER_VALUES = frozenset({"root", "0", "root:root", "0:0"})
|
|
103
|
+
CONTINUATION = "\\"
|
|
104
|
+
|
|
105
|
+
PRODUCTION_DEPLOY_SEGMENTS = frozenset({
|
|
106
|
+
"deploy",
|
|
107
|
+
"deployment",
|
|
108
|
+
"deployments",
|
|
109
|
+
"production",
|
|
110
|
+
"prod",
|
|
111
|
+
"k8s",
|
|
112
|
+
"kubernetes",
|
|
113
|
+
"helm",
|
|
114
|
+
"release",
|
|
115
|
+
"releases",
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
NON_PRODUCTION_DOCKER_SEGMENTS = frozenset({
|
|
119
|
+
"docker",
|
|
120
|
+
"examples",
|
|
121
|
+
"example",
|
|
122
|
+
"tests",
|
|
123
|
+
"test",
|
|
124
|
+
"testing",
|
|
125
|
+
"ci",
|
|
126
|
+
"scripts",
|
|
127
|
+
"fixtures",
|
|
128
|
+
"fixture",
|
|
129
|
+
"samples",
|
|
130
|
+
"sample",
|
|
131
|
+
"demos",
|
|
132
|
+
"demo",
|
|
133
|
+
"target_arena",
|
|
134
|
+
"scratch",
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
PRIVILEGED_INSTRUCTION_RE = re.compile(
|
|
138
|
+
r"(?:\b--privileged\b|\bsudo\b|\bsetfacl\b|\bchmod\s+(?:-[a-zA-Z]+\s+)?(?:[0-7]*777|a\+[rwxXst]+)\b)",
|
|
139
|
+
re.IGNORECASE,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _is_non_production_dockerfile(file_path: str) -> bool:
|
|
144
|
+
normalized = str(file_path).replace("\\", "/").lower()
|
|
145
|
+
parts = set(normalized.strip("/").split("/"))
|
|
146
|
+
if parts & PRODUCTION_DEPLOY_SEGMENTS:
|
|
147
|
+
return False
|
|
148
|
+
return bool(parts & NON_PRODUCTION_DOCKER_SEGMENTS)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _has_explicit_privileged_instructions(
|
|
152
|
+
source: str,
|
|
153
|
+
instructions: Optional[Sequence[Tuple[int, str, str]]] = None,
|
|
154
|
+
) -> bool:
|
|
155
|
+
if instructions is None:
|
|
156
|
+
instructions = _parse_dockerfile_instructions(source)
|
|
157
|
+
for _line, keyword, arguments in instructions:
|
|
158
|
+
if keyword == "USER":
|
|
159
|
+
val = arguments.split()[0].lower() if arguments.split() else ""
|
|
160
|
+
if val in ROOT_USER_VALUES:
|
|
161
|
+
return True
|
|
162
|
+
return bool(PRIVILEGED_INSTRUCTION_RE.search(source))
|
|
163
|
+
|
|
164
|
+
# ── GitHub Actions ────────────────────────────────────────────────────────
|
|
165
|
+
WORKFLOW_DIR_PARTS = frozenset({".github"})
|
|
166
|
+
WORKFLOW_SUBDIR = "workflows"
|
|
167
|
+
WORKFLOW_SUFFIXES: Tuple[str, ...] = (".yml", ".yaml")
|
|
168
|
+
USES_RE = re.compile(r"^\s*(?:-\s*)?uses:\s*(?P<value>[^\s#]+)\s*(?:#.*)?$")
|
|
169
|
+
# An immutable reference is a full 40-character commit SHA.
|
|
170
|
+
PINNED_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
|
171
|
+
LOCAL_ACTION_PREFIXES: Tuple[str, ...] = ("./", "../", "/", ".github/", "docker://")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def is_dockerfile_path(path: str) -> bool:
|
|
175
|
+
"""True for ``Dockerfile``, ``Dockerfile.<variant>`` and ``<name>.dockerfile``."""
|
|
176
|
+
name = str(path).replace("\\", "/").rsplit("/", 1)[-1].lower()
|
|
177
|
+
return name.startswith("dockerfile") or name.endswith(".dockerfile")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def is_workflow_path(path: str) -> bool:
|
|
181
|
+
"""True for YAML documents inside a ``.github/workflows`` directory."""
|
|
182
|
+
normalized = str(path).replace("\\", "/").lower()
|
|
183
|
+
if not normalized.endswith(WORKFLOW_SUFFIXES):
|
|
184
|
+
return False
|
|
185
|
+
parts = normalized.split("/")
|
|
186
|
+
for index, part in enumerate(parts[:-1]):
|
|
187
|
+
if part in WORKFLOW_DIR_PARTS and index + 1 < len(parts) - 1:
|
|
188
|
+
if parts[index + 1] == WORKFLOW_SUBDIR:
|
|
189
|
+
return True
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def is_iac_path(path: str) -> bool:
|
|
194
|
+
return is_dockerfile_path(path) or is_workflow_path(path)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ══════════════════════════════════════════════════════════════════════════
|
|
198
|
+
# Dockerfile analysis
|
|
199
|
+
# ══════════════════════════════════════════════════════════════════════════
|
|
200
|
+
def _parse_dockerfile_instructions(source: str) -> List[Tuple[int, str, str]]:
|
|
201
|
+
"""Return ``[(start_line, INSTRUCTION, arguments)]`` honouring line continuations."""
|
|
202
|
+
instructions: List[Tuple[int, str, str]] = []
|
|
203
|
+
logical: List[str] = []
|
|
204
|
+
start_line = 0
|
|
205
|
+
|
|
206
|
+
for lineno, raw in enumerate(source.splitlines(), start=1):
|
|
207
|
+
line = raw.strip()
|
|
208
|
+
if not logical:
|
|
209
|
+
if not line or line.startswith("#"):
|
|
210
|
+
continue
|
|
211
|
+
start_line = lineno
|
|
212
|
+
else:
|
|
213
|
+
if not line or line.startswith("#"):
|
|
214
|
+
# A comment or blank line inside a continuation ends the instruction.
|
|
215
|
+
instructions.append(_split_instruction(start_line, " ".join(logical)))
|
|
216
|
+
logical = []
|
|
217
|
+
continue
|
|
218
|
+
|
|
219
|
+
if line.endswith(CONTINUATION) and not line.endswith("\\\\"):
|
|
220
|
+
logical.append(line[:-1].strip())
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
logical.append(line)
|
|
224
|
+
instructions.append(_split_instruction(start_line, " ".join(logical)))
|
|
225
|
+
logical = []
|
|
226
|
+
|
|
227
|
+
if logical:
|
|
228
|
+
instructions.append(_split_instruction(start_line, " ".join(logical)))
|
|
229
|
+
return [(line, kw, args) for line, kw, args in instructions if kw]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _split_instruction(start_line: int, text: str) -> Tuple[int, str, str]:
|
|
233
|
+
keyword, _, arguments = text.partition(" ")
|
|
234
|
+
return start_line, keyword.strip().upper(), arguments.strip()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _declares_non_root_user(instructions: Sequence[Tuple[int, str, str]]) -> bool:
|
|
238
|
+
"""True when the effective USER instruction drops root privileges.
|
|
239
|
+
|
|
240
|
+
A variable reference (``USER ${APP_USER}``) cannot be resolved statically and is
|
|
241
|
+
treated as an intentional privilege drop rather than guessed at.
|
|
242
|
+
"""
|
|
243
|
+
effective: Optional[str] = None
|
|
244
|
+
for _line, keyword, arguments in instructions:
|
|
245
|
+
if keyword != "USER":
|
|
246
|
+
continue
|
|
247
|
+
value = arguments.split()[0].lower() if arguments.split() else ""
|
|
248
|
+
effective = value
|
|
249
|
+
if effective is None:
|
|
250
|
+
return False
|
|
251
|
+
if effective in ROOT_USER_VALUES:
|
|
252
|
+
return False
|
|
253
|
+
return True
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def audit_dockerfile(file_path: str, source: str, audit_all: bool = False) -> List[Dict[str, Any]]:
|
|
257
|
+
"""Emit CWE-250 / CWE-269 findings for a Dockerfile that runs as root."""
|
|
258
|
+
instructions = _parse_dockerfile_instructions(source)
|
|
259
|
+
if not instructions:
|
|
260
|
+
return []
|
|
261
|
+
if _declares_non_root_user(instructions):
|
|
262
|
+
return []
|
|
263
|
+
|
|
264
|
+
# If the file path indicates testing, examples, or local CI infrastructure,
|
|
265
|
+
# suppress generic missing non-root USER warnings unless audit_all is set
|
|
266
|
+
# or the Dockerfile has explicit privileged execution vulnerabilities.
|
|
267
|
+
if (
|
|
268
|
+
_is_non_production_dockerfile(file_path)
|
|
269
|
+
and not audit_all
|
|
270
|
+
and not _has_explicit_privileged_instructions(source, instructions)
|
|
271
|
+
):
|
|
272
|
+
return []
|
|
273
|
+
|
|
274
|
+
cmd_lines = [line for line, kw, _ in instructions if kw == "CMD"]
|
|
275
|
+
entrypoint_lines = [line for line, kw, _ in instructions if kw == "ENTRYPOINT"]
|
|
276
|
+
if not cmd_lines and not entrypoint_lines:
|
|
277
|
+
# Nothing is executed by the image itself; no privilege exposure to report.
|
|
278
|
+
return []
|
|
279
|
+
|
|
280
|
+
total_lines = max(1, len(source.splitlines()))
|
|
281
|
+
findings: List[Dict[str, Any]] = []
|
|
282
|
+
|
|
283
|
+
# CWE-250: the container's start command runs with root privileges.
|
|
284
|
+
run_line = cmd_lines[-1] if cmd_lines else entrypoint_lines[-1]
|
|
285
|
+
findings.append({
|
|
286
|
+
"file": file_path,
|
|
287
|
+
"line": max(1, min(run_line, total_lines)),
|
|
288
|
+
"cwe": "CWE-250",
|
|
289
|
+
"severity": "HIGH",
|
|
290
|
+
"category": "EXECUTION_WITH_UNNECESSARY_PRIVILEGES",
|
|
291
|
+
"message": (
|
|
292
|
+
"CWE-250: Container service runs as root; missing non-root USER instruction."
|
|
293
|
+
" Add USER <non-root> before the run instruction so a container escape does"
|
|
294
|
+
" not inherit UID 0"
|
|
295
|
+
),
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
# CWE-269: an ENTRYPOINT executes before any privilege drop can take effect.
|
|
299
|
+
if entrypoint_lines:
|
|
300
|
+
findings.append({
|
|
301
|
+
"file": file_path,
|
|
302
|
+
"line": max(1, min(entrypoint_lines[-1], total_lines)),
|
|
303
|
+
"cwe": "CWE-269",
|
|
304
|
+
"severity": "HIGH",
|
|
305
|
+
"category": "IMPROPER_PRIVILEGE_MANAGEMENT",
|
|
306
|
+
"message": (
|
|
307
|
+
"CWE-269: Container service runs as root; missing non-root USER instruction."
|
|
308
|
+
" The ENTRYPOINT executes with UID 0 because no USER instruction precedes it"
|
|
309
|
+
),
|
|
310
|
+
})
|
|
311
|
+
|
|
312
|
+
return findings
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
# ══════════════════════════════════════════════════════════════════════════
|
|
316
|
+
# GitHub Actions workflow analysis
|
|
317
|
+
# ══════════════════════════════════════════════════════════════════════════
|
|
318
|
+
def _is_remote_action(action_name: str) -> bool:
|
|
319
|
+
return not action_name.startswith(LOCAL_ACTION_PREFIXES)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def audit_workflow(file_path: str, source: str, audit_all: bool = False) -> List[Dict[str, Any]]:
|
|
323
|
+
"""Emit one CWE-1357 finding per action step pinned to a mutable reference."""
|
|
324
|
+
findings: List[Dict[str, Any]] = []
|
|
325
|
+
|
|
326
|
+
for lineno, raw in enumerate(source.splitlines(), start=1):
|
|
327
|
+
match = USES_RE.match(raw)
|
|
328
|
+
if not match:
|
|
329
|
+
continue
|
|
330
|
+
value = match.group("value").strip().strip("'\"")
|
|
331
|
+
action_name, separator, reference = value.rpartition("@")
|
|
332
|
+
if not separator or not action_name or not reference:
|
|
333
|
+
continue
|
|
334
|
+
if not _is_remote_action(action_name):
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
classification, severity, category = TrustedPublisherPolicy.evaluate(action_name, reference)
|
|
338
|
+
if classification in ("SEALED_IMMUTABLE_PIN", "REPOSITORY_INTERNAL_ACTION") or severity is None:
|
|
339
|
+
continue
|
|
340
|
+
|
|
341
|
+
if classification == "TRUSTED_PUBLISHER_MUTABLE_REF":
|
|
342
|
+
if not audit_all:
|
|
343
|
+
continue
|
|
344
|
+
message = (
|
|
345
|
+
f"GitHub Action step is pinned to a mutable semantic version tag from an official"
|
|
346
|
+
f" trusted publisher: {action_name}@{reference}. Pin to the full 40-character"
|
|
347
|
+
f" commit SHA for complete build immutability"
|
|
348
|
+
)
|
|
349
|
+
elif classification == "TRUSTED_PUBLISHER_MUTABLE_BRANCH":
|
|
350
|
+
message = (
|
|
351
|
+
f"GitHub Action step from an official trusted publisher is pinned to a mutable branch"
|
|
352
|
+
f" instead of an immutable commit SHA: {action_name}@{reference}. Pin to the full"
|
|
353
|
+
f" 40-character commit SHA to prevent upstream branch updates from silently altering build steps"
|
|
354
|
+
)
|
|
355
|
+
else:
|
|
356
|
+
ref_type = "mutable branch" if severity == "HIGH" else "mutable tag"
|
|
357
|
+
message = (
|
|
358
|
+
f"GitHub Action step uses an untrusted third-party component pinned to a"
|
|
359
|
+
f" {ref_type} instead of an immutable commit SHA: {action_name}@{reference}."
|
|
360
|
+
f" Pin to the full 40-character commit SHA so an upstream tag move or compromise"
|
|
361
|
+
f" cannot silently change the code that runs"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
# One record per vulnerable line. CWE-1357 is the primary id (the pipeline runs code
|
|
365
|
+
# it does not control). CWE-353 is the same defect seen from the integrity side, so it
|
|
366
|
+
# rides inside the alert text and in `related_cwes` instead of a second row that doubles
|
|
367
|
+
# the finding count for one `uses:` line. The id stays in the message because cli.py
|
|
368
|
+
# builds SARIF tags from the finding's own `cwe` only, and SARIF result text is exactly
|
|
369
|
+
# this string -- a metadata key alone would make CWE-353 unfindable in SARIF output.
|
|
370
|
+
findings.append({
|
|
371
|
+
"file": file_path,
|
|
372
|
+
"line": lineno,
|
|
373
|
+
"cwe": "CWE-1357",
|
|
374
|
+
"severity": severity,
|
|
375
|
+
"category": category,
|
|
376
|
+
"message": (
|
|
377
|
+
f"CWE-1357: {message}"
|
|
378
|
+
" (missing immutable commit reference — also CWE-353)"
|
|
379
|
+
),
|
|
380
|
+
"related_cwes": ["CWE-353"],
|
|
381
|
+
})
|
|
382
|
+
|
|
383
|
+
return findings
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def audit_iac_file(file_path: str, source: str, audit_all: bool = False) -> List[Dict[str, Any]]:
|
|
387
|
+
"""Dispatch a single IaC document to the appropriate auditor."""
|
|
388
|
+
if is_dockerfile_path(file_path):
|
|
389
|
+
return audit_dockerfile(file_path, source, audit_all=audit_all)
|
|
390
|
+
if is_workflow_path(file_path):
|
|
391
|
+
return audit_workflow(file_path, source, audit_all=audit_all)
|
|
392
|
+
return []
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def audit_iac_files(files: Dict[str, str], audit_all: bool = False) -> List[Dict[str, Any]]:
|
|
396
|
+
"""Audit a mapping of ``{file_path: source}`` IaC documents deterministically."""
|
|
397
|
+
findings: List[Dict[str, Any]] = []
|
|
398
|
+
for file_path in sorted(files):
|
|
399
|
+
findings.extend(audit_iac_file(file_path, files[file_path], audit_all=audit_all))
|
|
400
|
+
return sorted(findings, key=lambda item: (item["file"], item["line"], item["cwe"]))
|
in_app_adapter.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity In-App Notification Delivery Adapter.
|
|
3
|
+
|
|
4
|
+
Consumes NotificationIntent objects produced by NotificationPolicy,
|
|
5
|
+
translates them to NotificationCreate DTOs, and persists them via
|
|
6
|
+
NotificationRepository.
|
|
7
|
+
|
|
8
|
+
Invariants:
|
|
9
|
+
- Consumes already-created NotificationIntent objects only.
|
|
10
|
+
- Adapters MUST NOT re-evaluate notification policy.
|
|
11
|
+
- Every NotificationIntent is attempted independently and sequentially.
|
|
12
|
+
- No fake transaction-wide rollback: successful intents remain committed.
|
|
13
|
+
- If any intent fails, an AggregatePersistenceError is raised after all intents
|
|
14
|
+
have been attempted, propagating failure to the EventBus boundary without
|
|
15
|
+
affecting scanner execution.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import logging
|
|
21
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
|
22
|
+
|
|
23
|
+
from notification_models import Notification, NotificationCreate, RecipientScope
|
|
24
|
+
from notification_policy import NotificationIntent
|
|
25
|
+
from notification_repository import NotificationRepository
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger("tcs.in_app_adapter")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AggregatePersistenceError(Exception):
|
|
31
|
+
"""
|
|
32
|
+
Raised when one or more NotificationIntent objects fail persistence.
|
|
33
|
+
Contains the full list of failed intents and their associated exceptions.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
message: str,
|
|
39
|
+
failures: List[Tuple[NotificationIntent, Exception]],
|
|
40
|
+
persisted: List[Notification]
|
|
41
|
+
) -> None:
|
|
42
|
+
super().__init__(message)
|
|
43
|
+
self.failures = failures
|
|
44
|
+
self.persisted = persisted
|
|
45
|
+
|
|
46
|
+
def __repr__(self) -> str:
|
|
47
|
+
return f"AggregatePersistenceError({len(self.failures)} failure(s), {len(self.persisted)} persisted)"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class InAppNotificationAdapter:
|
|
51
|
+
"""
|
|
52
|
+
Synchronous adapter that persists In-App NotificationIntents via NotificationRepository.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, repository: NotificationRepository) -> None:
|
|
56
|
+
if not isinstance(repository, NotificationRepository):
|
|
57
|
+
raise TypeError(f"Expected NotificationRepository, got {type(repository).__name__}")
|
|
58
|
+
self._repository = repository
|
|
59
|
+
|
|
60
|
+
def handle_intent(self, intent: NotificationIntent) -> Notification:
|
|
61
|
+
"""
|
|
62
|
+
Persists a single NotificationIntent.
|
|
63
|
+
Raises exception immediately if this individual intent fails.
|
|
64
|
+
"""
|
|
65
|
+
if not isinstance(intent, NotificationIntent):
|
|
66
|
+
raise TypeError(f"Expected NotificationIntent, got {type(intent).__name__}")
|
|
67
|
+
|
|
68
|
+
dto = NotificationCreate(
|
|
69
|
+
organization_id=intent.organization_id,
|
|
70
|
+
recipient_scope=intent.recipient_scope,
|
|
71
|
+
user_id=intent.user_id,
|
|
72
|
+
event_id=intent.event_id,
|
|
73
|
+
scan_id=intent.scan_id,
|
|
74
|
+
dedupe_key=intent.dedupe_key,
|
|
75
|
+
type=intent.notification_type,
|
|
76
|
+
severity=intent.severity,
|
|
77
|
+
title=intent.title,
|
|
78
|
+
message=intent.message,
|
|
79
|
+
link=intent.link,
|
|
80
|
+
)
|
|
81
|
+
return self._repository.create(dto)
|
|
82
|
+
|
|
83
|
+
def handle_intents(self, intents: Sequence[NotificationIntent]) -> List[Notification]:
|
|
84
|
+
"""
|
|
85
|
+
Processes a sequence of NotificationIntents independently.
|
|
86
|
+
All intents are attempted. Successful intents remain persisted.
|
|
87
|
+
If any intent fails, an AggregatePersistenceError is raised after all
|
|
88
|
+
intents have been attempted.
|
|
89
|
+
"""
|
|
90
|
+
persisted: List[Notification] = []
|
|
91
|
+
failures: List[Tuple[NotificationIntent, Exception]] = []
|
|
92
|
+
|
|
93
|
+
for intent in intents:
|
|
94
|
+
if intent.channel != "IN_APP":
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
notif = self.handle_intent(intent)
|
|
98
|
+
persisted.append(notif)
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
logger.error(
|
|
101
|
+
"Failed to persist in-app notification intent %s for org %s: %s",
|
|
102
|
+
intent.intent_id,
|
|
103
|
+
intent.organization_id,
|
|
104
|
+
exc,
|
|
105
|
+
)
|
|
106
|
+
failures.append((intent, exc))
|
|
107
|
+
|
|
108
|
+
if failures:
|
|
109
|
+
raise AggregatePersistenceError(
|
|
110
|
+
f"In-app persistence failed for {len(failures)} of {len(intents)} intent(s).",
|
|
111
|
+
failures=failures,
|
|
112
|
+
persisted=persisted,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
return persisted
|