-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconfig.py
More file actions
1951 lines (1623 loc) · 84.7 KB
/
config.py
File metadata and controls
1951 lines (1623 loc) · 84.7 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
#!/usr/bin/env python3
"""
Configuration management for Socket Security Basics
Handles CLI arguments, environment variables, and provides a unified config object
"""
import argparse
import json
import os
import yaml
import logging
from pathlib import Path
from typing import Dict, Any, List, Optional
logger = logging.getLogger(__name__)
class Config:
"""Configuration object that provides unified access to all settings"""
def __init__(self, config_dict: Dict[str, Any] | None = None, json_config_path: str | None = None):
"""Initialize configuration from dictionary, JSON file, or environment
Args:
config_dict: Optional configuration dictionary (takes precedence)
json_config_path: Optional path to JSON configuration file
"""
if config_dict is not None:
# Use provided config dictionary directly
self._config = config_dict
elif json_config_path is not None:
# Load from JSON file and merge with environment
try:
json_config = load_config_from_json(json_config_path)
self._config = merge_json_and_env_config(json_config)
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
logger = logging.getLogger(__name__)
logger.error("Failed to load JSON config from %s: %s", json_config_path, e)
# Fall back to merged config (includes Socket Basics API config)
self._config = merge_json_and_env_config()
else:
# Default: merge environment config with Socket Basics API config
self._config = merge_json_and_env_config()
self._config = self._config
# Log where the configuration is being loaded from
logger = logging.getLogger(__name__)
config_source = self._config.get('_config_source', 'environment')
source_descriptions = {
'api': 'Socket dashboard (API)',
'json_file': 'JSON config file (--config)',
'environment': 'environment variables',
}
source_desc = source_descriptions.get(config_source, config_source)
logger.info(f"Configuration loaded from: {source_desc}")
# DEBUG: Log final configuration values
logger.debug("Final Config object created with key values:")
logger.debug(f" javascript_sast_enabled: {self._config.get('javascript_sast_enabled')}")
logger.debug(f" socket_tier_1_enabled: {self._config.get('socket_tier_1_enabled')}")
logger.debug(f" console_tabular_enabled: {self._config.get('console_tabular_enabled')}")
logger.debug(f" socket_org: {self._config.get('socket_org')}")
logger.debug(f" socket_api_key set: {bool(self._config.get('socket_api_key'))}")
# Validate workspace path: warn and fall back to cwd when missing
ws = Path(self._config.get('workspace', os.getcwd()))
if not ws.exists():
logging.getLogger(__name__).warning("Configured workspace does not exist: %s; falling back to current working directory", str(ws))
ws = Path(os.getcwd())
self.workspace = ws
self.output_dir = Path(self._config.get('output_dir', self.workspace))
self.scan_files = self._parse_scan_files(self._config.get('scan_files', ''))
def get(self, key: str, default=None):
"""Get configuration value"""
return self._config.get(key, default)
def set(self, key: str, value: Any):
"""Set configuration value"""
self._config[key] = value
def _parse_scan_files(self, scan_files_str: str) -> List[str]:
"""Parse comma-separated scan files into a list"""
if not scan_files_str.strip():
return []
return [f.strip() for f in scan_files_str.split(',') if f.strip()]
def get_scan_targets(self) -> List[str]:
"""Determine files to scan based on configuration"""
# If explicit 'scan_all' set, return workspace directory
if self.get('scan_all', False):
return [str(self.workspace)]
# If user provided specific files to scan, validate their existence
if self.scan_files:
targets = [self.workspace / f for f in self.scan_files]
valid = []
for t in targets:
if t.exists():
valid.append(str(t))
else:
logging.getLogger(__name__).warning("Scan target does not exist: %s", str(t))
return valid
# Default: scan the workspace itself
return [str(self.workspace)]
def get_action_for_severity(self, severity: str) -> str:
"""Map severity to action according to security policy"""
# Normalize severity to lowercase for consistent mapping
severity_lower = severity.lower()
# Security policy mapping
if severity_lower == 'critical':
return 'error'
elif severity_lower == 'high':
return 'warn'
elif severity_lower in ['medium', 'middle', 'moderate']:
return 'monitor'
elif severity_lower == 'low':
return 'ignore'
else:
# Default action for unknown severities
return 'monitor'
@property
def repo(self) -> str:
"""Get repository name"""
return str(self.get('repo', ''))
@property
def branch(self) -> str:
"""Get branch name"""
return str(self.get('branch', ''))
@property
def commit_hash(self) -> str:
"""Get commit hash (optional)"""
return str(self.get('commit_hash', ''))
@property
def is_default_branch(self) -> bool:
"""Check if current branch is the default branch"""
return bool(self.get('is_default_branch', False))
def is_notifier_available(self, notifier: str) -> bool:
"""Check if a notifier is available based on Socket plan"""
available_notifiers = self.get('available_notifiers', ['console_tabular', 'console_json'])
if not isinstance(available_notifiers, list):
available_notifiers = ['console_tabular', 'console_json']
return notifier in available_notifiers
def get_socket_plan_info(self) -> Dict[str, Any]:
"""Get Socket plan information"""
return {
'plan': self.get('socket_plan', 'free'),
'has_enterprise': self.get('socket_has_enterprise', False),
'available_notifiers': self.get('available_notifiers', ['console_tabular', 'console_json'])
}
def should_run_sast(self) -> bool:
"""Check if any SAST language is enabled dynamically"""
try:
# Get SAST parameters dynamically from connectors config
connectors_config = load_connectors_config()
opengrep_config = connectors_config.get('connectors', {}).get('opengrep', {})
for param in opengrep_config.get('parameters', []):
param_name = param.get('name', '')
if 'sast_enabled' in param_name and self.get(param_name, False):
return True
return False
except Exception:
# Fallback to hardcoded check if YAML loading fails
sast_langs = [
'python_sast_enabled', 'golang_sast_enabled', 'javascript_sast_enabled',
'typescript_sast_enabled', 'java_sast_enabled', 'ruby_sast_enabled',
'dotnet_sast_enabled', 'scala_sast_enabled', 'kotlin_sast_enabled',
'rust_sast_enabled', 'c_sast_enabled', 'cpp_sast_enabled',
'php_sast_enabled', 'swift_sast_enabled', 'elixir_sast_enabled',
'erlang_sast_enabled', 'csharp_sast_enabled'
]
return any(self.get(lang, False) for lang in sast_langs)
def build_opengrep_rules(self) -> List[str]:
"""Build list of rule files based on enabled languages"""
# Explicit mapping from connector boolean flags to bundled rule filenames.
# Exclude languages for which we don't ship rule files (objective-c, erlang).
language_rules = {
'python_sast_enabled': 'python.yml',
'go_sast_enabled': 'go.yml',
'golang_sast_enabled': 'go.yml',
'javascript_sast_enabled': 'javascript_typescript.yml',
'typescript_sast_enabled': 'javascript_typescript.yml',
'java_sast_enabled': 'java.yml',
'ruby_sast_enabled': 'ruby.yml',
'csharp_sast_enabled': 'dotnet.yml',
'dotnet_sast_enabled': 'dotnet.yml',
'scala_sast_enabled': 'scala.yml',
'kotlin_sast_enabled': 'kotlin.yml',
'rust_sast_enabled': 'rust.yml',
'c_sast_enabled': 'c_cpp.yml',
'cpp_sast_enabled': 'c_cpp.yml',
'php_sast_enabled': 'php.yml',
'swift_sast_enabled': 'swift.yml',
'elixir_sast_enabled': 'elixir.yml'
}
# If user has requested 'all rules', run the full rule files for the languages
# that are enabled. If no specific languages are enabled but --all-languages is
# set, fall back to all bundled rule files. If neither is set, return empty
# to allow upstream logic to skip scanning.
if self.get('all_rules_enabled', False):
rule_files = []
for flag, filename in language_rules.items():
if self.get(flag, False):
if filename not in rule_files:
rule_files.append(filename)
# If no specific language flags were enabled, but user set --all-languages,
# return all bundled rules.
if not rule_files:
if self.get('all_languages_enabled', False):
try:
base_dir = Path(__file__).parent.parent
rules_dir = base_dir / 'rules'
found = [p.name for p in rules_dir.glob('*.yml') if p.is_file()]
excluded = {'objective-c.yml', 'erlang.yml'}
return [f for f in found if f not in excluded]
except Exception:
return list({v for v in language_rules.values()})
# No languages enabled -> nothing to run
return []
return rule_files
rule_files = []
for flag, filename in language_rules.items():
if self.get(flag, False):
if filename not in rule_files:
rule_files.append(filename)
return rule_files
def get_enabled_rules_for_language(self, language: str) -> List[str]:
"""Get list of enabled rules for a specific language"""
rules_param = f"{language}_enabled_rules"
rules_str = self.get(rules_param, "")
if not rules_str or not rules_str.strip():
return []
return [rule.strip() for rule in rules_str.split(',') if rule.strip()]
def build_filtered_opengrep_rules(self) -> Dict[str, List[str]]:
"""Build mapping of rule files to specific rules that should be enabled"""
# Map connector flags to (rule filename, parameter name) so we can
# look up the user-specified enabled rules for that language.
language_rule_mapping = {
'python_sast_enabled': ('python.yml', 'python_enabled_rules'),
'go_sast_enabled': ('go.yml', 'go_enabled_rules'),
'golang_sast_enabled': ('go.yml', 'go_enabled_rules'),
'javascript_sast_enabled': ('javascript_typescript.yml', 'javascript_enabled_rules'),
'typescript_sast_enabled': ('javascript_typescript.yml', 'javascript_enabled_rules'),
'java_sast_enabled': ('java.yml', 'java_enabled_rules'),
'ruby_sast_enabled': ('ruby.yml', 'ruby_enabled_rules'),
'csharp_sast_enabled': ('dotnet.yml', 'csharp_enabled_rules'),
'dotnet_sast_enabled': ('dotnet.yml', 'dotnet_enabled_rules'),
'scala_sast_enabled': ('scala.yml', 'scala_enabled_rules'),
'kotlin_sast_enabled': ('kotlin.yml', 'kotlin_enabled_rules'),
'rust_sast_enabled': ('rust.yml', 'rust_enabled_rules'),
'c_sast_enabled': ('c_cpp.yml', 'c_enabled_rules'),
'cpp_sast_enabled': ('c_cpp.yml', 'cpp_enabled_rules'),
'php_sast_enabled': ('php.yml', 'php_enabled_rules'),
'swift_sast_enabled': ('swift.yml', 'swift_enabled_rules'),
'elixir_sast_enabled': ('elixir.yml', 'elixir_enabled_rules')
}
rule_file_filters: Dict[str, set] = {}
for flag, (rule_file, rules_param) in language_rule_mapping.items():
if not self.get(flag, False):
continue
# rules_param is the exact parameter name defined in connectors.yaml
enabled_rules = self.get(rules_param, "")
if not enabled_rules:
continue
for r in [s.strip() for s in enabled_rules.split(',') if s.strip()]:
if rule_file not in rule_file_filters:
rule_file_filters[rule_file] = set()
rule_file_filters[rule_file].add(r)
# Convert sets to lists for output
return {k: list(v) for k, v in rule_file_filters.items()}
def get_custom_rules_path(self) -> Optional[Path]:
"""Get the absolute path to custom SAST rules directory.
Returns path relative to workspace if workspace is set, otherwise relative to cwd.
Returns None if custom rules are not enabled or path doesn't exist.
"""
# Cache the result to avoid repeated warnings and path resolution
if hasattr(self, '_custom_rules_path_cache'):
return self._custom_rules_path_cache
if not self.get('use_custom_sast_rules', False):
self._custom_rules_path_cache = None
return None
custom_path_str = self.get('custom_sast_rule_path', 'custom_rules')
if not custom_path_str:
self._custom_rules_path_cache = None
return None
# Determine base path
try:
if hasattr(self, 'workspace') and self.workspace:
base_path = Path(self.workspace)
else:
base_path = Path.cwd()
except Exception:
base_path = Path.cwd()
# Resolve custom rules path
custom_path = base_path / custom_path_str
# Check if path exists
if not custom_path.exists():
logger.debug(f"Custom SAST rules path does not exist: {custom_path}")
self._custom_rules_path_cache = None
return None
if not custom_path.is_dir():
logger.warning(f"Custom SAST rules path is not a directory: {custom_path}")
self._custom_rules_path_cache = None
return None
self._custom_rules_path_cache = custom_path
return custom_path
# Centralized environment variable getters
# All connectors and notifiers should use these methods instead of calling os.getenv directly
def get_env_with_fallbacks(*env_vars: str, default: str = '') -> str:
"""Get environment variable value with multiple fallback options.
Args:
*env_vars: Variable number of environment variable names to check (in priority order)
default: Default value if none of the env vars are set
Returns:
First non-empty environment variable value found, or default
"""
for env_var in env_vars:
value = os.getenv(env_var)
if value:
return value
return default
def get_github_token() -> str:
"""Get GitHub token from environment variables."""
return get_env_with_fallbacks('GITHUB_TOKEN', 'INPUT_GITHUB_TOKEN')
def get_github_repository() -> str:
"""Get GitHub repository from environment variables."""
return get_env_with_fallbacks('GITHUB_REPOSITORY', 'INPUT_GITHUB_REPOSITORY')
def get_github_pr_number() -> str:
"""Get GitHub PR number from environment variables."""
return get_env_with_fallbacks('GITHUB_PR_NUMBER', 'INPUT_PR_NUMBER')
def get_slack_webhook_url() -> str:
"""Get Slack webhook URL from environment variables."""
return get_env_with_fallbacks('SLACK_WEBHOOK_URL', 'INPUT_SLACK_WEBHOOK_URL')
def get_webhook_url() -> str:
"""Get generic webhook URL from environment variables."""
return get_env_with_fallbacks('WEBHOOK_URL', 'INPUT_WEBHOOK_URL')
def get_ms_sentinel_workspace_id() -> str:
"""Get Microsoft Sentinel workspace ID from environment variables."""
return get_env_with_fallbacks('MS_SENTINEL_WORKSPACE_ID', 'INPUT_MS_SENTINEL_WORKSPACE_ID')
def get_ms_sentinel_shared_key() -> str:
"""Get Microsoft Sentinel shared key from environment variables."""
return get_env_with_fallbacks('MS_SENTINEL_SHARED_KEY', 'INPUT_MS_SENTINEL_SHARED_KEY')
def get_ms_sentinel_collector_url() -> str:
"""Get Microsoft Sentinel collector URL from environment variables."""
return get_env_with_fallbacks('MS_SENTINEL_COLLECTOR_URL', 'INPUT_MS_SENTINEL_COLLECTOR_URL')
def get_jira_url() -> str:
"""Get JIRA URL from environment variables."""
return get_env_with_fallbacks('JIRA_URL', 'INPUT_JIRA_URL')
def get_jira_project() -> str:
"""Get JIRA project from environment variables."""
return get_env_with_fallbacks('JIRA_PROJECT', 'INPUT_JIRA_PROJECT')
def get_jira_email() -> str:
"""Get JIRA email from environment variables."""
return get_env_with_fallbacks('JIRA_EMAIL', 'INPUT_JIRA_EMAIL')
def get_jira_api_token() -> str:
"""Get JIRA API token from environment variables."""
return get_env_with_fallbacks('JIRA_API_TOKEN', 'INPUT_JIRA_API_TOKEN')
def get_sumologic_http_source_url() -> str:
"""Get SumoLogic HTTP source URL from environment variables."""
return get_env_with_fallbacks('SUMO_LOGIC_HTTP_SOURCE_URL', 'INPUT_SUMO_LOGIC_HTTP_SOURCE_URL')
def get_sumologic_endpoint() -> str:
"""Get SumoLogic endpoint from environment variables."""
return get_env_with_fallbacks('SUMOLOGIC_ENDPOINT', 'INPUT_SUMOLOGIC_ENDPOINT')
def get_msteams_webhook_url() -> str:
"""Get Microsoft Teams webhook URL from environment variables."""
return get_env_with_fallbacks('MSTEAMS_WEBHOOK_URL', 'INPUT_MSTEAMS_WEBHOOK_URL')
def get_socket_basics_severities() -> str:
"""Get Socket Basics severities from environment variables."""
return get_env_with_fallbacks('SOCKET_BASICS_SEVERITIES', 'INPUT_FINDING_SEVERITIES')
def get_github_workspace() -> str:
"""Get GitHub workspace from environment variables."""
return get_env_with_fallbacks('GITHUB_WORKSPACE', default=os.getcwd())
def load_config_from_json(json_path: str) -> Dict[str, Any]:
"""Load configuration from a JSON file
Args:
json_path: Path to the JSON configuration file
Returns:
Dictionary containing the configuration from the JSON file
Raises:
FileNotFoundError: If the JSON file doesn't exist
json.JSONDecodeError: If the JSON file is malformed
"""
try:
with open(json_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# Validate that the loaded config is a dictionary
if not isinstance(config, dict):
raise ValueError(f"JSON config file must contain a JSON object, got {type(config).__name__}")
logger = logging.getLogger(__name__)
logger.info("Successfully loaded configuration from JSON file: %s", json_path)
return config
except FileNotFoundError:
raise FileNotFoundError(f"JSON configuration file not found: {json_path}")
except json.JSONDecodeError as e:
raise json.JSONDecodeError(f"Invalid JSON in configuration file {json_path}: {e.msg}", e.doc, e.pos)
def load_config_from_env() -> Dict[str, Any]:
"""Load configuration from environment variables dynamically from connectors.yaml"""
config = {
# Core workspace settings
'workspace': os.getenv('GITHUB_WORKSPACE', os.getcwd()),
'output_dir': os.getenv('OUTPUT_DIR', os.getcwd()),
# Scan scope
'scan_all': os.getenv('INPUT_SCAN_ALL', 'false').lower() == 'true',
'scan_files': os.getenv('INPUT_SCAN_FILES', ''),
# Core Socket API configuration (top-level, like workspace)
'socket_org': (
os.getenv('SOCKET_ORG', '') or
os.getenv('SOCKET_ORG_SLUG', '') or
os.getenv('INPUT_SOCKET_ORG', '')
),
'socket_api_key': (
os.getenv('SOCKET_SECURITY_API_KEY', '') or
os.getenv('SOCKET_SECURITY_API_TOKEN', '') or
os.getenv('SOCKET_API_KEY', '') or
os.getenv('INPUT_SOCKET_SECURITY_API_KEY', '') or
os.getenv('INPUT_SOCKET_API_KEY', '')
),
# Socket plan detection (will be populated later in merge process)
'socket_plan': '',
'socket_has_enterprise': False,
'available_notifiers': ['console_tabular', 'console_json'], # Default free plan notifiers
# OpenGrep configuration (optional override for custom rules)
'opengrep_rules_dir': os.getenv('INPUT_OPENGREP_RULES_DIR', ''),
# GitHub environment variables for discovery functions
'github_actor': os.getenv('GITHUB_ACTOR', ''),
'github_pr_number': os.getenv('GITHUB_PR_NUMBER', ''),
'github_head_ref': os.getenv('GITHUB_HEAD_REF', ''),
'github_event_path': os.getenv('GITHUB_EVENT_PATH', ''),
'github_sha': os.getenv('GITHUB_SHA', ''),
'github_repository': os.getenv('GITHUB_REPOSITORY', ''),
'github_ref_name': os.getenv('GITHUB_REF_NAME', ''),
}
# Dynamically load connector parameters from YAML configuration
try:
connectors_config = load_connectors_config()
for connector_name, connector_config in connectors_config.get('connectors', {}).items():
for param in connector_config.get('parameters', []):
param_name = param.get('name')
env_variable = param.get('env_variable')
param_type = param.get('type', 'str')
default_value = param.get('default', False if param_type == 'bool' else '')
if param_name and env_variable:
env_value = os.getenv(env_variable)
if env_value is not None:
if param_type == 'bool':
val = env_value.lower() == 'true'
config[param_name] = val
# honor 'enables' and 'disables' metadata from connectors.yaml
try:
if val and 'enables' in param:
for enabled in param.get('enables', []):
config[enabled] = True
if val and 'disables' in param:
for disabled in param.get('disables', []):
config[disabled] = False
# if the boolean flag is false but a default was provided,
# do not automatically flip related params; explicit true flags
# drive enable/disable propagation.
except Exception:
pass
elif param_type == 'int':
try:
config[param_name] = int(env_value)
except ValueError:
config[param_name] = default_value
else: # str type
config[param_name] = env_value
else:
# Use default value if environment variable is not set
config[param_name] = default_value
except Exception as e:
logging.getLogger(__name__).warning("Warning: Error loading dynamic config from environment: %s", e)
# Also load notification parameters from notifications.yaml so CLI/env can enable them
try:
base_dir = Path(__file__).parent.parent
notif_path = base_dir / 'notifications.yaml'
if notif_path.exists():
with open(notif_path, 'r') as f:
notif_cfg = yaml.safe_load(f) or {}
for n_name, n_cfg in (notif_cfg.get('notifiers') or {}).items():
for param in n_cfg.get('parameters', []) or []:
p_name = param.get('name')
env_var = param.get('env_variable')
p_type = param.get('type', 'str')
default_value = param.get('default', '' if p_type != 'bool' else False)
if p_name and env_var:
env_value = os.getenv(env_var)
if env_value is not None:
if p_type == 'bool':
config[p_name] = env_value.lower() == 'true'
elif p_type == 'int':
try:
config[p_name] = int(env_value)
except ValueError:
logging.getLogger(__name__).warning(
"Invalid integer for %s (env %s): %s; using default %s",
p_name, env_var, env_value, default_value
)
config[p_name] = default_value
else:
config[p_name] = env_value
else:
config[p_name] = default_value
except Exception:
# Best-effort; do not fail on notification parsing
pass
# Auto-enable scanning when values are provided (removes need for separate enabled flags)
# If container_images has a value, enable image scanning
if config.get('container_images'):
config['trivy_image_enabled'] = True
config['container_image_scanning_enabled'] = True
# If dockerfiles has a value, enable Dockerfile scanning
if config.get('dockerfiles'):
config['trivy_dockerfile_enabled'] = True
config['dockerfile_scanning_enabled'] = True
return config
def load_socket_basics_config() -> Dict[str, Any] | None:
"""Load Socket Basics configuration from Socket API if organization has enterprise plan
Returns:
Socket Basics configuration dictionary if available, None otherwise
"""
logger = logging.getLogger(__name__)
logger.debug(" load_socket_basics_config() called")
# Check if Socket API integration is available
# Support both direct env vars and GitHub Actions INPUT_ prefixed vars
api_key = (
os.environ.get('SOCKET_SECURITY_API_KEY')
or os.environ.get('SOCKET_SECURITY_API_TOKEN')
or os.environ.get('INPUT_SOCKET_SECURITY_API_KEY')
)
logger.debug(f" API key check - SOCKET_SECURITY_API_KEY set: {bool(os.environ.get('SOCKET_SECURITY_API_KEY'))}")
logger.debug(f" API key check - SOCKET_SECURITY_API_TOKEN set: {bool(os.environ.get('SOCKET_SECURITY_API_TOKEN'))}")
logger.debug(f" API key check - INPUT_SOCKET_SECURITY_API_KEY set: {bool(os.environ.get('INPUT_SOCKET_SECURITY_API_KEY'))}")
logger.debug(f" Final api_key available: {bool(api_key)}")
if not api_key:
logger.info("Socket API key not detected - running in free plan mode (limited features)")
logger.debug("Checked: SOCKET_SECURITY_API_KEY, SOCKET_SECURITY_API_TOKEN, INPUT_SOCKET_SECURITY_API_KEY")
return {
'socket_plan': 'free',
'socket_has_enterprise': False,
'available_notifiers': ['console_tabular', 'console_json']
}
logger.info("Socket API key detected - attempting to load dashboard configuration")
# Support both direct env vars and GitHub Actions INPUT_ prefixed vars
org_slug = (
os.environ.get('SOCKET_ORG_SLUG')
or os.environ.get('SOCKET_ORG')
or os.environ.get('INPUT_SOCKET_ORG')
)
logger.debug(f" SOCKET_ORG_SLUG: {os.environ.get('SOCKET_ORG_SLUG', 'not set')}")
logger.debug(f" SOCKET_ORG: {os.environ.get('SOCKET_ORG', 'not set')}")
logger.debug(f" INPUT_SOCKET_ORG: {os.environ.get('INPUT_SOCKET_ORG', 'not set')}")
logger.debug(f" org_slug from env: {org_slug or 'not set - will auto-discover'}")
try:
# Import socketdev here to avoid import errors if not installed
from socketdev import socketdev
# Initialize SDK
sdk = socketdev(token=api_key, timeout=100)
# Get organizations and find the right one or auto-discover
orgs = sdk.org.get()
target_org = None
logger.debug(f" Found {len(orgs.get('organizations', {}))} organizations in API response")
if len(orgs) > 0:
if org_slug:
# Look for specific organization
logger.debug(f" Looking for specific organization: {org_slug}")
for org_key in orgs['organizations']:
org = orgs['organizations'][org_key]
if org.get('slug') == org_slug:
target_org = org
logger.info(f"Found organization '{org_slug}' with plan: {org.get('plan', '')}")
break
else:
# Auto-discover first organization
logger.debug(" Auto-discovering organization (no SOCKET_ORG set)")
for org_key in orgs['organizations']:
org = orgs['organizations'][org_key]
target_org = org
org_slug = org['slug']
logger.info(f"Auto-discovered organization '{org_slug}' with plan: {org.get('plan', '')}")
break
if not target_org or not org_slug:
logger.warning("No suitable organization found in API response")
return None
# Check if organization has enterprise plan
plan = target_org.get('plan', '')
has_enterprise = plan.startswith('enterprise')
# Always return plan information, even for non-enterprise plans
base_plan_config = {
'socket_plan': plan,
'socket_has_enterprise': has_enterprise,
'socket_org': org_slug, # Populate discovered org
'available_notifiers': ['console_tabular', 'console_json'] if not has_enterprise else [
'console_tabular', 'console_json', 'slack', 'ms_teams', 'jira',
'webhook', 'sumologic', 'ms_sentinel', 'github_pr', 'json_notifier'
]
}
if not has_enterprise:
logger.info(f"Organization '{org_slug}' does not have enterprise plan, returning basic config only")
return base_plan_config
# Get Socket Basics configuration
basics_config_response = sdk.basics.get_config(org_slug=org_slug)
logger.info(f"Retrieved Socket Basics config for enterprise organization '{org_slug}'")
# Convert response to dictionary if needed
basics_config = None
if isinstance(basics_config_response, dict):
basics_config = basics_config_response
elif hasattr(basics_config_response, '__dict__'):
basics_config = basics_config_response.__dict__
elif hasattr(basics_config_response, 'to_dict') and callable(getattr(basics_config_response, 'to_dict')):
basics_config = basics_config_response.to_dict()
else:
# Try to convert to dict using json serialization
try:
basics_config = json.loads(json.dumps(basics_config_response, default=str))
except Exception:
logger.warning("Could not convert Socket Basics config response to dictionary")
return None
# If additionalParameters contains JSON, parse and merge it
if isinstance(basics_config, dict) and basics_config.get('additionalParameters'):
logger.debug(" Found additionalParameters in Socket Basics config")
logger.debug(f" additionalParameters content: {basics_config['additionalParameters']}")
try:
additional_params = json.loads(basics_config['additionalParameters'])
logger.debug(f" Parsed additionalParameters: {json.dumps(additional_params, indent=2)}")
if isinstance(additional_params, dict):
merged_config = {**base_plan_config, **basics_config, **additional_params}
logger.debug(" Merged additionalParameters into Socket Basics config")
logger.debug(f" Final merged config keys: {list(merged_config.keys())}")
logger.debug(f" Key config values - javascript_sast_enabled: {merged_config.get('javascript_sast_enabled')}, socket_tier_1_enabled: {merged_config.get('socket_tier_1_enabled')}, console_tabular_enabled: {merged_config.get('console_tabular_enabled')}")
return merged_config
except json.JSONDecodeError as e:
logger.warning(f"additionalParameters is not valid JSON: {e}, using base config")
logger.debug(f" Raw additionalParameters that failed to parse: {repr(basics_config['additionalParameters'])}")
# Return basic config merged with plan information
return {**base_plan_config, **basics_config} if isinstance(basics_config, dict) else base_plan_config
except ImportError:
logger.debug("socketdev package not installed, skipping Socket Basics config load")
return None
except Exception as e:
logger.warning(f"Error loading Socket Basics config: {e}")
return None
def load_explicit_env_config() -> Dict[str, Any]:
"""Load only explicitly set environment variables (not defaults)"""
logger = logging.getLogger(__name__)
config = {}
# Log which API key sources are available for debugging
api_key_sources = {
'SOCKET_SECURITY_API_KEY': bool(os.environ.get('SOCKET_SECURITY_API_KEY')),
'SOCKET_SECURITY_API_TOKEN': bool(os.environ.get('SOCKET_SECURITY_API_TOKEN')),
'INPUT_SOCKET_SECURITY_API_KEY': bool(os.environ.get('INPUT_SOCKET_SECURITY_API_KEY')),
}
found_sources = [k for k, v in api_key_sources.items() if v]
if found_sources:
logger.debug(f"API key sources detected: {', '.join(found_sources)}")
# Core settings - only if explicitly set
if 'GITHUB_WORKSPACE' in os.environ:
config['workspace'] = os.environ['GITHUB_WORKSPACE']
if 'OUTPUT_DIR' in os.environ:
config['output_dir'] = os.environ['OUTPUT_DIR']
if 'INPUT_SCAN_ALL' in os.environ:
config['scan_all'] = os.environ['INPUT_SCAN_ALL'].lower() == 'true'
if 'INPUT_SCAN_FILES' in os.environ:
config['scan_files'] = os.environ['INPUT_SCAN_FILES']
if 'INPUT_OPENGREP_RULES_DIR' in os.environ:
config['opengrep_rules_dir'] = os.environ['INPUT_OPENGREP_RULES_DIR']
# Dynamically load connector parameters from YAML configuration - only if explicitly set
try:
connectors_config = load_connectors_config()
for connector_name, connector_config in connectors_config.get('connectors', {}).items():
for param in connector_config.get('parameters', []):
param_name = param.get('name')
env_variable = param.get('env_variable')
param_type = param.get('type', 'str')
if param_name and env_variable and env_variable in os.environ:
env_value = os.environ[env_variable]
if param_type == 'bool':
val = env_value.lower() == 'true'
config[param_name] = val
# honor 'enables' and 'disables' metadata from connectors.yaml
try:
if val and 'enables' in param:
for enabled in param.get('enables', []):
config[enabled] = True
if val and 'disables' in param:
for disabled in param.get('disables', []):
config[disabled] = False
except Exception:
pass
elif param_type == 'int':
try:
config[param_name] = int(env_value)
except ValueError:
pass # Skip invalid values
else: # str type
config[param_name] = env_value
except Exception as e:
logging.getLogger(__name__).warning("Warning: Error loading explicit env config: %s", e)
return config
def normalize_api_config(api_config: Dict[str, Any]) -> Dict[str, Any]:
"""Normalize camelCase API keys to snake_case internal format.
Maps Socket Basics API response keys (camelCase) to internal config keys (snake_case).
This allows the API to use camelCase while maintaining snake_case internally.
Args:
api_config: Configuration dictionary from Socket Basics API (camelCase)
Returns:
Normalized configuration dictionary (snake_case)
"""
# Mapping from camelCase API keys to snake_case internal keys
API_TO_INTERNAL_MAP = {
# Console/Output
'consoleTabularEnabled': 'console_tabular_enabled',
'consoleJsonEnabled': 'console_json_enabled',
'verbose': 'verbose',
# SAST Language Flags
'allLanguagesEnabled': 'all_languages_enabled',
'pythonSastEnabled': 'python_sast_enabled',
'javascriptSastEnabled': 'javascript_sast_enabled',
'typescriptSastEnabled': 'typescript_sast_enabled',
'goSastEnabled': 'go_sast_enabled',
'golangSastEnabled': 'golang_sast_enabled',
'javaSastEnabled': 'java_sast_enabled',
'phpSastEnabled': 'php_sast_enabled',
'rubySastEnabled': 'ruby_sast_enabled',
'csharpSastEnabled': 'csharp_sast_enabled',
'dotnetSastEnabled': 'dotnet_sast_enabled',
'cSastEnabled': 'c_sast_enabled',
'cppSastEnabled': 'cpp_sast_enabled',
'kotlinSastEnabled': 'kotlin_sast_enabled',
'scalaSastEnabled': 'scala_sast_enabled',
'swiftSastEnabled': 'swift_sast_enabled',
'rustSastEnabled': 'rust_sast_enabled',
'elixirSastEnabled': 'elixir_sast_enabled',
# SAST Rules Configuration
'allRulesEnabled': 'all_rules_enabled',
'pythonEnabledRules': 'python_enabled_rules',
'pythonDisabledRules': 'python_disabled_rules',
'javascriptEnabledRules': 'javascript_enabled_rules',
'javascriptDisabledRules': 'javascript_disabled_rules',
'goEnabledRules': 'go_enabled_rules',
'goDisabledRules': 'go_disabled_rules',
'javaEnabledRules': 'java_enabled_rules',
'javaDisabledRules': 'java_disabled_rules',
'kotlinEnabledRules': 'kotlin_enabled_rules',
'kotlinDisabledRules': 'kotlin_disabled_rules',
'scalaEnabledRules': 'scala_enabled_rules',
'scalaDisabledRules': 'scala_disabled_rules',
'phpEnabledRules': 'php_enabled_rules',
'phpDisabledRules': 'php_disabled_rules',
'rubyEnabledRules': 'ruby_enabled_rules',
'rubyDisabledRules': 'ruby_disabled_rules',
'csharpEnabledRules': 'csharp_enabled_rules',
'csharpDisabledRules': 'csharp_disabled_rules',
'dotnetEnabledRules': 'dotnet_enabled_rules',
'dotnetDisabledRules': 'dotnet_disabled_rules',
'cEnabledRules': 'c_enabled_rules',
'cDisabledRules': 'c_disabled_rules',
'cppEnabledRules': 'cpp_enabled_rules',
'cppDisabledRules': 'cpp_disabled_rules',
'swiftEnabledRules': 'swift_enabled_rules',
'swiftDisabledRules': 'swift_disabled_rules',
'rustEnabledRules': 'rust_enabled_rules',
'rustDisabledRules': 'rust_disabled_rules',
'elixirEnabledRules': 'elixir_enabled_rules',
'elixirDisabledRules': 'elixir_disabled_rules',
# OpenGrep/SAST Configuration
'openGrepNotificationMethod': 'opengrep_notification_method',
# Socket Tier 1
'socketTier1Enabled': 'socket_tier_1_enabled',
'socketAdditionalParams': 'socket_additional_params',
# Secret Scanning
'secretScanningEnabled': 'secret_scanning_enabled',
'disableAllSecrets': 'disable_all_secrets',
'trufflehogExcludeDir': 'trufflehog_exclude_dir',
'trufflehogShowUnverified': 'trufflehog_show_unverified',
'trufflehogNotificationMethod': 'trufflehog_notification_method',
# Container/Image Scanning
'containerImagesToScan': 'container_images',
'dockerfiles': 'dockerfiles',
'trivyImageEnabled': 'trivy_image_enabled',
'trivyDockerfileEnabled': 'trivy_dockerfile_enabled',
'trivyNotificationMethod': 'trivy_notification_method',
'trivyDisabledRules': 'trivy_disabled_rules',
'trivyImageScanningDisabled': 'trivy_image_scanning_disabled',
# Notifier Configuration
'slackWebhookUrl': 'slack_webhook_url',
'webhookUrl': 'webhook_url',
'msSentinelWorkspaceId': 'ms_sentinel_workspace_id',
'msSentinelKey': 'ms_sentinel_shared_key',
'sumologicEndpoint': 'sumologic_endpoint',
'jiraUrl': 'jira_url',
'jiraProject': 'jira_project',
'jiraEmail': 'jira_email',
'jiraApiToken': 'jira_api_token',
'githubToken': 'github_token',
'githubApiUrl': 'github_api_url',
'msteamsWebhookUrl': 'msteams_webhook_url',
# S3 Configuration
's3Enabled': 's3_enabled',
's3Bucket': 's3_bucket',
's3AccessKey': 's3_access_key',
's3SecretKey': 's3_secret_key',
's3Endpoint': 's3_endpoint',
's3Region': 's3_region',
# Additional Features
'externalCveScanningEnabled': 'external_cve_scanning_enabled',
'socketScanningEnabled': 'socket_scanning_enabled',
'socketScaEnabled': 'socket_sca_enabled',
'additionalParameters': 'additional_parameters',
}
normalized = {}
logger = logging.getLogger(__name__)
for api_key, value in api_config.items():
# Check if we have a mapping for this key
if api_key in API_TO_INTERNAL_MAP:
internal_key = API_TO_INTERNAL_MAP[api_key]
normalized[internal_key] = value
logger.debug(f" Mapped API key '{api_key}' -> '{internal_key}' = {value}")
else:
# Pass through unmapped keys as-is (for plan info, etc.)
normalized[api_key] = value
logger.debug(f" Pass-through key '{api_key}' = {value}")
# Special handling: if containerImagesToScan or dockerfiles have values, enable scanning
# This eliminates the need for separate *_enabled flags
if normalized.get('container_images'):
normalized['trivy_image_enabled'] = True
normalized['container_image_scanning_enabled'] = True # For backward compatibility
logger.debug(" Auto-enabled trivy_image_enabled because container_images is set")
if normalized.get('dockerfiles'):
normalized['trivy_dockerfile_enabled'] = True
normalized['dockerfile_scanning_enabled'] = True # For backward compatibility
logger.debug(" Auto-enabled trivy_dockerfile_enabled because dockerfiles is set")
# Handle trivy notification method mapping
if 'trivy_notification_method' in normalized:
normalized['notification_method'] = normalized['trivy_notification_method']
# Handle trufflehog notification method mapping
if 'trufflehog_notification_method' in normalized:
if 'notification_method' not in normalized:
normalized['notification_method'] = normalized['trufflehog_notification_method']
# Handle opengrep notification method mapping
if 'opengrep_notification_method' in normalized:
if 'notification_method' not in normalized:
normalized['notification_method'] = normalized['opengrep_notification_method']
return normalized