-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.py
More file actions
619 lines (522 loc) · 27.9 KB
/
config.py
File metadata and controls
619 lines (522 loc) · 27.9 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
# -
# #%L
# Contrast AI SmartFix
# %%
# Copyright (C) 2026 Contrast Security, Inc.
# %%
# Contact: [email protected]
# License: Commercial
# NOTICE: This Software and the patented inventions embodied within may only be
# used as part of Contrast Security’s commercial offerings. Even though it is
# made available through public repositories, use of this Software is subject to
# the applicable End User Licensing Agreement found at
# https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
# between Contrast Security and the End User. The Software may not be reverse
# engineered, modified, repackaged, sold, redistributed or otherwise used in a
# way not consistent with the End User License Agreement.
# #L%
#
import os
import re
import sys
import json
from pathlib import Path
from typing import Optional, Any, Dict, List
from src.smartfix.config.command_validator import validate_command, CommandValidationError
def _log_config_message(message: str, is_error: bool = False, is_warning: bool = False) -> None:
"""A minimal logger for use only within the config module before full logging is set up."""
# This function should have no dependencies on other project modules
if is_error or is_warning:
print(message, file=sys.stderr)
else:
print(message)
class ConfigurationError(Exception):
"""Custom exception for configuration errors."""
pass
class Config:
"""
A centralized, object-oriented class to manage all configuration settings.
It reads from environment variables upon instantiation and provides validated
and typed settings as attributes.
"""
# Class-level recursion guard: True while build command detection is in progress
_build_detection_in_progress = False
def __init__(self, env: Dict[str, str] = os.environ, testing: bool = False) -> None: # noqa: C901
self.env = env
self.testing = testing
# --- Preset ---
self.VERSION = "v1.0.11"
self.USER_AGENT = f"contrast-smart-fix {self.VERSION}"
# --- Paths (initialized early for use in command detection) ---
if testing:
# For tests, default to /tmp if GITHUB_WORKSPACE not set
self.REPO_ROOT = Path(self._get_env_var("GITHUB_WORKSPACE", required=False, default="/tmp")).resolve()
else:
self.REPO_ROOT = Path(self._get_env_var("GITHUB_WORKSPACE", required=True)).resolve()
self.SCRIPT_DIR = Path(__file__).parent.resolve()
# --- Core Settings ---
self.DEBUG_MODE = self._get_bool_env("DEBUG_MODE", default=False)
# Check for testing flag to make BASE_BRANCH optional in tests
if testing and "BASE_BRANCH" not in env:
self.BASE_BRANCH = "main" # Default for tests
else:
self.BASE_BRANCH = self._get_env_var("BASE_BRANCH", required=True)
self.RUN_TASK = self._get_env_var("RUN_TASK", required=False, default="generate_fix")
# --- AI Agent Configuration ---
self.CODING_AGENT = self._get_coding_agent()
from src.smartfix.shared.coding_agents import CodingAgents
is_smartfix_coding_agent = self.CODING_AGENT == CodingAgents.SMARTFIX.name
default_agent_model = ""
if is_smartfix_coding_agent:
default_agent_model = "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0"
self.AGENT_MODEL = self._get_env_var("AGENT_MODEL", required=False, default=default_agent_model)
# --- Build and Formatting Configuration ---
is_build_command_required = self.RUN_TASK == "generate_fix" and is_smartfix_coding_agent
# Make BUILD_COMMAND optional in tests
if testing and "BUILD_COMMAND" not in env and is_build_command_required:
self.BUILD_COMMAND = "echo 'Test build command'"
else:
self.BUILD_COMMAND = self._get_env_var("BUILD_COMMAND", required=False)
# Auto-detect if not provided AND required
# Skip detection entirely when BUILD_COMMAND not needed
if not self.BUILD_COMMAND and not testing and is_build_command_required:
# Recursion guard: detection calls get_config() internally
if not Config._build_detection_in_progress:
Config._build_detection_in_progress = True
try:
self.BUILD_COMMAND = self._auto_detect_build_command()
finally:
Config._build_detection_in_progress = False
# Mark as auto-detected for proper validation
self._build_command_source = "ai_detected"
else:
# Recursion detected: detection already in progress
_log_config_message(
"Build command detection already in progress, skipping",
is_warning=True
)
self.BUILD_COMMAND = None
self._build_command_source = "ai_detected"
else:
# Command from environment/config (trusted source)
self._build_command_source = "config"
# Validate BUILD_COMMAND if present
if not testing and self.BUILD_COMMAND:
self._validate_command("BUILD_COMMAND", self.BUILD_COMMAND, source=self._build_command_source)
self.FORMATTING_COMMAND = self._get_env_var("FORMATTING_COMMAND", required=False)
# Auto-detect formatting command if not provided AND formatting is needed
# Only needed for generate_fix task
is_format_command_needed = self.RUN_TASK == "generate_fix" and is_smartfix_coding_agent
if not self.FORMATTING_COMMAND and not testing and is_format_command_needed:
# Recursion guard: skip if we're inside a recursive get_config() call
if not Config._build_detection_in_progress:
self.FORMATTING_COMMAND = self._auto_detect_format_command()
# Mark as auto-detected for proper validation
self._format_command_source = "ai_detected"
else:
# Recursion detected: skip formatting detection
_log_config_message(
"Format command detection skipped (recursion detected)",
is_warning=True
)
self._format_command_source = "config"
else:
# Command from environment/config (trusted source)
self._format_command_source = "config"
# Validate FORMATTING_COMMAND if present
if not testing and self.FORMATTING_COMMAND:
self._validate_command("FORMATTING_COMMAND", self.FORMATTING_COMMAND, source=self._format_command_source)
# --- Validated and normalized settings ---
self.MAX_OPEN_PRS = self._get_validated_int("MAX_OPEN_PRS", default=5, min_val=0)
self.MAX_EVENTS_PER_AGENT = self._get_validated_int("MAX_EVENTS_PER_AGENT", default=120, min_val=10, max_val=500)
# --- GitHub Configuration ---
if testing:
self.GITHUB_TOKEN = self._get_env_var("GITHUB_TOKEN", required=False, default="mock-token-for-testing")
self.GITHUB_REPOSITORY = self._get_env_var("GITHUB_REPOSITORY", required=False, default="mock/repo-for-testing")
self.GITHUB_SERVER_URL = self._get_env_var("GITHUB_SERVER_URL", required=False, default="https://github.com")
else:
self.GITHUB_TOKEN = self._get_env_var("GITHUB_TOKEN", required=True)
self.GITHUB_REPOSITORY = self._get_env_var("GITHUB_REPOSITORY", required=True)
# GITHUB_SERVER_URL is automatically set by GitHub Actions (e.g., https://github.com or https://mycompany.ghe.com)
self.GITHUB_SERVER_URL = self._get_env_var("GITHUB_SERVER_URL", required=True, default="https://github.com")
self.GITHUB_RUN_ID = self._get_env_var("GITHUB_RUN_ID", required=False, default="")
# --- Contrast API Configuration ---
if testing:
self.CONTRAST_HOST = self._get_env_var("CONTRAST_HOST", required=False, default="test-host")
self.CONTRAST_ORG_ID = self._get_env_var("CONTRAST_ORG_ID", required=False, default="test-org")
# In testing mode, respect explicit CONTRAST_APP_ID if set; otherwise, derive it from CONTRAST_APP_IDS,
# and only then fall back to the 'test-app' default when neither is provided.
self.CONTRAST_APP_ID = self._get_env_var("CONTRAST_APP_ID", required=False, default=None)
self.CONTRAST_APP_IDS = self._parse_app_ids(self._get_env_var("CONTRAST_APP_IDS", required=False))
if self.CONTRAST_APP_ID is None:
if self.CONTRAST_APP_IDS:
self.CONTRAST_APP_ID = self.CONTRAST_APP_IDS[0]
else:
self.CONTRAST_APP_ID = "test-app"
self.CONTRAST_AUTHORIZATION_KEY = self._get_env_var("CONTRAST_AUTHORIZATION_KEY", required=False, default="test-auth")
self.CONTRAST_API_KEY = self._get_env_var("CONTRAST_API_KEY", required=False, default="test-api")
else:
self.CONTRAST_HOST = self._get_env_var("CONTRAST_HOST", required=True)
self.CONTRAST_ORG_ID = self._get_env_var("CONTRAST_ORG_ID", required=True)
self.CONTRAST_APP_ID, self.CONTRAST_APP_IDS = self._resolve_app_id()
self.CONTRAST_AUTHORIZATION_KEY = self._get_env_var("CONTRAST_AUTHORIZATION_KEY", required=True)
self.CONTRAST_API_KEY = self._get_env_var("CONTRAST_API_KEY", required=True)
# Only check config values in non-testing mode
if not testing:
self._check_contrast_config_values_exist()
# --- Feature Flags ---
self.SKIP_WRITING_SECURITY_TEST = self._get_bool_env("SKIP_WRITING_SECURITY_TEST", default=False)
self.USE_SMARTFIX_INSTRUCTIONS = self._get_bool_env("USE_SMARTFIX_INSTRUCTIONS", default=True)
self.USE_REPO_AGENT_INSTRUCTIONS = self._get_bool_env("USE_REPO_AGENT_INSTRUCTIONS", default=True)
self.ENABLE_FULL_TELEMETRY = self._get_bool_env("ENABLE_FULL_TELEMETRY", default=True)
self.USE_CONTRAST_LLM = self._get_bool_env("USE_CONTRAST_LLM", default=True)
self.ENABLE_ANTHROPIC_PROMPT_CACHING = self._get_bool_env("ENABLE_ANTHROPIC_PROMPT_CACHING", default=True)
# --- LLM Retry Configuration ---
self.LLM_MAX_RETRIES = self._get_validated_int("LLM_MAX_RETRIES", default=7, min_val=1)
self.LLM_INITIAL_RETRY_DELAY_SECONDS = self._get_validated_int("LLM_INITIAL_RETRY_DELAY_SECONDS", default=1, min_val=1)
self.LLM_RETRY_MULTIPLIER = self._get_validated_int("LLM_RETRY_MULTIPLIER", default=2, min_val=2)
# Update agent model for Contrast LLM if no explicit model was set
if (is_smartfix_coding_agent
and self.USE_CONTRAST_LLM
and self._get_env_var("AGENT_MODEL", required=False) is None):
self.AGENT_MODEL = "contrast/claude-sonnet-4-5"
# Validate AWS Bedrock configuration if applicable
self._validate_aws_bedrock_config()
# --- Vulnerability Configuration ---
self.VULNERABILITY_SEVERITIES = self._parse_and_validate_severities(
self._get_env_var("VULNERABILITY_SEVERITIES", required=False, default='["CRITICAL", "HIGH", "MEDIUM"]')
)
if not testing:
self._log_initial_settings()
def _get_env_var(self, var_name: str, required: bool = True, default: Optional[Any] = None) -> Optional[str]:
value = self.env.get(var_name)
if required and not value:
raise ConfigurationError(f"Error: Required environment variable {var_name} is not set.")
return value if value else default
def _get_bool_env(self, var_name: str, default: bool = False) -> bool:
return self._get_env_var(var_name, required=False, default=str(default)).lower() == "true"
def _get_validated_int(self, var_name: str, default: int, min_val: Optional[int] = None, max_val: Optional[int] = None) -> int:
val_str = self._get_env_var(var_name, required=False, default=str(default))
try:
value = int(val_str)
if min_val is not None and value < min_val:
_log_config_message(f"{var_name} ({value}) is below minimum ({min_val}). Using {min_val}.", is_warning=True)
return min_val
if max_val is not None and value > max_val:
_log_config_message(f"{var_name} ({value}) is above maximum ({max_val}). Using {max_val}.", is_warning=True)
return max_val
return value
except (ValueError, TypeError):
_log_config_message(f"Invalid value for {var_name}. Using default: {default}", is_warning=True)
return default
def _check_contrast_config_values_exist(self) -> None:
if not all([self.CONTRAST_HOST, self.CONTRAST_ORG_ID, self.CONTRAST_APP_ID, self.CONTRAST_AUTHORIZATION_KEY, self.CONTRAST_API_KEY]):
raise ConfigurationError("Error: Missing one or more Contrast API configuration variables (HOST, ORG_ID, APP_ID, AUTH_KEY, API_KEY).")
def _validate_command(self, var_name: str, command: Optional[str], source: str = "config") -> None:
"""
Validate a command against the allowlist.
Args:
var_name: Name of the config variable (for error messages)
command: Command string to validate (can be None)
source: Command source, either "config" (from action.yml, trusted) or
"ai_detected" (generated by AI agent, requires validation).
Default: "config"
Raises:
ConfigurationError: If command fails validation
Notes:
- "config" source: Commands from action.yml inputs are trusted (from humans)
and skip allowlist validation
- "ai_detected" source: Commands generated by AI agents go through full
allowlist validation for security
"""
if not command:
# Empty or None commands are allowed (handled by required flag in _get_env_var)
return
# Skip validation for config-sourced commands (from humans via action.yml)
if source == "config":
_log_config_message(
f"{var_name} from action config (trusted source), skipping allowlist validation"
)
return
# Validate AI-generated commands through allowlist
try:
validate_command(var_name, command)
except CommandValidationError as e:
# Log the validation failure for debugging
_log_config_message(
f"Command validation failed for {var_name}: {str(e)}",
is_error=True
)
# Convert CommandValidationError to ConfigurationError
raise ConfigurationError(str(e)) from e
def _auto_detect_build_command(self) -> Optional[str]:
"""
Auto-detect build command using deterministic detection.
Uses file-marker-based detection to find a valid build command.
Returns None if no command can be detected — the Fix agent's
BuildTool will discover the command at runtime.
Returns:
Detected build command or None
"""
from src.smartfix.config.command_detector import detect_build_command
try:
command = detect_build_command(
repo_root=self.REPO_ROOT,
project_dir=None, # NOTE: Will need update when monorepo support is implemented
)
if command:
_log_config_message(
f"Auto-detected BUILD_COMMAND: {command}",
is_error=False
)
else:
_log_config_message(
"Could not auto-detect BUILD_COMMAND (agent will discover at runtime)",
is_warning=True
)
return command
except Exception as e:
_log_config_message(
f"Build command auto-detection failed: {str(e)}",
is_error=True
)
return None
def _auto_detect_format_command(self) -> Optional[str]:
"""
Auto-detect format command using deterministic detection.
Returns:
Detected format command or None if detection fails
"""
from src.smartfix.config.command_detector import detect_format_command
try:
detected = detect_format_command(
repo_root=self.REPO_ROOT,
project_dir=None # NOTE: Will need update when monorepo support is implemented
)
if detected:
_log_config_message(
f"Auto-detected FORMATTING_COMMAND: {detected}",
is_error=False
)
else:
_log_config_message(
"Could not auto-detect FORMATTING_COMMAND (optional)",
is_error=False
)
return detected
except Exception as e:
_log_config_message(
f"Format command auto-detection failed: {str(e)}",
is_error=False
)
return None
def _get_coding_agent(self) -> str:
from src.smartfix.shared.coding_agents import CodingAgents
coding_agent = self._get_env_var("CODING_AGENT", required=False, default="SMARTFIX")
try:
# Try to convert string to Enum
CodingAgents[coding_agent.upper()]
return coding_agent.upper()
except (KeyError, ValueError):
_log_config_message(
f"Warning: Invalid CODING_AGENT '{coding_agent}'. "
f"Must be one of {[agent.name for agent in CodingAgents]}. "
f"Defaulting to '{CodingAgents.SMARTFIX.name}'.",
is_warning=True
)
return CodingAgents.SMARTFIX.name
def _resolve_app_id(self):
"""
Resolve the active application ID from contrast_app_id or contrast_app_ids inputs.
Precedence:
1. CONTRAST_APP_ID (singular) — takes precedence if set (backward compat)
2. CONTRAST_APP_IDS (plural JSON array) — first element used if singular is absent
3. Neither set — raises ConfigurationError
Returns:
Tuple[str, List[str]]: (resolved_app_id, parsed_app_ids_list)
"""
singular = self._get_env_var("CONTRAST_APP_ID", required=False)
if singular:
return singular, []
plural_raw = self._get_env_var("CONTRAST_APP_IDS", required=False)
if plural_raw:
app_ids = self._parse_app_ids(plural_raw)
return app_ids[0], app_ids
raise ConfigurationError(
"Error: Must set either contrast_app_id or contrast_app_ids. "
"Use contrast_app_id for a single application or "
"contrast_app_ids for a JSON array of application IDs."
)
def _parse_app_ids(self, json_str: Optional[str]) -> List[str]:
"""
Parse and validate a JSON array of application IDs.
Args:
json_str: JSON string representing an array of app IDs, or None
Returns:
List[str]: Parsed list of app IDs, or empty list if json_str is None/empty
Raises:
ConfigurationError: If json_str is set but invalid or results in an empty list
"""
if not json_str:
return []
try:
app_ids = json.loads(json_str)
except json.JSONDecodeError:
raise ConfigurationError(
f"Error: contrast_app_ids must be a valid JSON array. "
f"Got: {json_str!r}"
)
if not isinstance(app_ids, list):
raise ConfigurationError(
f"Error: contrast_app_ids must be a JSON array, not {type(app_ids).__name__}. "
f"Example: '[\"app-id-1\", \"app-id-2\"]'"
)
if not app_ids:
raise ConfigurationError(
"Error: contrast_app_ids must not be an empty array."
)
cleaned_ids: List[str] = []
invalid_entries = []
for index, raw_app_id in enumerate(app_ids):
app_id_str = str(raw_app_id).strip() if raw_app_id is not None else ""
if app_id_str:
cleaned_ids.append(app_id_str)
else:
invalid_entries.append((index, raw_app_id))
if invalid_entries:
details = ", ".join(
f"{idx} (value: {repr(value)})" for idx, value in invalid_entries
)
raise ConfigurationError(
f"Error: contrast_app_ids contains invalid entries at positions: {details}."
)
return cleaned_ids
def _parse_and_validate_severities(self, json_str: Optional[str]) -> List[str]:
default_severities = ["CRITICAL", "HIGH", "MEDIUM"]
valid_severities = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "NOTE"]
try:
if not json_str:
return default_severities
severities = json.loads(json_str)
if not isinstance(severities, list):
_log_config_message(f"Vulnerability_severities must be a list, got {type(severities)}. Using default.", is_warning=True)
return default_severities
validated = [s.upper() for s in severities if s.upper() in valid_severities]
if not validated:
_log_config_message(f"No valid severity levels provided. Using default: {default_severities}", is_warning=True)
return default_severities
return validated
except json.JSONDecodeError:
_log_config_message(f"Error parsing vulnerability_severities JSON: {json_str}. Using default.", is_error=True)
return default_severities
def _validate_aws_bedrock_config(self) -> None:
"""Validate AWS Bedrock configuration when using Bedrock models.
This prevents cryptic IDNA encoding errors when AWS region is missing
or contains invalid characters. Without this validation, users would see:
'UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long)'
which is very difficult to debug.
"""
# Only validate for generate_fix task
if self.RUN_TASK != "generate_fix":
return
model_lower = self.AGENT_MODEL.lower() if self.AGENT_MODEL else ""
# Only validate if using Bedrock models (not Contrast LLM)
if self.USE_CONTRAST_LLM or "bedrock/" not in model_lower:
return
# Check that AWS credentials are present when using Bedrock
# Check for either bearer token OR IAM credentials
has_bearer_token = bool(self.env.get('AWS_BEARER_TOKEN_BEDROCK', '').strip())
has_iam_credentials = any(
key.startswith('AWS_') and key not in ('AWS_BEARER_TOKEN_BEDROCK', 'AWS_REGION_NAME') and self.env.get(key, '').strip()
for key in self.env.keys()
)
has_aws_credentials = has_bearer_token or has_iam_credentials
if not has_aws_credentials:
raise ConfigurationError(
"Error: AWS credentials are required when using Bedrock models.\n"
"You must set either:\n"
" - AWS IAM credentials (such as AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN)\n"
" - AWS Other Tokens (AWS_BEARER_TOKEN_BEDROCK)\n"
f"Current model: {self.AGENT_MODEL}"
)
# Check for AWS_REGION_NAME (what LiteLLM expects)
# action.yml sets this from inputs.aws_region or env.AWS_REGION
aws_region = self.env.get('AWS_REGION_NAME', '').strip()
if not aws_region:
raise ConfigurationError(
"Error: aws_region is required when using Bedrock models.\n"
"Set the 'aws_region' input in your workflow (e.g., aws_region: 'us-east-1').\n"
"This is required for both AWS IAM credentials and AWS Bearer Token authentication."
)
# Validate region format - just catch obvious mistakes like quotes or special chars
# Allow only lowercase letters, numbers, and hyphens (flexible for future regions)
if not re.match(r'^[a-z][a-z0-9-]*[a-z0-9]$', aws_region):
raise ConfigurationError(
f"Error: Invalid aws_region format: '{aws_region}'\n"
"Region should contain only lowercase letters, numbers, and hyphens.\n"
"Check for quotes, spaces, or uppercase letters in your configuration."
)
# Normalize the region value in the environment so LiteLLM gets the trimmed value
# This fixes cases where whitespace was present in the original input
if self.env.get('AWS_REGION_NAME', '') != aws_region:
os.environ['AWS_REGION_NAME'] = aws_region
# Check for AWS credentials (either bearer token OR IAM credentials)
has_bearer_token = bool(self.env.get('AWS_BEARER_TOKEN_BEDROCK', '').strip())
has_access_key = bool(self.env.get('AWS_ACCESS_KEY_ID', '').strip())
has_secret_key = bool(self.env.get('AWS_SECRET_ACCESS_KEY', '').strip())
if not has_bearer_token and not (has_access_key and has_secret_key):
raise ConfigurationError(
"Error: AWS credentials required for Bedrock models.\n"
"Provide either:\n"
" 1. AWS_BEARER_TOKEN_BEDROCK (via aws_bearer_token_bedrock input), OR\n"
" 2. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables"
)
def _log_initial_settings(self) -> None:
if not self.DEBUG_MODE:
return
_log_config_message(f"Repository Root: {self.REPO_ROOT}")
_log_config_message(f"Script Directory: {self.SCRIPT_DIR}")
_log_config_message(f"Debug Mode: {self.DEBUG_MODE}")
_log_config_message(f"Base Branch: {self.BASE_BRANCH}")
_log_config_message(f"Run Task: {self.RUN_TASK}")
if not self.USE_CONTRAST_LLM:
_log_config_message(f"Agent Model: {self.AGENT_MODEL}")
_log_config_message(f"Coding Agent: {self.CODING_AGENT}")
_log_config_message(f"Skip Writing Security Test: {self.SKIP_WRITING_SECURITY_TEST}")
_log_config_message(f"Use SmartFix Instructions: {self.USE_SMARTFIX_INSTRUCTIONS}")
_log_config_message(f"Use Repo Agent Instructions: {self.USE_REPO_AGENT_INSTRUCTIONS}")
_log_config_message(f"Vulnerability Severities: {self.VULNERABILITY_SEVERITIES}")
_log_config_message(f"Max Events Per Agent: {self.MAX_EVENTS_PER_AGENT}")
_log_config_message(f"Enable Full Telemetry: {self.ENABLE_FULL_TELEMETRY}")
_log_config_message(f"Use Contrast LLM: {self.USE_CONTRAST_LLM}")
# --- Global Singleton Instance ---
# This is the single source of truth for configuration in the application.
# It is instantiated once when the module is imported.
_config_instance: Optional[Config] = None
def get_config(testing: bool = False) -> Config:
"""
Returns the singleton Config instance, creating it if necessary.
This function ensures that the Config is instantiated only when first needed,
which is crucial for testing environments where environment variables are
patched at runtime.
Args:
testing: If True, uses testing defaults for missing environment variables.
This should only be used in tests.
"""
global _config_instance
if _config_instance is None:
try:
_config_instance = Config(testing=testing)
except ConfigurationError as e:
_log_config_message(str(e), is_error=True)
sys.exit(1)
except ImportError as e:
_log_config_message(f"A module required for configuration could not be imported: {e}", is_error=True)
sys.exit(1)
return _config_instance
def reset_config() -> None:
"""For testing purposes only. Resets the config singleton."""
global _config_instance
_config_instance = None
# Also reset the detection flag to allow fresh detection in tests
Config._build_detection_in_progress = False