-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmessages.py
More file actions
1249 lines (1117 loc) · 53.6 KB
/
messages.py
File metadata and controls
1249 lines (1117 loc) · 53.6 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
import json
import logging
import os
import re
import uuid
from datetime import datetime
from pathlib import Path
from mdutils import MdUtils
from prettytable import PrettyTable
from socketsecurity.core.classes import Diff, Issue, Purl
log = logging.getLogger("socketcli")
class Messages:
@staticmethod
def map_severity_to_sarif(severity: str) -> str:
"""
Map Socket severity levels to SARIF levels (GitHub code scanning).
'low' -> 'note'
'medium' or 'middle' -> 'warning'
'high' or 'critical' -> 'error'
"""
severity_mapping = {
"low": "note",
"medium": "warning",
"middle": "warning", # older data might say "middle"
"high": "error",
"critical": "error",
}
return severity_mapping.get(severity.lower(), "note")
@staticmethod
def get_manifest_file_url(diff: Diff, manifest_path: str, config=None) -> str:
"""
Generate proper URL for manifest file based on the repository type and diff URL.
:param diff: Diff object containing diff_url and report_url
:param manifest_path: Path to the manifest file (can contain multiple files separated by ';')
:param config: Configuration object to determine SCM type
:return: Properly formatted URL for the manifest file
"""
if not manifest_path:
return ""
# Handle multiple manifest files separated by ';' - use the first one
first_manifest = manifest_path.split(';')[0] if ';' in manifest_path else manifest_path
# Clean up the manifest path - remove build agent paths and normalize
clean_path = first_manifest
# Remove common build agent path prefixes
prefixes_to_remove = [
'opt/buildagent/work/',
'/opt/buildagent/work/',
'home/runner/work/',
'/home/runner/work/',
]
for prefix in prefixes_to_remove:
if clean_path.startswith(prefix):
# Find the part after the build ID (usually a hash)
parts = clean_path[len(prefix):].split('/', 2)
if len(parts) >= 3:
clean_path = parts[2] # Take everything after build ID and repo name
break
# Remove leading slashes
clean_path = clean_path.lstrip('/')
# Determine SCM type from config or diff_url
scm_type = "api" # Default to API
if config and hasattr(config, 'scm'):
scm_type = config.scm.lower()
elif hasattr(diff, 'diff_url') and diff.diff_url:
diff_url = diff.diff_url.lower()
if 'github.com' in diff_url or 'github' in diff_url:
scm_type = "github"
elif 'gitlab' in diff_url:
scm_type = "gitlab"
elif 'bitbucket' in diff_url:
scm_type = "bitbucket"
# Generate URL based on SCM type using config information
# NEVER use diff.diff_url for SCM URLs - those are Socket URLs for "View report" links
if scm_type == "github":
if config and hasattr(config, 'repo') and config.repo:
# Get branch from config, default to main
branch = getattr(config, 'branch', 'main') if hasattr(config, 'branch') and config.branch else 'main'
# Construct GitHub URL from repo info (could be github.com or GitHub Enterprise)
github_server = os.getenv('GITHUB_SERVER_URL', 'https://github.com')
return f"{github_server}/{config.repo}/blob/{branch}/{clean_path}"
elif scm_type == "gitlab":
if config and hasattr(config, 'repo') and config.repo:
# Get branch from config, default to main
branch = getattr(config, 'branch', 'main') if hasattr(config, 'branch') and config.branch else 'main'
# Construct GitLab URL from repo info (could be gitlab.com or self-hosted GitLab)
gitlab_server = os.getenv('CI_SERVER_URL', 'https://gitlab.com')
return f"{gitlab_server}/{config.repo}/-/blob/{branch}/{clean_path}"
elif scm_type == "bitbucket":
if config and hasattr(config, 'repo') and config.repo:
# Get branch from config, default to main
branch = getattr(config, 'branch', 'main') if hasattr(config, 'branch') and config.branch else 'main'
# Construct Bitbucket URL from repo info (could be bitbucket.org or Bitbucket Server)
bitbucket_server = os.getenv('BITBUCKET_SERVER_URL', 'https://bitbucket.org')
return f"{bitbucket_server}/{config.repo}/src/{branch}/{clean_path}"
# Fallback to Socket file view for API or unknown repository types
if hasattr(diff, 'report_url') and diff.report_url:
# Strip leading slash and URL encode for Socket dashboard
socket_path = clean_path.lstrip('/')
encoded_path = socket_path.replace('/', '%2F')
return f"{diff.report_url}?tab=files&file={encoded_path}"
return ""
@staticmethod
def find_line_in_file(packagename: str, packageversion: str, manifest_file: str) -> tuple:
"""
Finds the line number and snippet of code for the given package/version in a manifest file.
Returns a 2-tuple: (line_number, snippet_or_message).
Supports:
1) JSON-based manifest files (package-lock.json, Pipfile.lock, composer.lock)
- Locates a dictionary entry with the matching package & version
- Searches the raw text for the key
2) Text-based (requirements.txt, package.json, yarn.lock, pnpm-lock.yaml, etc.)
- Uses regex patterns to detect a match line by line
"""
file_type = Path(manifest_file).name
log.debug("Processing file for line lookup: %s", manifest_file)
if file_type in ["package-lock.json", "Pipfile.lock", "composer.lock"]:
try:
with open(manifest_file, "r", encoding="utf-8") as f:
raw_text = f.read()
log.debug("Read %d characters from %s", len(raw_text), manifest_file)
data = json.loads(raw_text)
packages_dict = (
data.get("packages")
or data.get("default")
or data.get("dependencies")
or {}
)
log.debug("Found package keys in %s: %s", manifest_file, list(packages_dict.keys()))
found_key = None
found_info = None
for key, value in packages_dict.items():
if key.endswith(packagename) and "version" in value:
if value["version"] == packageversion:
found_key = key
found_info = value
break
if found_key and found_info:
needle_key = f'"{found_key}":'
lines = raw_text.splitlines()
log.debug("Total lines in %s: %d", manifest_file, len(lines))
for i, line in enumerate(lines, start=1):
if needle_key in line:
log.debug("Found match at line %d in %s: %s", i, manifest_file, line.strip())
return i, line.strip()
return 1, f'"{found_key}": {found_info}'
else:
return 1, f"{packagename} {packageversion} (not found in {manifest_file})"
except (FileNotFoundError, json.JSONDecodeError) as e:
log.error("Error reading %s: %s", manifest_file, e)
return 1, f"Error reading {manifest_file}"
# For pnpm-lock.yaml, use a special regex pattern.
if file_type.lower() == "pnpm-lock.yaml":
searchstring = rf'^\s*/{re.escape(packagename)}/{re.escape(packageversion)}:'
else:
search_patterns = {
"package.json": rf'"{packagename}":\s*"[\^~]?{re.escape(packageversion)}"',
"yarn.lock": rf'{packagename}@{packageversion}',
"requirements.txt": rf'^{re.escape(packagename)}\s*(?:==|===|!=|>=|<=|~=|\s+)?\s*{re.escape(packageversion)}(?:\s*;.*)?$',
"pyproject.toml": rf'{packagename}\s*=\s*"{re.escape(packageversion)}"',
"Pipfile": rf'"{packagename}"\s*=\s*"{re.escape(packageversion)}"',
"go.mod": rf'require\s+{re.escape(packagename)}\s+{re.escape(packageversion)}',
"go.sum": rf'{re.escape(packagename)}\s+{re.escape(packageversion)}',
"pom.xml": rf'<artifactId>{re.escape(packagename)}</artifactId>\s*<version>{re.escape(packageversion)}</version>',
"build.gradle": rf'implementation\s+"{re.escape(packagename)}:{re.escape(packageversion)}"',
"Gemfile": rf'gem\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"',
"Gemfile.lock": rf'\s+{re.escape(packagename)}\s+\({re.escape(packageversion)}\)',
".csproj": rf'<PackageReference\s+Include="{re.escape(packagename)}"\s+Version="{re.escape(packageversion)}"\s*/>',
".fsproj": rf'<PackageReference\s+Include="{re.escape(packagename)}"\s+Version="{re.escape(packageversion)}"\s*/>',
"paket.dependencies": rf'nuget\s+{re.escape(packagename)}\s+{re.escape(packageversion)}',
"Cargo.toml": rf'{re.escape(packagename)}\s*=\s*"{re.escape(packageversion)}"',
"build.sbt": rf'"{re.escape(packagename)}"\s*%\s*"{re.escape(packageversion)}"',
"Podfile": rf'pod\s+"{re.escape(packagename)}",\s*"{re.escape(packageversion)}"',
"Package.swift": rf'\.package\(name:\s*"{re.escape(packagename)}",\s*url:\s*".*?",\s*version:\s*"{re.escape(packageversion)}"\)',
"mix.exs": rf'\{{:{re.escape(packagename)},\s*"{re.escape(packageversion)}"\}}',
"composer.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"',
"conanfile.txt": rf'{re.escape(packagename)}/{re.escape(packageversion)}',
"vcpkg.json": rf'"{re.escape(packagename)}":\s*"{re.escape(packageversion)}"',
}
searchstring = search_patterns.get(file_type, rf'{re.escape(packagename)}.*{re.escape(packageversion)}')
log.debug("Using search pattern for %s: %s", file_type, searchstring)
try:
with open(manifest_file, 'r', encoding="utf-8") as file:
lines = [line.rstrip("\n") for line in file]
log.debug("Total lines in %s: %d", manifest_file, len(lines))
for line_number, line_content in enumerate(lines, start=1):
line_main = line_content.split(";", 1)[0].strip()
if re.search(searchstring, line_main, re.IGNORECASE):
log.debug("Match found at line %d in %s: %s", line_number, manifest_file, line_content.strip())
return line_number, line_content.strip()
except FileNotFoundError:
return 1, f"{manifest_file} not found"
except Exception as e:
return 1, f"Error reading {manifest_file}: {e}"
return 1, f"{packagename} {packageversion} (not found)"
@staticmethod
def get_manifest_type_url(manifest_file: str, pkg_name: str, pkg_version: str) -> str:
"""
Determine the correct URL path based on the manifest file type.
"""
manifest_to_url_prefix = {
"package.json": "npm",
"package-lock.json": "npm",
"yarn.lock": "npm",
"pnpm-lock.yaml": "npm",
"requirements.txt": "pypi",
"pyproject.toml": "pypi",
"Pipfile": "pypi",
"go.mod": "go",
"go.sum": "go",
"pom.xml": "maven",
"build.gradle": "maven",
".csproj": "nuget",
".fsproj": "nuget",
"paket.dependencies": "nuget",
"Cargo.toml": "cargo",
"Gemfile": "rubygems",
"Gemfile.lock": "rubygems",
"composer.json": "composer",
"vcpkg.json": "vcpkg",
}
file_type = Path(manifest_file).name
url_prefix = manifest_to_url_prefix.get(file_type, "unknown")
return f"https://socket.dev/{url_prefix}/package/{pkg_name}/alerts/{pkg_version}"
@staticmethod
def create_security_comment_sarif(diff) -> dict:
"""
Create SARIF-compliant output from the diff report, including dynamic URL generation
based on manifest type and improved <br/> formatting for GitHub SARIF display.
This function now:
- Processes every alert in diff.new_alerts.
- For alerts with multiple manifest files, generates an individual SARIF result for each file.
- Appends the manifest file name to the rule ID and name to make each result unique.
- Does NOT fall back to 'requirements.txt' if no manifest file is provided.
- Adds detailed log to validate our assumptions.
"""
if len(diff.new_alerts) == 0:
for alert in diff.new_alerts:
if alert.error:
break
sarif_data = {
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": {
"driver": {
"name": "Socket Security",
"informationUri": "https://socket.dev",
"rules": []
}
},
"results": []
}]
}
rules_map = {}
results_list = []
for alert in diff.new_alerts:
pkg_name = alert.pkg_name
pkg_version = alert.pkg_version
base_rule_id = f"{pkg_name}=={pkg_version}"
severity = alert.severity
log.debug("Alert %s - introduced_by: %s, manifests: %s", base_rule_id, alert.introduced_by, getattr(alert, 'manifests', None))
manifest_files = []
if alert.introduced_by and isinstance(alert.introduced_by, list):
for entry in alert.introduced_by:
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
files = [f.strip() for f in entry[1].split(";") if f.strip()]
manifest_files.extend(files)
elif isinstance(entry, str):
manifest_files.extend([m.strip() for m in entry.split(";") if m.strip()])
elif hasattr(alert, 'manifests') and alert.manifests:
manifest_files = [mf.strip() for mf in alert.manifests.split(";") if mf.strip()]
log.debug("Alert %s - extracted manifest_files: %s", base_rule_id, manifest_files)
if not manifest_files:
log.error("Alert %s: No manifest file found; cannot determine file location.", base_rule_id)
continue
log.debug("Alert %s - using manifest_files for processing: %s", base_rule_id, manifest_files)
# Create an individual SARIF result for each manifest file.
for mf in manifest_files:
log.debug("Alert %s - Processing manifest file: %s", base_rule_id, mf)
socket_url = Messages.get_manifest_type_url(mf, pkg_name, pkg_version)
line_number, line_content = Messages.find_line_in_file(pkg_name, pkg_version, mf)
if line_number < 1:
line_number = 1
log.debug("Alert %s: Manifest %s, line %d: %s", base_rule_id, mf, line_number, line_content)
# Create a unique rule id and name by appending the manifest file.
unique_rule_id = f"{base_rule_id} ({mf})"
rule_name = f"Alert {base_rule_id} ({mf})"
props = {}
if hasattr(alert, 'props') and alert.props:
props = alert.props
suggestion = ''
if hasattr(alert, 'suggestion'):
suggestion = alert.suggestion
alert_title = ''
if hasattr(alert, 'title'):
alert_title = alert.title
description = ''
if hasattr(alert, 'description'):
description = alert.description
short_desc = (f"{props.get('note', '')}<br/><br/>Suggested Action:<br/>{suggestion}"
f"<br/><a href=\"{socket_url}\">{socket_url}</a>")
full_desc = "{} - {}".format(alert_title, description.replace('\r\n', '<br/>'))
if unique_rule_id not in rules_map:
rules_map[unique_rule_id] = {
"id": unique_rule_id,
"name": rule_name,
"shortDescription": {"text": rule_name},
"fullDescription": {"text": full_desc},
"helpUri": socket_url,
"defaultConfiguration": {
"level": Messages.map_severity_to_sarif(severity)
},
}
result_obj = {
"ruleId": unique_rule_id,
"message": {"text": short_desc},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": mf},
"region": {
"startLine": line_number,
"snippet": {"text": line_content},
},
}
}]
}
results_list.append(result_obj)
sarif_data["runs"][0]["tool"]["driver"]["rules"] = list(rules_map.values())
sarif_data["runs"][0]["results"] = results_list
return sarif_data
@staticmethod
def _normalize_reachability(reachability: str) -> str:
return str(reachability or "unknown").strip().lower().replace("-", "_").replace(" ", "_")
@staticmethod
def _matches_reachability_filter(reachability: str, selector: str, undeterminable: bool = False) -> bool:
normalized = Messages._normalize_reachability(reachability)
selected = (selector or "all").strip().lower()
if selected == "all":
return True
if selected == "reachable":
return normalized == "reachable"
potential_states = {"unknown", "error", "maybe_reachable", "potentially_reachable"}
is_potential = normalized in potential_states or undeterminable
if selected == "potentially":
return is_potential
if selected == "reachable-or-potentially":
return normalized == "reachable" or is_potential
return True
@staticmethod
def create_security_comment_sarif_from_facts(
components_with_alerts: list,
reachability_filter: str = "all",
grouping: str = "instance",
) -> dict:
"""
Create SARIF output directly from reachability facts-derived alerts.
Args:
components_with_alerts: Components from convert_to_alerts(...)
reachability_filter: all|reachable|potentially|reachable-or-potentially
grouping: instance|alert
"""
sarif_data = {
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": {
"driver": {
"name": "Socket Security",
"informationUri": "https://socket.dev",
"rules": []
}
},
"results": []
}]
}
rules_map = {}
results_list = []
grouped_results = {}
for component in components_with_alerts or []:
comp_type = component.get("type", "unknown")
comp_name = component.get("name") or component.get("id") or "unknown-package"
comp_version = component.get("version") or "unknown-version"
fallback_uri = f"pkg:{comp_type}/{comp_name}@{comp_version}"
manifests = component.get("manifestFiles", [])
manifest_uris = []
if isinstance(manifests, list):
for mf in manifests:
if isinstance(mf, dict):
path = mf.get("path") or mf.get("file") or mf.get("name")
if path:
manifest_uris.append(str(path))
elif isinstance(mf, str):
manifest_uris.append(mf)
if not manifest_uris:
manifest_uris = [fallback_uri]
else:
# Preserve order while removing duplicate manifest entries.
manifest_uris = list(dict.fromkeys(manifest_uris))
for alert in component.get("alerts", []):
props = alert.get("props", {}) or {}
reachability = Messages._normalize_reachability(props.get("reachability", "unknown"))
undeterminable = bool(props.get("undeterminableReachability", False))
if not Messages._matches_reachability_filter(
reachability=reachability,
selector=reachability_filter,
undeterminable=undeterminable,
):
continue
vuln_id = props.get("ghsaId") or props.get("cveId") or alert.get("title") or "unknown-vulnerability"
severity = str(alert.get("severity", "low")).lower()
if grouping == "alert":
rule_id = f"{comp_name}:{vuln_id}"
rule_name = f"Reachability alert {vuln_id} in {comp_name}"
else:
rule_id = f"{comp_name}=={comp_version}:{vuln_id}"
rule_name = f"Reachability alert {vuln_id} in {comp_name}@{comp_version}"
socket_url = (
props.get("url")
or Messages.get_manifest_type_url(manifest_uris[0], comp_name, comp_version)
)
if rule_id not in rules_map:
rules_map[rule_id] = {
"id": rule_id,
"name": rule_name,
"shortDescription": {"text": rule_name},
"fullDescription": {"text": alert.get("title", rule_name)},
"helpUri": socket_url,
"defaultConfiguration": {
"level": Messages.map_severity_to_sarif(severity)
},
}
message = (
f"Reachability: {reachability}. "
f"Suggested Action:<br/>{props.get('range', '')}"
f"<br/><a href=\"{socket_url}\">{socket_url}</a>"
)
if grouping == "alert":
alert_key = props.get("key") or props.get("alertKey") or f"{comp_type}:{comp_name}:{vuln_id}"
existing = grouped_results.get(alert_key)
if not existing:
first_uri = manifest_uris[0]
grouped_results[alert_key] = {
"ruleId": rule_id,
"message": {"text": message},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": first_uri},
"region": {
"startLine": 1,
"snippet": {"text": f"{comp_name}@{comp_version}"}
},
}
}],
"properties": {
"reachability": reachability,
"reachabilityStates": [reachability],
"versions": [str(comp_version)],
"manifestUris": list(manifest_uris),
"purls": [props.get("purl")] if props.get("purl") else [],
"ghsaId": props.get("ghsaId"),
"cveId": props.get("cveId"),
"source": "socket-facts",
"socketAlertKey": alert_key,
}
}
else:
states = set(existing["properties"].get("reachabilityStates", []))
states.add(reachability)
existing["properties"]["reachabilityStates"] = sorted(states)
versions = set(existing["properties"].get("versions", []))
versions.add(str(comp_version))
existing["properties"]["versions"] = sorted(versions)
uris = set(existing["properties"].get("manifestUris", []))
uris.update(manifest_uris)
existing["properties"]["manifestUris"] = sorted(uris)
purls = set(existing["properties"].get("purls", []))
if props.get("purl"):
purls.add(props.get("purl"))
existing["properties"]["purls"] = sorted(purls)
else:
for uri in manifest_uris:
results_list.append({
"ruleId": rule_id,
"message": {"text": message},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": uri},
"region": {
"startLine": 1,
"snippet": {"text": f"{comp_name}@{comp_version}"}
},
}
}],
"properties": {
"reachability": reachability,
"purl": props.get("purl"),
"ghsaId": props.get("ghsaId"),
"cveId": props.get("cveId"),
"source": "socket-facts"
}
})
if grouping == "alert":
for grouped in grouped_results.values():
states = grouped["properties"].get("reachabilityStates", [])
if "reachable" in states:
grouped["properties"]["reachability"] = "reachable"
elif states:
grouped["properties"]["reachability"] = states[0]
results_list.append(grouped)
sarif_data["runs"][0]["tool"]["driver"]["rules"] = list(rules_map.values())
sarif_data["runs"][0]["results"] = results_list
return sarif_data
@staticmethod
def create_security_comment_json(diff: Diff) -> dict:
scan_failed = False
if len(diff.new_alerts) > 0:
for alert in diff.new_alerts:
alert: Issue
if alert.error:
scan_failed = True
break
output = {
"scan_failed": scan_failed,
"new_alerts": [],
"full_scan_id": diff.id,
"diff_url": diff.diff_url
}
for alert in diff.new_alerts:
alert: Issue
output["new_alerts"].append(json.loads(str(alert)))
return output
@staticmethod
def map_socket_severity_to_gitlab(severity: str) -> str:
"""
Map Socket severity levels to GitLab severity levels.
Socket: critical, high, medium/middle, low
GitLab: Critical, High, Medium, Low, Info, Unknown
"""
severity_mapping = {
"critical": "Critical",
"high": "High",
"medium": "Medium",
"middle": "Medium", # Socket's older format
"low": "Low",
}
return severity_mapping.get(severity.lower(), "Unknown")
@staticmethod
def generate_uuid_from_alert_gitlab(alert: Issue) -> str:
"""
Generate deterministic UUID for vulnerability based on alert properties.
This ensures consistent IDs across runs for the same vulnerability.
"""
# Create unique string from alert key properties
unique_str = f"{alert.pkg_name}:{alert.pkg_version}:{alert.type}:{alert.severity}"
# Generate UUID5 (deterministic) from namespace and unique string
namespace = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS namespace
return str(uuid.uuid5(namespace, unique_str))
@staticmethod
def extract_identifiers_gitlab(alert: Issue) -> list:
"""
Extract CVE and other identifiers from alert properties.
Socket stores CVE info in alert.props dict.
Returns array of identifier objects per GitLab schema.
"""
identifiers = []
# Primary identifier: Socket alert type
identifiers.append({
"type": "socket_alert",
"name": f"Socket {alert.type}",
"value": alert.type,
"url": alert.url if hasattr(alert, 'url') and alert.url else None
})
# Extract CVE identifiers from props
if hasattr(alert, 'props') and alert.props:
if 'cve' in alert.props:
cves = alert.props['cve']
if isinstance(cves, list):
for cve in cves:
identifiers.append({
"type": "cve",
"name": cve,
"value": cve,
"url": f"https://cve.mitre.org/cgi-bin/cvename.cgi?name={cve}"
})
elif isinstance(cves, str):
identifiers.append({
"type": "cve",
"name": cves,
"value": cves,
"url": f"https://cve.mitre.org/cgi-bin/cvename.cgi?name={cves}"
})
return identifiers
@staticmethod
def extract_location_gitlab(alert: Issue) -> dict:
"""
Extract location information for GitLab report.
GitLab location requires:
- file: path to manifest file
- dependency: package name and version
- dependency_path (optional): dependency chain
"""
# Get manifest file from introduced_by or manifests attribute
manifest_file = "unknown"
dependency_path = []
is_direct = True
if hasattr(alert, 'introduced_by') and alert.introduced_by:
if isinstance(alert.introduced_by, list) and len(alert.introduced_by) > 0:
first_entry = alert.introduced_by[0]
if isinstance(first_entry, (list, tuple)) and len(first_entry) >= 2:
dependency_path_str = first_entry[0]
manifest_file = first_entry[1].split(';')[0] if ';' in first_entry[1] else first_entry[1]
# Parse dependency path
if ' > ' in dependency_path_str:
dependency_path = dependency_path_str.split(' > ')
# If there's a chain, it's transitive (not direct)
is_direct = len(dependency_path) <= 1
elif hasattr(alert, 'manifests') and alert.manifests:
manifest_file = alert.manifests.split(';')[0]
location = {
"file": manifest_file,
"dependency": {
"package": {
"name": alert.pkg_name
},
"version": alert.pkg_version,
"direct": is_direct
}
}
return location
@staticmethod
def create_security_comment_gitlab(diff: Diff) -> dict:
"""
Create GitLab Dependency Scanning report format from Socket scan results.
Spec: https://docs.gitlab.com/ee/development/integrations/secure.html
Schema: https://gitlab.com/gitlab-org/security-products/security-report-schemas
Args:
diff: Diff report containing new_alerts and package information
Returns:
Dictionary compliant with GitLab Dependency Scanning schema
"""
from socketsecurity import __version__
gitlab_report = {
"version": "15.0.0", # GitLab schema version
"scan": {
"analyzer": {
"id": "socket-security",
"name": "Socket Security",
"version": __version__,
"vendor": {
"name": "Socket"
}
},
"scanner": {
"id": "socket-cli",
"name": "Socket CLI",
"version": __version__,
"vendor": {
"name": "Socket"
}
},
"type": "dependency_scanning",
"start_time": datetime.utcnow().isoformat() + "Z",
"end_time": datetime.utcnow().isoformat() + "Z",
"status": "success"
},
"vulnerabilities": []
}
# Process each alert
for alert in diff.new_alerts:
vulnerability = {
"id": Messages.generate_uuid_from_alert_gitlab(alert),
"category": "dependency_scanning",
"name": alert.title if hasattr(alert, 'title') else f"{alert.type} in {alert.pkg_name}",
"message": f"{alert.pkg_name}@{alert.pkg_version}: {alert.title if hasattr(alert, 'title') else alert.type}",
"description": alert.description if hasattr(alert, 'description') and alert.description else "",
"severity": Messages.map_socket_severity_to_gitlab(alert.severity),
"identifiers": Messages.extract_identifiers_gitlab(alert),
"links": [{"url": alert.url}] if hasattr(alert, 'url') and alert.url else [],
"location": Messages.extract_location_gitlab(alert)
}
# Add solution if available
if hasattr(alert, 'suggestion') and alert.suggestion:
vulnerability["solution"] = alert.suggestion
gitlab_report["vulnerabilities"].append(vulnerability)
return gitlab_report
@staticmethod
def security_comment_template(diff: Diff, config=None) -> str:
"""
Generates the security comment template in the new required format.
Dynamically determines placement of the alerts table if markers like `<!-- start-socket-alerts-table -->` are used.
:param diff: Diff - Contains the detected vulnerabilities and warnings.
:param config: Optional configuration object to determine SCM type.
:return: str - The formatted Markdown/HTML string.
"""
# Group license policy violations by PURL (ecosystem/package@version)
license_groups = {}
security_alerts = []
for alert in diff.new_alerts:
if alert.type == "licenseSpdxDisj":
purl_key = f"{alert.pkg_type}/{alert.pkg_name}@{alert.pkg_version}"
if purl_key not in license_groups:
license_groups[purl_key] = []
license_groups[purl_key].append(alert)
else:
security_alerts.append(alert)
# Start of the comment
comment = """<!-- socket-security-comment-actions -->
> **❗️ Caution**
> **Review the following alerts detected in dependencies.**
>
> According to your organization's policies, you **must** resolve all **"Block"** alerts before proceeding. It's recommended to resolve **"Warn"** alerts too.
> Learn more about [Socket for GitHub](https://socket.dev?utm_medium=gh).
<!-- start-socket-updated-alerts-table -->
<table>
<thead>
<tr>
<th>Action</th>
<th>Severity</th>
<th align="left">Alert (click for details)</th>
</tr>
</thead>
<tbody>
"""
# Loop through security alerts (non-license), dynamically generating rows
for alert in security_alerts:
severity_icon = Messages.get_severity_icon(alert.severity)
action = "Block" if alert.error else "Warn"
details_open = ""
# Generate proper manifest URL
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
# Generate a table row for each alert
comment += f"""
<!-- start-socket-alert-{alert.pkg_name}@{alert.pkg_version} -->
<tr>
<td><strong>{action}</strong></td>
<td align="center">
<img src="{severity_icon}" alt="{alert.severity}" width="20" height="20">
</td>
<td>
<details {details_open}>
<summary>{alert.pkg_name}@{alert.pkg_version} - {alert.title}</summary>
<p><strong>Note:</strong> {alert.description}</p>
<p><strong>Source:</strong> <a href="{manifest_url}">Manifest File</a></p>
<p>ℹ️ Read more on:
<a href="{alert.purl}">This package</a> |
<a href="{alert.url}">This alert</a> |
<a href="https://socket.dev/alerts/malware">What is known malware?</a></p>
<blockquote>
<p><em>Suggestion:</em> {alert.suggestion}</p>
<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>
<code>@SocketSecurity ignore {alert.pkg_name}@{alert.pkg_version}</code><br/>
Or ignore all future alerts with:<br/>
<code>@SocketSecurity ignore-all</code></p>
</blockquote>
</details>
</td>
</tr>
<!-- end-socket-alert-{alert.pkg_name}@{alert.pkg_version} -->
"""
# Add license policy violation entries grouped by PURL
for purl_key, alerts in license_groups.items():
action = "Block" if any(alert.error for alert in alerts) else "Warn"
first_alert = alerts[0]
# Use orange diamond for license policy violations
license_icon = "🔶"
# Build license findings list
license_findings = []
for alert in alerts:
license_findings.append(alert.title)
comment += f"""
<!-- start-socket-alert-{first_alert.pkg_name}@{first_alert.pkg_version} -->
<tr>
<td><strong>{action}</strong></td>
<td align="center">{license_icon}</td>
<td>
<details>
<summary>{first_alert.pkg_name}@{first_alert.pkg_version} has a License Policy Violation.</summary>
<p><strong>License findings:</strong></p>
<ul>
"""
for finding in license_findings:
comment += f" <li>{finding}</li>\n"
# Generate proper manifest URL for license violations
license_manifest_url = Messages.get_manifest_file_url(diff, first_alert.manifests, config)
comment += f""" </ul>
<p><strong>From:</strong> <a href="{license_manifest_url}">Manifest File</a></p>
<p>ℹ️ Read more on: <a href="{first_alert.purl}">This package</a> | <a href="https://socket.dev/alerts/license">What is a license policy violation?</a></p>
<blockquote>
<p><em>Next steps:</em> Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at <strong>support@socket.dev</strong>.</p>
<p><em>Suggestion:</em> Find a package that does not violate your license policy or adjust your policy to allow this package's license.</p>
<p><em>Mark the package as acceptable risk:</em> To ignore this alert only in this pull request, reply with the comment <code>@SocketSecurity ignore {first_alert.pkg_name}@{first_alert.pkg_version}</code>. You can also ignore all packages with <code>@SocketSecurity ignore-all</code>. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.</p>
</blockquote>
</details>
</td>
</tr>
<!-- end-socket-alert-{first_alert.pkg_name}@{first_alert.pkg_version} -->
"""
# Close table
# Use diff_url for PRs, report_url for non-PR scans
view_report_url = ""
if hasattr(diff, 'diff_url') and diff.diff_url:
view_report_url = diff.diff_url
elif hasattr(diff, 'report_url') and diff.report_url:
view_report_url = diff.report_url
comment += f"""
</tbody>
</table>
<!-- end-socket-alerts-table -->
[View full report]({view_report_url}?action=error%2Cwarn)
"""
return comment
@staticmethod
def get_severity_icon(severity: str) -> str:
"""
Maps severity levels to their corresponding badge/icon URLs.
:param severity: str - Severity level (e.g., "Critical", "High").
:return: str - Badge/icon URL.
"""
severity_map = {
"critical": "https://github-app-statics.socket.dev/severity-3.svg",
"high": "https://github-app-statics.socket.dev/severity-2.svg",
"medium": "https://github-app-statics.socket.dev/severity-1.svg",
"low": "https://github-app-statics.socket.dev/severity-0.svg",
}
return severity_map.get(severity.lower(), "https://github-app-statics.socket.dev/severity-0.svg")
@staticmethod
def create_next_steps(md: MdUtils, next_steps: dict):
"""
Creates the next steps section of the security comment template
:param md: MdUtils - Main markdown variable
:param next_steps: Dict - Contains the detected next steps to include
:return:
"""
for step in next_steps:
detail = next_steps[step]
md.new_line("<details>")
md.new_line(f"<summary>{step}</summary>")
for line in detail:
md.new_paragraph(line)
md.new_line("</details>")
return md
@staticmethod
def create_deeper_look(md: MdUtils) -> MdUtils:
"""
Creates the deeper look section for the Security Comment Template
:param md: MdUtils - Main markdown variable
:return:
"""
md.new_line("<details>")
md.new_line("<summary>Take a deeper look at the dependency</summary>")
md.new_paragraph(
"Take a moment to review the security alert above. Review the linked package source code to understand the "
"potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, "
"reach out to your security team or ask the Socket team for help at support [AT] socket [DOT] dev."
)
md.new_line("</details>")
return md
@staticmethod
def create_remove_package(md: MdUtils) -> MdUtils:
"""
Creates the remove packages suggestion section for the Security Comment Template
:param md:
:return:
"""
md.new_line("<details>")
md.new_line("<summary>Remove the package</summary>")
md.new_paragraph(
"If you happen to install a dependency that Socket reports as "
"[https://socket.dev/npm/issue/malware](Known Malware) you should immediately remove it and select a "
"different dependency. For other alert types, you may may wish to investigate alternative packages or "
"consider if there are other ways to mitigate the specific risk posed by the dependency."
)
md.new_line("</details>")
return md
@staticmethod
def create_acceptable_risk(md: MdUtils, ignore_commands: list) -> MdUtils:
"""
Creates the comment on how to accept risk for the Security Comment Template
:param md: MdUtils - Main markdown variable
:param ignore_commands: List of detected ignore commands based on the alerts associated purls
:return:
"""
md.new_line("<details>")
md.new_line("<summary>Mark a package as acceptable risk</summary>")
md.new_paragraph(
"To ignore an alert, reply with a comment starting with `SocketSecurity ignore` followed by a space "
"separated list of `ecosystem/package-name@version` specifiers. e.g. `SocketSecurity ignore npm/foo@1.0.0`"