MarketAlly.AIPlugin.Extensions/MarketAlly.AIPlugin.Security/Configuration/SecurityConfiguration.cs

255 lines
9.1 KiB
C#
Executable File

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace MarketAlly.AIPlugin.Security.Configuration
{
/// <summary>
/// Central configuration management for security analysis plugins
/// </summary>
public class SecurityAnalysisConfiguration
{
public PatternConfiguration Patterns { get; set; } = new PatternConfiguration();
public ScanConfiguration ScanSettings { get; set; } = new ScanConfiguration();
public ReportingConfiguration Reporting { get; set; } = new ReportingConfiguration();
public PerformanceConfiguration Performance { get; set; } = new PerformanceConfiguration();
/// <summary>
/// Loads configuration from JSON file
/// </summary>
public static SecurityAnalysisConfiguration LoadFromFile(string configPath)
{
if (!File.Exists(configPath))
{
return GetDefault();
}
try
{
var json = File.ReadAllText(configPath);
var config = JsonSerializer.Deserialize<SecurityAnalysisConfiguration>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip
});
return config ?? GetDefault();
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to load security configuration from {configPath}: {ex.Message}", ex);
}
}
/// <summary>
/// Saves configuration to JSON file
/// </summary>
public void SaveToFile(string configPath)
{
try
{
var json = JsonSerializer.Serialize(this, new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
File.WriteAllText(configPath, json);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to save security configuration to {configPath}: {ex.Message}", ex);
}
}
/// <summary>
/// Gets default configuration
/// </summary>
public static SecurityAnalysisConfiguration GetDefault()
{
return new SecurityAnalysisConfiguration
{
Patterns = PatternConfiguration.GetDefault(),
ScanSettings = ScanConfiguration.GetDefault(),
Reporting = ReportingConfiguration.GetDefault(),
Performance = PerformanceConfiguration.GetDefault()
};
}
/// <summary>
/// Validates the configuration
/// </summary>
public ValidationResult Validate()
{
var errors = new List<string>();
if (ScanSettings.MaxFileSizeBytes <= 0)
errors.Add("MaxFileSizeBytes must be greater than 0");
if (ScanSettings.MaxFilesPerScan <= 0)
errors.Add("MaxFilesPerScan must be greater than 0");
if (Performance.MaxParallelism <= 0)
errors.Add("MaxParallelism must be greater than 0");
if (Performance.TimeoutSeconds <= 0)
errors.Add("TimeoutSeconds must be greater than 0");
return new ValidationResult
{
IsValid = errors.Count == 0,
Errors = errors
};
}
}
/// <summary>
/// Configuration for security patterns
/// </summary>
public class PatternConfiguration
{
public List<CustomPattern> CustomSecretPatterns { get; set; } = new List<CustomPattern>();
public List<CustomPattern> CustomVulnerabilityPatterns { get; set; } = new List<CustomPattern>();
public List<string> ExcludedPatterns { get; set; } = new List<string>();
public bool EnableEntropyBasedDetection { get; set; } = false;
public double EntropyThreshold { get; set; } = 4.5;
public static PatternConfiguration GetDefault()
{
return new PatternConfiguration
{
ExcludedPatterns = new List<string>
{
"example", "placeholder", "your_api_key", "test", "demo"
},
EnableEntropyBasedDetection = false,
EntropyThreshold = 4.5
};
}
}
/// <summary>
/// Custom security pattern definition
/// </summary>
public class CustomPattern
{
public string Name { get; set; }
public string Pattern { get; set; }
public string Category { get; set; }
public string Severity { get; set; }
public string Description { get; set; }
public string Recommendation { get; set; }
public bool Enabled { get; set; } = true;
/// <summary>
/// Compiles the pattern to a Regex object
/// </summary>
public Regex ToRegex()
{
return new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
/// <summary>
/// Configuration for scan behavior
/// </summary>
public class ScanConfiguration
{
public List<string> IncludedFileExtensions { get; set; } = new List<string>();
public List<string> ExcludedDirectories { get; set; } = new List<string>();
public List<string> ExcludedFiles { get; set; } = new List<string>();
public long MaxFileSizeBytes { get; set; } = 10 * 1024 * 1024; // 10MB
public int MaxFilesPerScan { get; set; } = 10000;
public string DefaultSeverityLevel { get; set; } = "medium";
public bool EnableContextAnalysis { get; set; } = true;
public int ContextLineRadius { get; set; } = 2;
public static ScanConfiguration GetDefault()
{
return new ScanConfiguration
{
IncludedFileExtensions = new List<string>
{
".cs", ".js", ".ts", ".py", ".java", ".php", ".rb", ".go", ".cpp", ".c", ".h",
".json", ".xml", ".config", ".yml", ".yaml", ".properties", ".ini"
},
ExcludedDirectories = new List<string>
{
"node_modules", "bin", "obj", ".git", ".vs", "packages", "target", "build", ".vscode"
},
ExcludedFiles = new List<string>
{
"*.min.js", "*.min.css", "package-lock.json", "yarn.lock"
},
MaxFileSizeBytes = 10 * 1024 * 1024,
MaxFilesPerScan = 10000,
DefaultSeverityLevel = "medium",
EnableContextAnalysis = true,
ContextLineRadius = 2
};
}
}
/// <summary>
/// Configuration for reporting and output
/// </summary>
public class ReportingConfiguration
{
public List<string> OutputFormats { get; set; } = new List<string>();
public bool IncludeRecommendations { get; set; } = true;
public bool IncludeCodeContext { get; set; } = true;
public bool MaskSensitiveValues { get; set; } = true;
public string ReportTemplate { get; set; } = "default";
public Dictionary<string, object> CustomReportSettings { get; set; } = new Dictionary<string, object>();
public static ReportingConfiguration GetDefault()
{
return new ReportingConfiguration
{
OutputFormats = new List<string> { "json", "markdown" },
IncludeRecommendations = true,
IncludeCodeContext = true,
MaskSensitiveValues = true,
ReportTemplate = "default"
};
}
}
/// <summary>
/// Configuration for performance optimization
/// </summary>
public class PerformanceConfiguration
{
public int MaxParallelism { get; set; } = Environment.ProcessorCount;
public bool EnableCaching { get; set; } = true;
public int CacheExpiryMinutes { get; set; } = 60;
public bool EnableIncrementalAnalysis { get; set; } = false;
public int TimeoutSeconds { get; set; } = 300; // 5 minutes
public int RateLimitDelayMs { get; set; } = 100;
public static PerformanceConfiguration GetDefault()
{
return new PerformanceConfiguration
{
MaxParallelism = Environment.ProcessorCount,
EnableCaching = true,
CacheExpiryMinutes = 60,
EnableIncrementalAnalysis = false,
TimeoutSeconds = 300,
RateLimitDelayMs = 100
};
}
}
/// <summary>
/// Configuration validation result
/// </summary>
public class ValidationResult
{
public bool IsValid { get; set; }
public List<string> Errors { get; set; } = new List<string>();
public List<string> Warnings { get; set; } = new List<string>();
}
}