use crate::error::{ConfigError, Result};
use std::env;
use std::path::{Path, PathBuf};
#[cfg(feature = "wasm")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "wasm", derive(Serialize, Deserialize))]
pub struct Config {
pub github_token: String,
pub gitleaks_license: Option<String>,
pub gitleaks_version: String,
pub gitleaks_config: Option<PathBuf>,
pub enable_summary: bool,
pub enable_upload_artifact: bool,
pub enable_comments: bool,
pub notify_user_list: Vec<String>,
pub base_ref: Option<String>,
pub workspace_path: PathBuf,
pub event_path: PathBuf,
pub event_name: String,
pub repository: String,
pub repository_owner: String,
}
impl Config {
pub fn from_env() -> Result<Self> {
let workspace_path = Self::get_required_env("GITHUB_WORKSPACE")?;
let event_path = Self::get_required_env("GITHUB_EVENT_PATH")?;
let event_name = Self::get_required_env("GITHUB_EVENT_NAME")?;
let repository = Self::get_required_env("GITHUB_REPOSITORY")?;
let repository_owner = Self::get_required_env("GITHUB_REPOSITORY_OWNER")?;
let github_token = env::var("GITHUB_TOKEN").unwrap_or_default();
if event_name == "pull_request" && github_token.is_empty() {
return Err(ConfigError::MissingEnvVar(
"GITHUB_TOKEN is required for pull_request events".into(),
)
.into());
}
let gitleaks_license = env::var("GITLEAKS_LICENSE").ok();
let gitleaks_version =
env::var("GITLEAKS_VERSION").unwrap_or_else(|_| "8.24.3".to_string());
let enable_summary = Self::parse_boolean_env("GITLEAKS_ENABLE_SUMMARY", true)?;
let enable_upload_artifact =
Self::parse_boolean_env("GITLEAKS_ENABLE_UPLOAD_ARTIFACT", true)?;
let enable_comments = Self::parse_boolean_env("GITLEAKS_ENABLE_COMMENTS", true)?;
let notify_user_list =
Self::parse_user_list(&env::var("GITLEAKS_NOTIFY_USER_LIST").unwrap_or_default());
let base_ref = env::var("BASE_REF").ok();
let gitleaks_config = if let Ok(explicit_config) = env::var("GITLEAKS_CONFIG") {
let path = PathBuf::from(&explicit_config);
Self::validate_path(&path, &PathBuf::from(&workspace_path))?;
Some(path)
} else {
let default_config = PathBuf::from(&workspace_path).join("gitleaks.toml");
if default_config.exists() {
Some(default_config)
} else {
None
}
};
let workspace_path = Self::validate_workspace_path(&workspace_path)?;
let event_path = Self::validate_path_buf(&event_path, &workspace_path)?;
if !repository.contains('/') {
return Err(ConfigError::InvalidRepository(repository).into());
}
Ok(Config {
github_token,
gitleaks_license,
gitleaks_version,
gitleaks_config,
enable_summary,
enable_upload_artifact,
enable_comments,
notify_user_list,
base_ref,
workspace_path,
event_path,
event_name,
repository,
repository_owner,
})
}
fn get_required_env(key: &str) -> Result<String> {
env::var(key).map_err(|_| ConfigError::MissingEnvVar(key.to_string()).into())
}
fn parse_boolean_env(key: &str, default: bool) -> Result<bool> {
match env::var(key) {
Ok(value) => match value.as_str() {
"false" | "0" => Ok(false),
_ => Ok(true),
},
Err(_) => Ok(default),
}
}
fn parse_user_list(input: &str) -> Vec<String> {
if input.is_empty() {
return Vec::new();
}
input
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
fn validate_workspace_path(path: &str) -> Result<PathBuf> {
let path_buf = PathBuf::from(path);
if !path_buf.exists() {
return Err(ConfigError::FileNotFound(path.to_string()).into());
}
if !path_buf.is_dir() {
return Err(ConfigError::InvalidPath(format!("{} is not a directory", path)).into());
}
path_buf.canonicalize().map_err(|e| {
ConfigError::InvalidPath(format!("Failed to canonicalize {}: {}", path, e)).into()
})
}
fn validate_path_buf(path: &str, workspace: &Path) -> Result<PathBuf> {
let path_buf = PathBuf::from(path);
if path.contains("..") {
return Err(ConfigError::PathTraversal(path.to_string()).into());
}
let canonical = if path_buf.exists() {
path_buf.canonicalize().map_err(|e| {
ConfigError::InvalidPath(format!("Failed to canonicalize {}: {}", path, e))
})?
} else {
if path_buf.is_absolute() {
path_buf
} else {
workspace.join(&path_buf)
}
};
if !canonical.starts_with(workspace) {
return Err(ConfigError::OutsideWorkspace(path.to_string()).into());
}
Ok(canonical)
}
fn validate_path(path: &Path, workspace: &Path) -> Result<()> {
if path.to_string_lossy().contains("..") {
return Err(ConfigError::PathTraversal(path.display().to_string()).into());
}
if path.exists() {
let canonical = path.canonicalize().map_err(|e| {
ConfigError::InvalidPath(format!(
"Failed to canonicalize {}: {}",
path.display(),
e
))
})?;
if !canonical.starts_with(workspace) {
return Err(ConfigError::OutsideWorkspace(path.display().to_string()).into());
}
}
Ok(())
}
pub fn validate_git_ref(git_ref: &str) -> Result<()> {
if git_ref.is_empty() {
return Ok(()); }
let dangerous_chars = [';', '&', '|', '$', '`', '\n', '\r', '<', '>'];
for ch in dangerous_chars {
if git_ref.contains(ch) {
return Err(ConfigError::InvalidGitRef(format!(
"Contains dangerous character '{}'",
ch
))
.into());
}
}
if git_ref.contains("..") {
return Err(ConfigError::InvalidGitRef("Contains path traversal".to_string()).into());
}
Ok(())
}
pub fn sarif_path(&self) -> PathBuf {
self.workspace_path.join("results.sarif")
}
pub fn repo_parts(&self) -> (&str, &str) {
let parts: Vec<&str> = self.repository.split('/').collect();
if parts.len() == 2 {
(parts[0], parts[1])
} else {
(self.repository_owner.as_str(), "")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn test_parse_boolean_env() {
assert_eq!(
Config::parse_boolean_env("NONEXISTENT", true).unwrap(),
true
);
assert_eq!(
Config::parse_boolean_env("NONEXISTENT", false).unwrap(),
false
);
env::set_var("TEST_BOOL_FALSE", "false");
assert_eq!(
Config::parse_boolean_env("TEST_BOOL_FALSE", true).unwrap(),
false
);
env::set_var("TEST_BOOL_ZERO", "0");
assert_eq!(
Config::parse_boolean_env("TEST_BOOL_ZERO", true).unwrap(),
false
);
env::set_var("TEST_BOOL_TRUE", "true");
assert_eq!(
Config::parse_boolean_env("TEST_BOOL_TRUE", false).unwrap(),
true
);
env::set_var("TEST_BOOL_ONE", "1");
assert_eq!(
Config::parse_boolean_env("TEST_BOOL_ONE", false).unwrap(),
true
);
env::set_var("TEST_BOOL_ANY", "anything");
assert_eq!(
Config::parse_boolean_env("TEST_BOOL_ANY", false).unwrap(),
true
);
}
#[test]
fn test_parse_user_list() {
assert_eq!(Config::parse_user_list(""), Vec::<String>::new());
assert_eq!(Config::parse_user_list("@user1"), vec!["@user1"]);
assert_eq!(
Config::parse_user_list("@user1, @user2, @user3"),
vec!["@user1", "@user2", "@user3"]
);
assert_eq!(
Config::parse_user_list("@user1,@user2"),
vec!["@user1", "@user2"]
);
}
#[test]
fn test_validate_git_ref() {
assert!(Config::validate_git_ref("").is_ok());
assert!(Config::validate_git_ref("main").is_ok());
assert!(Config::validate_git_ref("abc123def456").is_ok());
assert!(Config::validate_git_ref("refs/heads/feature-branch").is_ok());
assert!(Config::validate_git_ref("main;echo hello").is_err());
assert!(Config::validate_git_ref("main&& rm -rf /").is_err());
assert!(Config::validate_git_ref("../../../etc/passwd").is_err());
assert!(Config::validate_git_ref("main`whoami`").is_err());
}
#[test]
fn test_repo_parts() {
let config = Config {
github_token: String::new(),
gitleaks_license: None,
gitleaks_version: "8.24.3".to_string(),
gitleaks_config: None,
enable_summary: true,
enable_upload_artifact: true,
enable_comments: true,
notify_user_list: Vec::new(),
base_ref: None,
workspace_path: PathBuf::from("/tmp"),
event_path: PathBuf::from("/tmp/event.json"),
event_name: "push".to_string(),
repository: "owner/repo".to_string(),
repository_owner: "owner".to_string(),
};
assert_eq!(config.repo_parts(), ("owner", "repo"));
}
}