Repository navigation
Expand file tree
/
Copy pathaction_runtime.py
More file actions
1871 lines (1673 loc) · 62 KB
/
Copy pathaction_runtime.py
File metadata and controls
1871 lines (1673 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Runtime helpers for the standalone DeployWhisper GitHub Action bundle."""
from __future__ import annotations
import argparse
from datetime import UTC, datetime
import hashlib
import json
import math
import os
from pathlib import Path
import re
import subprocess
import sys
from typing import Iterable
from urllib import error, parse, request
import uuid
COMMENT_MARKER = "<!-- deploywhisper:pr-comment -->"
SCAN_META_MARKER = "deploywhisper:scan-meta"
GITHUB_API_BASE_URL = "https://api.github.com"
MAX_PR_COMMENT_LENGTH = 2000
SCAN_META_KEY_LIMIT = 88
SCAN_META_LABEL_LIMIT = 32
SCAN_META_KEY_LENGTH = 16
SCAN_META_MARKER_LENGTH_LIMIT = 1600
DELTA_LINE_PREFIXES = (
"- Finding changes:",
"- New finding:",
"- Resolved finding:",
"- Persistent finding:",
)
SENSITIVE_FILE_MARKERS = {
".env",
".pem",
".key",
".tfstate",
"id_rsa",
"kubeconfig",
"credentials",
}
SUPPORTED_TOOL_TYPES = {
"terraform",
"kubernetes",
"ansible",
"jenkins",
"cloudformation",
}
class ActionRuntimeError(RuntimeError):
"""Raised when the GitHub Action cannot complete its operational work."""
def _shorten(text: str, limit: int) -> str:
normalized = " ".join(text.split())
if len(normalized) <= limit:
return normalized
return normalized[: max(limit - 1, 0)].rstrip() + "…"
def _shorten_preserve_tail(text: str, limit: int) -> str:
normalized = " ".join(text.split())
if len(normalized) <= limit:
return normalized
if limit <= 1:
return "…"[:limit]
separator = " … "
if limit <= len(separator) + 2:
return _shorten(normalized, limit)
head_length = max((limit - len(separator)) // 2, 1)
tail_length = max(limit - len(separator) - head_length, 1)
return (
normalized[:head_length].rstrip()
+ separator
+ normalized[-tail_length:].lstrip()
)
def _prioritize_delta_lines(text: str) -> str:
lines = text.splitlines()
delta_lines = [
line
for line in lines
if any(line.startswith(prefix) for prefix in DELTA_LINE_PREFIXES)
]
if not delta_lines:
return text
remaining = [line for line in lines if line not in delta_lines]
insert_index = min(3, len(remaining))
return "\n".join(remaining[:insert_index] + delta_lines + remaining[insert_index:])
def _compact_opening_with_delta_lines(text: str, limit: int) -> str | None:
lines = text.splitlines()
delta_lines = [
line
for line in lines
if any(line.startswith(prefix) for prefix in DELTA_LINE_PREFIXES)
]
if not delta_lines:
return None
prefix: list[str] = []
for line in lines:
if (
line == COMMENT_MARKER
or line.startswith("## ")
or line.startswith("**Summary:**")
):
prefix.append(line)
if len(prefix) >= 3:
break
detail_lines = (
["<details>", "<summary>Top risks and evidence</summary>", ""]
if "<details>" in lines
else []
)
compact_lines = prefix + delta_lines + detail_lines
compact = "\n".join(compact_lines)
if len(compact) <= limit:
return compact
compact_lines = [
_shorten(line, 72) if line.startswith("**Summary:**") else line
for line in compact_lines
]
compact = "\n".join(compact_lines)
if len(compact) <= limit:
return compact
compact = "\n".join(
[line for line in compact_lines if not line.startswith("**Summary:**")]
)
if len(compact) <= limit:
return compact
return None
def _format_timestamp(value: str | None) -> str:
if not value:
return "timestamp unavailable"
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return value
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=UTC)
return parsed.astimezone(UTC).strftime("%Y-%m-%d %H:%M UTC")
def _split_changed_files(raw_value: str) -> list[str]:
normalized = raw_value.replace(",", "\n")
return [item.strip() for item in normalized.splitlines() if item.strip()]
def _dedupe_paths(paths: Iterable[str]) -> list[str]:
unique_paths: list[str] = []
seen: set[str] = set()
for raw_path in paths:
normalized = Path(raw_path).as_posix().lstrip("./")
if not normalized or normalized in seen:
continue
seen.add(normalized)
unique_paths.append(normalized)
return unique_paths
def _load_event_payload(environ: dict[str, str] | None = None) -> dict:
env = environ or os.environ
event_path = env.get("GITHUB_EVENT_PATH")
if not event_path:
return {}
payload_path = Path(event_path)
if not payload_path.is_file():
return {}
try:
return json.loads(payload_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ActionRuntimeError(
f"GITHUB_EVENT_PATH does not contain valid JSON: {payload_path}"
) from exc
def _decode_content(raw_content: bytes | None) -> str:
if not raw_content:
return ""
return raw_content.decode("utf-8", errors="ignore")
def _content_preview(content: str, *, line_limit: int = 100) -> str:
return "\n".join(content.splitlines()[:line_limit])
def is_sensitive_file(name: str) -> bool:
lower_name = name.lower()
path = Path(lower_name)
if path.name in SENSITIVE_FILE_MARKERS:
return True
return any(marker in lower_name for marker in SENSITIVE_FILE_MARKERS)
def detect_tool_type(name: str, raw_content: bytes | None = None) -> str:
lower_name = name.lower()
path = Path(lower_name)
content = _decode_content(raw_content)
if lower_name == "jenkinsfile" or path.name == "jenkinsfile":
return "jenkins"
if path.suffix in {".tf", ".tfvars", ".hcl"}:
return "terraform"
if path.suffix == ".json":
try:
payload = json.loads(content) if content else {}
except json.JSONDecodeError:
payload = {}
if isinstance(payload, dict):
if "resource_changes" in payload:
return "terraform"
if any(
key in payload
for key in (
"AWSTemplateFormatVersion",
"Resources",
"Parameters",
"Outputs",
)
):
return "cloudformation"
if path.suffix in {".yaml", ".yml"}:
preview = _content_preview(content)
if re.search(
r"(?m)^(AWSTemplateFormatVersion|Resources|Parameters|Outputs)\s*:",
preview,
) or re.search(
r"(?m)(!Ref\b|!Sub\b|!GetAtt\b|Fn::Sub\b|Fn::Join\b|Fn::GetAtt\b|AWS::)",
preview,
):
return "cloudformation"
if re.search(r"(?m)^\s*apiVersion\s*:\s*\S+", content) and re.search(
r"(?m)^\s*kind\s*:\s*\S+", content
):
return "kubernetes"
if re.search(r"(?m)^\s*Transform\s*:\s*AWS::", content):
return "cloudformation"
if re.search(r"(?m)^\s*(hosts|tasks|roles)\s*:", content):
return "ansible"
return "unsupported"
def load_github_context(environ: dict[str, str] | None = None) -> dict[str, object]:
"""Load the GitHub event context required for changed-file discovery."""
env = environ or os.environ
payload = _load_event_payload(env)
pull_request = payload.get("pull_request") or {}
base_ref = pull_request.get("base") or {}
head_ref = pull_request.get("head") or {}
return {
"event_name": str(env.get("GITHUB_EVENT_NAME") or ""),
"repository": str(env.get("GITHUB_REPOSITORY") or ""),
"sha": str(env.get("GITHUB_SHA") or ""),
"pull_request_number": payload.get("number") or pull_request.get("number"),
"base_sha": base_ref.get("sha"),
"head_sha": head_ref.get("sha") or env.get("GITHUB_SHA"),
}
def _git_output(repo_root: Path, *args: str) -> str:
try:
completed = subprocess.run(
["git", *args],
cwd=repo_root,
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as exc:
message = (exc.stderr or exc.stdout or "").strip()
raise ActionRuntimeError(
f"Git command failed: git {' '.join(args)}"
+ (f" ({message})" if message else "")
) from exc
return completed.stdout.strip()
def _ensure_commit_available(repo_root: Path, sha: str) -> None:
if not sha:
return
try:
subprocess.run(
["git", "cat-file", "-e", f"{sha}^{{commit}}"],
cwd=repo_root,
check=True,
capture_output=True,
text=True,
)
return
except subprocess.CalledProcessError:
pass
_git_output(repo_root, "fetch", "--no-tags", "--depth=1", "origin", sha)
def discover_changed_files(repo_root: Path, context: dict[str, object]) -> list[str]:
"""Determine changed files for the current GitHub event."""
base_sha = str(context.get("base_sha") or "")
head_sha = str(context.get("head_sha") or "")
if base_sha and head_sha:
_ensure_commit_available(repo_root, base_sha)
_ensure_commit_available(repo_root, head_sha)
output = _git_output(
repo_root,
"diff",
"--name-only",
"--diff-filter=ACMR",
f"{base_sha}...{head_sha}",
)
return _dedupe_paths(output.splitlines())
output = _git_output(
repo_root,
"diff-tree",
"--no-commit-id",
"--name-only",
"-r",
"HEAD",
)
return _dedupe_paths(output.splitlines())
def select_artifacts_for_upload(
repo_root: Path, changed_files: Iterable[str]
) -> tuple[list[tuple[str, bytes]], list[str]]:
"""Filter changed files down to supported DeployWhisper artifacts."""
candidates: list[tuple[str, bytes]] = []
skipped: list[str] = []
for relative_path in _dedupe_paths(changed_files):
file_path = (repo_root / relative_path).resolve()
try:
file_path.relative_to(repo_root.resolve())
except ValueError:
skipped.append(f"{relative_path} (outside working directory)")
continue
if not file_path.is_file():
skipped.append(f"{relative_path} (missing or deleted)")
continue
candidates.append((relative_path, file_path.read_bytes()))
upload_files: list[tuple[str, bytes]] = []
for name, raw_content in candidates:
if is_sensitive_file(name):
skipped.append(f"{name} (sensitive)")
continue
if detect_tool_type(name, raw_content) not in SUPPORTED_TOOL_TYPES:
skipped.append(f"{name} (unsupported)")
continue
upload_files.append((name, raw_content))
return upload_files, skipped
def _resolve_analysis_endpoint(api_url: str) -> str:
parsed = parse.urlparse(api_url)
if not parsed.scheme or not parsed.netloc:
raise ActionRuntimeError(
"The `api-url` input must be an absolute DeployWhisper URL."
)
path = parsed.path.rstrip("/")
if not path:
path = "/api/v1/analyses"
elif path.endswith("/api/v1"):
path = f"{path}/analyses"
elif not path.endswith("/api/v1/analyses"):
path = f"{path}/api/v1/analyses"
return parse.urlunparse(
parsed._replace(path=path, params="", query="", fragment="")
)
def _multipart_body(
files: list[tuple[str, bytes]], fields: dict[str, str] | None = None
) -> tuple[bytes, str]:
boundary = f"deploywhisper-{uuid.uuid4().hex}"
body = bytearray()
for name, value in (fields or {}).items():
if value == "":
continue
body.extend(f"--{boundary}\r\n".encode("utf-8"))
body.extend(
f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("utf-8")
)
body.extend(value.encode("utf-8"))
body.extend(b"\r\n")
for filename, content in files:
body.extend(f"--{boundary}\r\n".encode("utf-8"))
disposition = (
'Content-Disposition: form-data; name="files"; '
f'filename="{Path(filename).name}"\r\n'
)
body.extend(disposition.encode("utf-8"))
body.extend(b"Content-Type: application/octet-stream\r\n\r\n")
body.extend(content)
body.extend(b"\r\n")
body.extend(f"--{boundary}--\r\n".encode("utf-8"))
return bytes(body), boundary
def _http_json(request_obj: request.Request) -> dict:
try:
with request.urlopen(request_obj, timeout=120) as response:
return json.loads(response.read().decode("utf-8"))
except error.HTTPError as exc:
payload = exc.read().decode("utf-8", errors="ignore")
raise ActionRuntimeError(
f"DeployWhisper API request failed with HTTP {exc.code}: "
f"{payload or exc.reason}"
) from exc
except error.URLError as exc:
raise ActionRuntimeError(
f"DeployWhisper API request could not be completed: {exc.reason}"
) from exc
except json.JSONDecodeError as exc:
raise ActionRuntimeError(
"DeployWhisper API returned a non-JSON response."
) from exc
def _truthy_input(value: object) -> bool:
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
def validate_scope_inputs(
*,
project_key: str | None,
project_id: str | None,
workspace_key: str | None,
workspace_id: str | None,
allow_derived_project_scope: bool,
) -> dict[str, str]:
project_key = (project_key or "").strip()
project_id = (project_id or "").strip()
workspace_key = (workspace_key or "").strip()
workspace_id = (workspace_id or "").strip()
for label, value in {
"project-key": project_key,
"project-id": project_id,
"workspace-key": workspace_key,
"workspace-id": workspace_id,
}.items():
if "\r" in value or "\n" in value:
raise ActionRuntimeError(f"{label} must not contain newline characters.")
for label, value in {
"project-id": project_id,
"workspace-id": workspace_id,
}.items():
if value and not re.fullmatch(r"[1-9][0-9]*", value):
raise ActionRuntimeError(f"{label} must be a positive numeric id.")
if project_key and project_id:
raise ActionRuntimeError(
"Provide only one project scope input: project-key or project-id."
)
if workspace_key and workspace_id:
raise ActionRuntimeError(
"Provide only one workspace scope input: workspace-key or workspace-id."
)
if (workspace_key or workspace_id) and not project_key and not project_id:
raise ActionRuntimeError(
"Workspace scope is project-local. Provide project-key or project-id "
"with workspace-key or workspace-id."
)
if not project_key and not project_id and not allow_derived_project_scope:
raise ActionRuntimeError(
"Project scope is required. Provide project-key or project-id, "
"or set allow-derived-project-scope to true when the API endpoint "
"derives project scope."
)
return {
"project_key": project_key,
"project_id": project_id,
"workspace_key": workspace_key,
"workspace_id": workspace_id,
}
def _github_api_json(
url: str,
*,
github_token: str,
method: str = "GET",
payload: dict | None = None,
) -> dict | list[dict]:
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {github_token}",
"X-GitHub-Api-Version": "2022-11-28",
}
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = request.Request(url, data=data, headers=headers, method=method)
try:
with request.urlopen(req, timeout=120) as response:
return json.loads(response.read().decode("utf-8"))
except error.HTTPError as exc:
response_body = exc.read().decode("utf-8", errors="ignore")
raise ActionRuntimeError(
f"GitHub API request failed with HTTP {exc.code}: "
f"{response_body or exc.reason}"
) from exc
except error.URLError as exc:
raise ActionRuntimeError(
f"GitHub API request could not be completed: {exc.reason}"
) from exc
except json.JSONDecodeError as exc:
raise ActionRuntimeError("GitHub API returned a non-JSON response.") from exc
def submit_analysis(
api_url: str,
artifacts: list[tuple[str, bytes]],
*,
api_token: str | None,
project_key: str | None = None,
project_id: str | None = None,
workspace_key: str | None = None,
workspace_id: str | None = None,
trigger_type: str,
trigger_id: str,
) -> dict:
"""POST artifacts to the existing analyses API."""
endpoint = _resolve_analysis_endpoint(api_url)
scope_fields = {
"project_key": (project_key or "").strip(),
"project_id": (project_id or "").strip(),
"workspace_key": (workspace_key or "").strip(),
"workspace_id": (workspace_id or "").strip(),
}
body, boundary = _multipart_body(artifacts, scope_fields)
headers = {
"Accept": "application/json",
"Content-Type": f"multipart/form-data; boundary={boundary}",
"Content-Length": str(len(body)),
"X-DeployWhisper-Trigger-Type": trigger_type,
"X-DeployWhisper-Trigger-Id": trigger_id,
}
if api_token:
headers["Authorization"] = f"Bearer {api_token}"
req = request.Request(endpoint, data=body, headers=headers, method="POST")
return _http_json(req)
def _scan_meta_marker(scan_meta: dict[str, object]) -> str:
return f"<!-- {SCAN_META_MARKER} {json.dumps(scan_meta, separators=(',', ':'))} -->"
def _scan_meta_int(payload: dict[str, object], key: str) -> int:
value = payload[key]
if isinstance(value, bool):
raise ValueError(f"{key} must be an integer.")
if isinstance(value, int):
return value
if isinstance(value, str) and re.fullmatch(r"[0-9]+", value.strip()):
return int(value.strip())
raise ValueError(f"{key} must be an integer.")
def extract_comment_metadata(comment_body: str) -> dict[str, object] | None:
match = re.search(
r"<!--\s*deploywhisper:scan-meta\s+(\{.*?\})\s*-->",
comment_body,
re.DOTALL,
)
if not match:
return None
try:
payload = json.loads(match.group(1))
except json.JSONDecodeError:
return None
if not isinstance(payload, dict):
return None
try:
report_id = _scan_meta_int(payload, "report_id")
risk_score = _scan_meta_int(payload, "risk_score")
if report_id <= 0 or risk_score < 0:
return None
raw_findings = payload.get("findings")
findings = _scan_meta_findings(raw_findings)
finding_keys = _scan_meta_finding_keys_from_payload(payload)
if finding_keys is None:
finding_keys, _, _ = _scan_meta_finding_keys(
raw_findings,
limit=len(_dict_items(raw_findings)),
)
return {
"report_id": report_id,
"risk_score": risk_score,
"severity": str(payload.get("severity") or "").lower(),
"recommendation": str(payload.get("recommendation") or "").lower(),
"created_at": str(payload.get("created_at") or ""),
"head_sha": str(payload.get("head_sha") or ""),
"finding_keys": finding_keys,
"findings": findings,
"findings_total": _safe_int(payload.get("findings_total"), len(finding_keys)),
"findings_truncated": payload.get("findings_truncated") is True,
"finding_labels_truncated": payload.get("finding_labels_truncated") is True,
}
except (KeyError, TypeError, ValueError):
return None
def _current_scan_meta(
current_report: dict[str, object], *, head_sha: str | None
) -> dict[str, object]:
finding_keys, findings_total, findings_truncated = _scan_meta_finding_keys(
current_report.get("findings")
)
scan_meta = {
"report_id": _safe_int(current_report.get("id")),
"risk_score": _safe_int(current_report.get("risk_score")),
"severity": str(current_report.get("severity") or "").lower(),
"recommendation": str(current_report.get("recommendation") or "").lower(),
"created_at": str(current_report.get("created_at") or ""),
}
if head_sha:
scan_meta["head_sha"] = head_sha
if finding_keys:
scan_meta["finding_keyset"] = _pack_finding_keys(finding_keys)
label_limit = min(len(finding_keys), SCAN_META_LABEL_LIMIT)
findings = _scan_meta_findings(current_report.get("findings"), limit=label_limit)
if findings:
scan_meta["findings"] = findings
if len(findings) < len(finding_keys):
scan_meta["finding_labels_truncated"] = True
if findings_truncated:
scan_meta["findings_total"] = findings_total
scan_meta["findings_truncated"] = True
_shrink_scan_meta_labels(scan_meta)
return scan_meta
def _shrink_scan_meta_labels(scan_meta: dict[str, object]) -> None:
findings = scan_meta.get("findings")
if not isinstance(findings, list):
return
while findings and len(_scan_meta_marker(scan_meta)) > SCAN_META_MARKER_LENGTH_LIMIT:
findings.pop()
scan_meta["finding_labels_truncated"] = True
if not findings:
scan_meta.pop("findings", None)
def _pack_finding_keys(keys: list[str]) -> str:
return "".join(key for key in keys if re.fullmatch(r"[a-f0-9]{16}", key))
def _unpack_finding_keyset(value: object) -> list[str] | None:
if not isinstance(value, str):
return None
keyset = value.strip().lower()
if not keyset:
return []
if len(keyset) % SCAN_META_KEY_LENGTH != 0:
return None
if not re.fullmatch(r"[a-f0-9]+", keyset):
return None
return [
keyset[index : index + SCAN_META_KEY_LENGTH]
for index in range(0, len(keyset), SCAN_META_KEY_LENGTH)
]
def _scan_meta_finding_keys_from_payload(payload: dict[str, object]) -> list[str] | None:
compact_keys = _unpack_finding_keyset(payload.get("finding_keyset"))
if compact_keys is not None:
return compact_keys
raw_keys = payload.get("finding_keys")
if not isinstance(raw_keys, list):
return None
keys: list[str] = []
seen: set[str] = set()
for raw_key in raw_keys:
key = _finding_identity_key({"key": raw_key})
if key and key not in seen:
seen.add(key)
keys.append(key)
return keys
def _nonblank_string(value: object) -> str:
return str(value or "").strip()
def _single_line_string(value: object) -> str:
return " ".join(_nonblank_string(value).split())
def _mapping_or_empty(value: object) -> dict:
return dict(value) if isinstance(value, dict) else {}
def _dict_items(value: object) -> list[dict]:
return (
[item for item in value if isinstance(item, dict)]
if isinstance(value, list)
else []
)
def _safe_int(value: object, default: int = 0) -> int:
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
if isinstance(value, str) and re.fullmatch(r"[0-9]+", value.strip()):
return int(value.strip())
return default
def _markdown_text(value: object) -> str:
text = _single_line_string(value)
replacements = {
"<!--": "<\\!--",
"-->": "--\\>",
"\\": "\\\\",
"<": "\\<",
">": "\\>",
"[": "\\[",
"]": "\\]",
"(": "\\(",
")": "\\)",
"#": "\\#",
"*": "\\*",
"_": "\\_",
"`": "\\`",
"|": "\\|",
"!": "\\!",
}
for source, replacement in replacements.items():
text = text.replace(source, replacement)
return text
def _comment_link(value: object) -> str:
link = _nonblank_string(value)
if not link:
return ""
if any(character.isspace() or character in '<>"' for character in link):
return ""
parsed = parse.urlparse(link)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return ""
return link.replace("(", "%28").replace(")", "%29")
def _finite_rate(value: object) -> float | None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
rate = float(value)
return rate if math.isfinite(rate) else None
def _scan_meta_text(value: object, limit: int) -> str:
text = _shorten(_single_line_string(value), limit)
return (
text.replace("<!--", "")
.replace("-->", "")
.replace("<", "")
.replace(">", "")
)
def _compact_finding_key(value: str) -> str:
normalized = " ".join(value.lower().split())
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:SCAN_META_KEY_LENGTH]
def _finding_title(finding: dict[str, object]) -> str:
return (
_nonblank_string(finding.get("title"))
or _nonblank_string(finding.get("description"))
or _nonblank_string(finding.get("summary"))
or _nonblank_string(finding.get("finding_id"))
or _nonblank_string(finding.get("id"))
)
def _finding_severity(finding: dict[str, object]) -> str:
severity = _single_line_string(finding.get("severity")).lower()
return severity or "unknown"
def _finding_identity_key(finding: dict[str, object]) -> str:
existing_key = _nonblank_string(finding.get("key"))
if existing_key:
if re.fullmatch(r"[a-f0-9]{16}", existing_key):
return existing_key
return _compact_finding_key(f"key:{existing_key}")
for field_name in ("finding_id", "id"):
stable_id = _nonblank_string(finding.get(field_name))
if stable_id:
return _compact_finding_key(f"{field_name}:{stable_id}")
title = _finding_title(finding)
if not title:
return ""
category = (
_nonblank_string(finding.get("category"))
or _nonblank_string(finding.get("resource_category"))
)
discriminator = _finding_discriminator(finding)
identity = {
"category": _single_line_string(category).lower(),
"title": _single_line_string(title).lower(),
"discriminator": discriminator.lower(),
}
return _compact_finding_key(json.dumps(identity, separators=(",", ":"), sort_keys=True))
def _finding_discriminator(finding: dict[str, object]) -> str:
values: list[str] = []
for field_name in (
"resource",
"resource_id",
"resource_name",
"resource_address",
"address",
"target",
"location",
"path",
"file",
"filename",
"line",
"service",
"name",
):
value = _nonblank_string(finding.get(field_name))
if value:
values.append(f"{field_name}:{value}")
evidence_refs = finding.get("evidence_refs")
if isinstance(evidence_refs, list):
values.extend(
f"evidence:{item_value}"
for item_value in sorted(
{
_single_line_string(item).lower()
for item in evidence_refs
if _single_line_string(item)
}
)
)
return "|".join(values)
def _scan_meta_findings(
value: object, *, limit: int = SCAN_META_LABEL_LIMIT
) -> list[dict[str, str]]:
findings: list[dict[str, str]] = []
seen: set[str] = set()
for raw_finding in _dict_items(value):
if len(findings) >= limit:
break
key = _finding_identity_key(raw_finding)
title = _finding_title(raw_finding)
if not key or key in seen or not title:
continue
seen.add(key)
findings.append(
{
"key": key,
"severity": _scan_meta_text(_finding_severity(raw_finding), 16),
"title": _scan_meta_text(title, 72),
}
)
return findings
def _scan_meta_finding_keys(
value: object, *, limit: int = SCAN_META_KEY_LIMIT
) -> tuple[list[str], int, bool]:
keys: list[str] = []
seen: set[str] = set()
total = 0
for raw_finding in _dict_items(value):
key = _finding_identity_key(raw_finding)
if not key or key in seen:
continue
seen.add(key)
total += 1
if len(keys) < limit:
keys.append(key)
return keys, total, total > len(keys)
def _finding_lookup(value: object) -> dict[str, dict[str, str]] | None:
if isinstance(value, dict):
keys = _scan_meta_finding_keys_from_payload(value)
labels = {
item["key"]: item
for item in _scan_meta_findings(value.get("findings"))
if _nonblank_string(item.get("key"))
}
if keys is not None:
lookup: dict[str, dict[str, str]] = {}
for key in keys:
lookup[key] = labels.get(key, {"key": key})
return lookup
if "findings" in value:
return labels
return None
if isinstance(value, list):
return {
item["key"]: item
for item in _scan_meta_findings(value, limit=len(value))
if _nonblank_string(item.get("key"))
}
return None
def _finding_delta(
previous_scan: dict[str, object] | None,
current_report: dict[str, object] | None,
) -> dict[str, list[dict[str, str]]]:
if not previous_scan or not current_report:
return {"new": [], "resolved": [], "persistent": []}
previous = _finding_lookup(previous_scan)
current = _finding_lookup(current_report.get("findings"))
if previous is None or current is None:
return {"new": [], "resolved": [], "persistent": []}
previous_keys = set(previous)
current_keys = set(current)
return {
"new": [current[key] for key in current if key not in previous_keys],
"resolved": [previous[key] for key in previous if key not in current_keys],
"persistent": [current[key] for key in current if key in previous_keys],
}
def _finding_label(finding: dict[str, str], *, limit: int) -> str:
severity = _markdown_text(finding.get("severity")).upper() or "UNKNOWN"
title = _shorten(_markdown_text(finding.get("title") or "Untitled finding"), limit)
return f"{severity} {title}"
def _finding_has_label(finding: dict[str, str]) -> bool:
return bool(_nonblank_string(finding.get("title")))
def _finding_delta_lines(
previous_scan: dict[str, object] | None,
current_report: dict[str, object] | None,
*,
limit: int,
) -> list[str]:
if isinstance(previous_scan, dict) and bool(previous_scan.get("findings_truncated")):
return [
(
"- Finding changes: previous marker was capped; exact new / resolved / "
"persistent counts are unavailable."
)
]
delta = _finding_delta(previous_scan, current_report)
if not any(delta.values()):
return []
partial = (
isinstance(previous_scan, dict)
and bool(previous_scan.get("findings_truncated"))
)
partial_note = " (partial; previous marker capped)" if partial else ""
lines = [
(
"- Finding changes: "
f"{len(delta['new'])} new / {len(delta['resolved'])} resolved / "
f"{len(delta['persistent'])} persistent{partial_note}"
)
]
examples = (
("New finding", delta["new"]),
("Resolved finding", delta["resolved"]),
("Persistent finding", delta["persistent"]),
)
for label, findings in examples:
finding = next((item for item in findings if _finding_has_label(item)), None)
if finding:
lines.append(f"- {label}: {_finding_label(finding, limit=limit)}")
return lines