use cert_x_gen::pentest_install::{Bundle, Installer};
use cert_x_gen::{
ai::{AIManager, TemplateValidator},
config::Config,
core::CertXGen,
error::{Error, Result},
output::OutputManager,
plugin::{LoggingPlugin, PluginManager},
progress::{get_progress, init_progress},
template::{Template, TemplateFilter},
types::{Protocol, Target, TemplateLanguage},
utils,
};
use std::io::IsTerminal;
use std::sync::Arc;
use std::{
collections::HashSet,
fs,
path::{Path, PathBuf},
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
mod cli;
mod scan_probes;
use cli::{Cli, Commands};
fn main() {
std::thread::Builder::new()
.name("cxg".into())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("build CLI runtime")
.block_on(cli_main());
})
.expect("start CLI thread")
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
}
async fn cli_main() {
let args: Vec<String> = std::env::args().collect();
let suppress_banner = std::env::var("CXG_NO_BANNER").is_ok()
|| args.iter().any(|arg| arg == "--quiet" || arg == "-q")
|| args
.iter()
.any(|arg| arg == "--version" || arg == "-V" || arg == "--json")
|| !std::io::stdout().is_terminal();
if !suppress_banner {
cert_x_gen::banner::display_banner();
}
let cli = Cli::parse();
if let Err(e) = init_logging(&cli) {
eprintln!("Failed to initialize logging: {}", e);
std::process::exit(1);
}
if let Err(e) = check_and_enter_sandbox(&cli).await {
tracing::error!("Sandbox error: {}", e);
eprintln!("Sandbox error: {}", e);
std::process::exit(1);
}
if let Err(e) = run(cli).await {
tracing::error!("Error: {}", e);
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
fn init_logging(cli: &Cli) -> Result<()> {
let progress_enabled = cli.verbose == 0;
init_progress(progress_enabled);
let filter_str = match cli.verbose {
0 => "error".to_string(),
1 => "cert_x_gen=info".to_string(),
2 => "cert_x_gen=trace".to_string(),
_ => "cert_x_gen=trace,debug".to_string(),
};
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&filter_str));
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_thread_ids(true)
.with_writer(std::io::stderr);
tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.init();
Ok(())
}
async fn run(cli: Cli) -> Result<()> {
if cli.update_templates {
use cert_x_gen::template::AutoUpdater;
let mut updater = AutoUpdater::new()?;
updater.perform_update()?;
let stats = updater.get_stats();
println!();
println!("Templates: {}", stats.summary());
return Ok(());
}
let is_template_update = matches!(
&cli.command,
Some(Commands::Template(cmd)) if matches!(cmd.action, cli::TemplateAction::Update { .. })
);
if !is_template_update
&& !matches!(
&cli.command,
Some(Commands::Build(_) | Commands::Pentest(_) | Commands::Update(_))
)
{
handle_auto_update(&cli).await?;
}
let command = match cli.command {
Some(cmd) => cmd,
None => {
use clap::CommandFactory;
let mut cmd = Cli::command();
cmd.print_help().ok();
println!();
return Ok(());
}
};
match command {
Commands::Scan(args) => {
if run_scan(args, cli.config).await? {
std::process::exit(2);
}
}
Commands::Build(cmd) => {
run_build_command(cmd)?;
}
Commands::Template(cmd) => {
run_template_command(cmd).await?;
}
Commands::Ai(cmd) => {
run_ai_command(cmd).await?;
}
Commands::Search(args) => {
run_search_command(args).await?;
}
Commands::Server(args) => {
run_server(args).await?;
}
Commands::Config(cmd) => {
run_config_command(cmd)?;
}
Commands::Sandbox(cmd) => {
run_sandbox_command(cmd).await?;
}
Commands::Mcp(cmd) => {
match cmd.action {
None => {
cert_x_gen::mcp::run_mcp().await?;
}
Some(cli::McpAction::Install { client }) => {
cert_x_gen::mcp::installer::run_install(client).await?;
}
Some(cli::McpAction::Uninstall { client }) => {
cert_x_gen::mcp::installer::run_uninstall(client).await?;
}
Some(cli::McpAction::Status) => {
cert_x_gen::mcp::installer::run_status().await?;
}
}
}
Commands::Pentest(cmd) => {
run_pentest_command(cmd).await?;
}
Commands::Update(cmd) => {
run_update_command(cmd).await?;
}
Commands::Version => {
print_version();
}
}
Ok(())
}
fn release_target() -> Result<String> {
let os = match std::env::consts::OS {
"macos" => "darwin",
"linux" => "linux",
"windows" => "windows",
other => {
return Err(Error::config(format!(
"no prebuilt cxg release for OS '{other}' — build from source"
)))
}
};
let arch = match std::env::consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
other => {
return Err(Error::config(format!(
"no prebuilt cxg release for architecture '{other}' — build from source"
)))
}
};
Ok(format!("{os}-{arch}"))
}
fn run_build_command(cmd: cli::BuildCommand) -> Result<()> {
use cert_x_gen::build::{self, InstrumentRequest, Manifest};
use std::io::Write;
if !cmd.instrument {
return Err(Error::config(
"cxg build needs --instrument: it has no other mode".to_string(),
));
}
let sanitizers: Vec<String> = cmd
.sanitizer
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if sanitizers.is_empty() {
return Err(Error::config(
"--sanitizer needs at least one sanitizer, e.g. --sanitizer address".to_string(),
));
}
let manifest = build::instrument(&InstrumentRequest {
project: cmd.project.clone(),
bin: cmd.bin.clone(),
sanitizers,
out_dir: cmd.out.clone(),
build_std: cmd.build_std,
});
let rendered =
serde_json::to_string_pretty(&manifest).map_err(|e| Error::Serialization(e.to_string()))?;
if let Some(ref path) = cmd.manifest {
std::fs::write(path, format!("{rendered}\n")).map_err(|e| {
Error::config(format!("cannot write --manifest '{}': {e}", path.display()))
})?;
}
match &manifest {
Manifest::Instrumented(built) => {
if cmd.quiet {
println!("{}", built.binary.display());
} else {
println!("{rendered}");
}
Ok(())
}
Manifest::Skipped(skipped) => {
if cmd.quiet {
eprintln!("cxg build: skipped: {}", skipped.reason);
} else {
println!("{rendered}");
}
let _ = std::io::stdout().flush();
std::process::exit(3);
}
}
}
async fn run_update_command(cmd: cli::UpdateCommand) -> Result<()> {
use cert_x_gen::release_update::{self, CHECKSUMS_ASSET};
let target = release_target()?;
let current = env!("CARGO_PKG_VERSION");
let invoked = std::env::current_exe()?;
let installed = release_update::installed_executable(&invoked)?;
let kind = release_update::detect_install(&installed);
if cmd.check {
let latest = lookup_release(None).await?;
if self_update::version::bump_is_greater(current, &latest.version).unwrap_or(false) {
println!("Update available: v{current} -> v{}", latest.version);
match kind.upgrade_command() {
Some(command) => println!("Upgrade it with: {command}"),
None => println!("Run `cxg update` to install it."),
}
} else {
println!("cxg is up to date (v{current})");
}
return Ok(());
}
if let (false, Some(manager), Some(command)) =
(cmd.force, kind.manager(), kind.upgrade_command())
{
eprintln!(
"cxg at {} is managed by {manager}, so `cxg update` leaves it alone.",
installed.display()
);
eprintln!("Upgrade it with: {command}");
eprintln!("(Pass --force to replace the file anyway.)");
std::process::exit(3);
}
let release = lookup_release(cmd.version.clone()).await?;
if cmd.version.is_none()
&& !self_update::version::bump_is_greater(current, &release.version).unwrap_or(false)
{
println!("cxg is already up to date (v{current})");
return Ok(());
}
let asset = release.asset_for(&target, None).ok_or_else(|| {
Error::config(format!(
"release v{} has no cxg binary for {target}",
release.version
))
})?;
let sums_asset = release
.assets
.iter()
.find(|a| a.name == CHECKSUMS_ASSET)
.ok_or_else(|| {
Error::config(format!(
"release v{} has no {CHECKSUMS_ASSET}, so its binary cannot be verified",
release.version
))
})?;
println!("Current exe: {}", installed.display());
if std::fs::symlink_metadata(&invoked).is_ok_and(|m| m.file_type().is_symlink()) {
println!(" (invoked as {})", invoked.display());
}
println!(
"New release: v{current} -> v{} ({})",
release.version, asset.name
);
if !cmd.yes {
let proceed = dialoguer::Confirm::new()
.with_prompt("Replace the installed binary?")
.default(true)
.interact()
.map_err(|e| {
Error::config(format!("cannot prompt for confirmation ({e}); pass --yes"))
})?;
if !proceed {
println!("Update cancelled.");
return Ok(());
}
}
let client = reqwest::Client::builder()
.user_agent(concat!("cxg/", env!("CARGO_PKG_VERSION")))
.build()?;
println!("Downloading {}...", asset.name);
let binary = download_release_asset(&client, &asset.download_url).await?;
let sums = download_release_asset(&client, &sums_asset.download_url).await?;
release_update::verify_sha256(&binary, &String::from_utf8_lossy(&sums), &asset.name)
.map_err(Error::config)?;
println!("Verified against {CHECKSUMS_ASSET}");
let staging = tempfile::tempdir()?;
let new_exe = staging.path().join(&asset.name);
std::fs::write(&new_exe, &binary)?;
release_update::replace_executable(&installed, &new_exe).map_err(|e| {
if e.kind() == std::io::ErrorKind::PermissionDenied {
Error::config(format!(
"no permission to replace {} ({e}); re-run with sudo, or reinstall cxg in a \
directory you can write",
installed.display()
))
} else {
Error::config(format!("cannot replace {}: {e}", installed.display()))
}
})?;
println!("Updated cxg to v{}", release.version);
Ok(())
}
async fn lookup_release(tag: Option<String>) -> Result<self_update::update::Release> {
tokio::task::spawn_blocking(move || -> Result<self_update::update::Release> {
let updater = self_update::backends::github::Update::configure()
.repo_owner("Bugb-Technologies")
.repo_name("cert-x-gen")
.bin_name("cxg")
.current_version(env!("CARGO_PKG_VERSION"))
.build()?;
Ok(match tag {
Some(tag) => updater.get_release_version(&tag)?,
None => updater.get_latest_release()?,
})
})
.await
.map_err(|e| Error::Internal(format!("release lookup task panicked: {e}")))?
}
async fn download_release_asset(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
let response = client
.get(url)
.header(reqwest::header::ACCEPT, "application/octet-stream")
.send()
.await?
.error_for_status()?;
Ok(response.bytes().await?.to_vec())
}
fn pentest_home() -> PathBuf {
cert_x_gen::template::PathResolver::user_config_dir().join("pentest")
}
#[derive(Debug, Default)]
struct PentestProcess {
code: i32,
error: String,
}
async fn run_pentest_command(cmd: cli::PentestCommand) -> Result<()> {
let result = run_pentest_process(cmd, false).await?;
if result.code != 0 {
std::process::exit(result.code);
}
Ok(())
}
async fn run_pentest_process(
cmd: cli::PentestCommand,
scan_dispatch: bool,
) -> Result<PentestProcess> {
use std::process::Command as SysCommand;
let process_log = if scan_dispatch {
match &cmd.action {
cli::PentestAction::Run(run) => run
.probe_inputs
.session_dir
.as_ref()
.map(|dir| dir.join("engine.stderr.log")),
_ => None,
}
} else {
None
};
let home = pentest_home();
let source_override = std::env::var_os("CXG_SOURCE").is_some();
let installer = Installer::new(home.parent().unwrap().to_path_buf(), Bundle::embedded());
let install_error = |e: anyhow::Error| {
Error::Config(format!("pentest pipeline: {e:#}. No stale pipeline was launched; check writable home/disk space and retry `cxg pentest update`."))
};
match &cmd.action {
cli::PentestAction::Status(cli::PentestStatusArgs { json }) => {
let status = installer.status();
if *json {
println!("{}", serde_json::to_string(&status).unwrap());
} else {
println!(
"Pentest pipeline: {} at {}",
status.freshness,
home.display()
);
}
return Ok(PentestProcess::default());
}
cli::PentestAction::Update(cli::PentestUpdateArgs {
json,
from_embedded,
}) => {
let result = installer
.update(false, *from_embedded, source_override)
.map_err(install_error)?;
if *json {
println!("{}", serde_json::to_string(&result).unwrap());
}
return Ok(PentestProcess::default());
}
cli::PentestAction::Install { force } => {
let bundle = match find_pentest_source() {
Ok(source) => Bundle::source(&source).map_err(install_error)?,
Err(e) if source_override => return Err(e),
Err(_) => Bundle::embedded(),
};
Installer::new(home.parent().unwrap().to_path_buf(), bundle)
.update(*force, false, source_override)
.map_err(install_error)?;
if let Err(e) = check_pentest_dependencies(&home) {
eprintln!("{e}");
}
return Ok(PentestProcess::default());
}
_ => {}
}
let _lease = installer
.execution_lease(source_override)
.map_err(install_error)?;
let orchestrator = home.join("cxg_pentest.py");
let mut args: Vec<String> = vec![orchestrator.to_string_lossy().to_string()];
match cmd.action {
cli::PentestAction::Install { .. }
| cli::PentestAction::Update(_)
| cli::PentestAction::Status(_) => unreachable!(),
cli::PentestAction::Capabilities => {
args.push("capabilities".into());
}
cli::PentestAction::Auth {
target,
profile,
auth_numbers,
creds,
creds_file,
login_path,
label,
verify_url,
headers,
tier,
persona,
cohort,
tags,
target_type,
app_cmd,
app_binary,
auth_sub,
auth_dir: parent_auth_dir,
} => match auth_sub {
Some(cli::AuthSubcommand::Import {
profile,
target,
storage_state,
label,
tier,
persona,
cohort,
tags,
headers,
auth_dir,
liveness_path,
liveness_status,
service,
ci,
}) => {
args.extend([
"auth".into(),
"import".into(),
"--profile".into(),
profile,
"--target".into(),
target,
]);
if let Some(s) = storage_state {
args.extend(["--storage-state".into(), s]);
}
if let Some(l) = label {
args.extend(["--label".into(), l]);
}
if let Some(t) = tier {
args.extend(["--tier".into(), t]);
}
if let Some(p) = persona {
args.extend(["--persona".into(), p]);
}
if let Some(c) = cohort {
args.extend(["--cohort".into(), c]);
}
for t in tags {
args.extend(["--tag".into(), t]);
}
for h in headers {
args.extend(["--header".into(), h]);
}
if let Some(path) = liveness_path {
args.extend(["--liveness-path".into(), path]);
}
for status in liveness_status {
args.extend(["--liveness-status".into(), status.to_string()]);
}
if let Some(name) = service {
args.extend(["--service".into(), name]);
}
if let Some(d) = auth_dir.or(parent_auth_dir) {
args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
}
if ci {
args.push("--ci".into());
}
}
Some(cli::AuthSubcommand::Verify {
profile,
target,
me_path,
auth_dir,
}) => {
args.extend([
"auth".into(),
"verify".into(),
"--profile".into(),
profile,
"--me-path".into(),
me_path,
]);
if let Some(t) = target {
args.extend(["--target".into(), t]);
}
if let Some(d) = auth_dir.or(parent_auth_dir) {
args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
}
}
None => {
let (target, profile) = match (target, profile) {
(Some(t), Some(p)) => (t, p),
_ => {
eprintln!(
"error: `cxg pentest auth` (interactive capture) requires --target and --profile"
);
eprintln!(" (use `cxg pentest auth import`/`auth verify` for the non-interactive CI paths)");
return Err(Error::Config(
"missing --target/--profile for auth capture".to_string(),
));
}
};
args.extend([
"auth".into(),
"login".into(),
"--target".into(),
target,
"--profile".into(),
profile,
"--auth-numbers".into(),
auth_numbers.to_string(),
"--login-path".into(),
login_path,
]);
if let Some(d) = parent_auth_dir {
args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
}
if let Some(c) = creds {
args.extend(["--creds".into(), c]);
}
if let Some(f) = creds_file {
args.extend(["--creds-file".into(), f.to_string_lossy().to_string()]);
}
if let Some(l) = label {
args.extend(["--label".into(), l]);
}
if let Some(v) = verify_url {
args.extend(["--verify-url".into(), v]);
}
for h in headers {
args.extend(["--header".into(), h]);
}
if let Some(t) = tier {
args.extend(["--tier".into(), t]);
}
if let Some(p) = persona {
args.extend(["--persona".into(), p]);
}
if let Some(c) = cohort {
args.extend(["--cohort".into(), c]);
}
for t in tags {
args.extend(["--tag".into(), t]);
}
args.push("--target-type".into());
args.push(target_type);
if let Some(v) = app_cmd {
args.push("--app-cmd".into());
args.push(v);
}
if let Some(v) = app_binary {
args.push("--app-binary".into());
args.push(v);
}
}
},
cli::PentestAction::AuthList { auth_dir } => {
args.extend(["auth".into(), "list".into()]);
if let Some(d) = auth_dir {
args.extend(["--auth-dir".into(), d.to_string_lossy().to_string()]);
}
}
cli::PentestAction::ScopeInit { output } => {
args.extend([
"scope".into(),
"init".into(),
"--output".into(),
output.to_string_lossy().to_string(),
]);
}
cli::PentestAction::Run(cli::PentestRunArgs {
probe_inputs:
cli::ProbeInputs {
codebase,
auth,
scope_file,
session_dir,
auth_dir,
auth_inputs,
no_author,
},
target,
interactive_auth,
auth_profile,
auth_numbers,
creds_file,
template_lang,
goal,
threat_id,
template_dir,
max_templates,
mutation_retries,
ai_provider,
ai,
headed,
destructive_ok,
attestation,
output,
mitigation_mode,
me_path,
generation_timeout,
skip_health_check,
insecure_tls,
proxy,
client_cert,
client_key,
oast,
oast_interactsh,
oast_listener,
oast_listener_dns,
oast_redirect_location,
oast_redirect_status,
oast_dns_rebind_ip,
target_type,
app_cmd,
app_binary,
host_scan_path,
tauri_prove,
tauri_prove_timeout,
attacker_origin,
allow_raw_socket,
capture_http,
allow_grpc,
grpc_descriptor_set,
no_grpc_reflection,
discover_routes,
no_code_graph,
only_routes,
only_route,
skills_file,
enable_chaining,
batch_size,
deterministic_templates,
template_timeout,
stall_timeout,
no_restart,
ci,
}) => {
let mutation_retries = if no_author { 0 } else { mutation_retries };
let ai = ai && !no_author;
let deterministic_templates = deterministic_templates && !no_author;
args.push("pentest".into());
args.extend(["--codebase".into(), codebase.to_string_lossy().to_string()]);
if let Some(t) = target {
args.extend(["--target".into(), t]);
}
args.extend(["--auth".into(), auth]);
args.extend(["--interactive-auth".into(), interactive_auth.to_string()]);
args.extend(["--auth-profile".into(), auth_profile]);
if let Some(n) = auth_numbers {
args.extend(["--auth-numbers".into(), n.to_string()]);
}
if let Some(f) = creds_file {
args.extend(["--creds-file".into(), f.to_string_lossy().to_string()]);
}
args.extend(["--template-lang".into(), template_lang]);
if let Some(g) = goal {
args.extend(["--goal".into(), g]);
}
if let Some(id) = threat_id {
args.extend(["--threat-id".into(), id]);
}
if let Some(d) = template_dir {
args.extend(["--template-dir".into(), d.to_string_lossy().to_string()]);
}
if no_author {
args.push("--no-author".into());
}
args.extend(["--max-templates".into(), max_templates.to_string()]);
args.extend(["--mutation-retries".into(), mutation_retries.to_string()]);
args.extend(["--ai-provider".into(), ai_provider]);
if ai {
args.push("--ai".into());
}
if headed {
args.push("--headed".into());
}
if let Some(s) = scope_file {
args.extend(["--scope-file".into(), s.to_string_lossy().to_string()]);
}
if destructive_ok {
args.push("--destructive-ok".into());
}
if let Some(a) = attestation {
args.extend(["--attestation".into(), a]);
}
if let Some(s) = session_dir {
args.extend(["--session-dir".into(), s.to_string_lossy().to_string()]);
}
if let Some(o) = output {
args.extend(["--output".into(), o.to_string_lossy().to_string()]);
}
args.extend(["--mitigation-mode".into(), mitigation_mode]);
args.extend(["--me-path".into(), me_path]);
args.extend([
"--generation-timeout".into(),
generation_timeout.to_string(),
]);
if insecure_tls {
args.push("--insecure-tls".into());
}
if let Some(proxy) = proxy {
args.extend(["--proxy".into(), proxy]);
}
if let Some(cert) = client_cert {
args.extend(["--client-cert".into(), cert.to_string_lossy().to_string()]);
}
if let Some(key) = client_key {
args.extend(["--client-key".into(), key.to_string_lossy().to_string()]);
}
if skip_health_check {
args.push("--skip-health-check".into());
}
if let Some(h) = oast {
args.extend(["--oast".into(), h]);
}
if let Some(server) = oast_interactsh {
args.push("--oast-interactsh".into());
if !server.is_empty() {
args.push(server);
}
}
if let Some(bind) = oast_listener {
args.push("--oast-listener".into());
if !bind.is_empty() {
args.push(bind);
}
}
if oast_listener_dns {
args.push("--oast-listener-dns".into());
}
for (flag, value) in [
("--oast-redirect-location", oast_redirect_location),
("--oast-redirect-status", oast_redirect_status),
("--oast-dns-rebind-ip", oast_dns_rebind_ip),
] {
if let Some(value) = value {
args.push(flag.into());
args.push(value);
}
}
args.push("--target-type".into());
args.push(target_type);
if let Some(v) = app_cmd {
args.push("--app-cmd".into());
args.push(v);
}
if let Some(v) = app_binary {
args.push("--app-binary".into());
args.push(v);
}
if let Some(v) = host_scan_path {
args.push("--host-scan-path".into());
args.push(v);
}
if tauri_prove {
args.push("--tauri-prove".into());
args.extend([
"--tauri-prove-timeout".into(),
tauri_prove_timeout.to_string(),
]);
}
if attacker_origin {
args.push("--attacker-origin".into());
}
if allow_raw_socket {
args.push("--allow-raw-socket".into());
}
if capture_http {
args.push("--capture-http".into());
}
if allow_grpc {
args.push("--allow-grpc".into());
}
if let Some(v) = grpc_descriptor_set {
args.push("--grpc-descriptor-set".into());
args.push(v);
}
if no_grpc_reflection {
args.push("--no-grpc-reflection".into());
}
if discover_routes {
args.push("--discover-routes".into());
}
if no_code_graph {
args.push("--no-code-graph".into());
}
if let Some(f) = only_routes {
args.extend(["--only-routes".into(), f.to_string_lossy().to_string()]);
}
for entry in only_route {
args.extend(["--only-route".into(), entry]);
}
if let Some(f) = skills_file {
args.extend(["--skills-file".into(), f.to_string_lossy().to_string()]);
}
if enable_chaining {
args.push("--enable-chaining".into());
}
if let Some(path) = auth_inputs {
args.push("--auth-inputs".into());
args.push(path.display().to_string());
}
if batch_size > 1 {
args.push("--batch-size".into());
args.push(batch_size.to_string());
}
if deterministic_templates {
args.push("--deterministic-templates".into());
}
if let Some(v) = template_timeout {
args.push("--template-timeout".into());
args.push(v.to_string());
}
if let Some(v) = stall_timeout {
args.push("--stall-timeout".into());
args.push(v.to_string());
}
if no_restart {
args.push("--no-restart".into());
}
if let Some(d) = auth_dir {
args.push("--auth-dir".into());
args.push(d.to_string_lossy().to_string());
}
if ci {
args.push("--ci".into());
}
}
}
let python = check_pentest_dependencies(&home)?;
let mut process = SysCommand::new(&python);
process.args(&args);
if scan_dispatch {
process.arg("--scan-dispatch");
let log = process_log
.ok_or_else(|| Error::config("automatic probes require an engine session directory"))?;
process.stderr(std::fs::File::create(&log)?);
process.stdin(std::process::Stdio::inherit());
let status = process
.status()
.map_err(|e| Error::Config(format!("failed to spawn python orchestrator: {e}")))?;
let error = std::fs::read_to_string(log).unwrap_or_default();
use std::io::Write;
std::io::stderr().write_all(error.as_bytes())?;
return Ok(PentestProcess {
code: status.code().unwrap_or(1),
error,
});
}
let status = process
.status()
.map_err(|e| Error::Config(format!("failed to spawn python orchestrator: {e}")))?;
Ok(PentestProcess {
code: status.code().unwrap_or(1),
error: String::new(),
})
}
fn which_python() -> Result<PathBuf> {
if let Ok(p) = std::env::var("CXG_PYTHON") {
return Ok(PathBuf::from(p));
}
for candidate in &["python3", "python"] {
if std::process::Command::new(candidate)
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
{
return Ok(PathBuf::from(candidate));
}
}
Err(Error::Config(
"python3 not found on PATH (set CXG_PYTHON env var to override)".into(),
))
}
fn check_pentest_dependencies(home: &Path) -> Result<PathBuf> {
let python = which_python()?;
let check = std::process::Command::new(&python)
.args(["-c", "import playwright, yaml"])
.output();
if !check.is_ok_and(|out| out.status.success()) {
return Err(Error::Config(format!(
"Python dependency check failed for {}. Run: \"{}\" -m pip install -r \"{}\"; then \"{}\" -m playwright install chromium. No target was contacted.",
python.display(), python.display(), home.join("requirements.txt").display(), python.display()
)));
}
Ok(python)
}
fn find_pentest_source() -> Result<PathBuf> {
if let Ok(s) = std::env::var("CXG_SOURCE") {
let p = PathBuf::from(s).join("pentest");
if p.join("cxg_pentest.py").is_file() {
return Ok(p);
}
return Err(Error::Config(format!(
"CXG_SOURCE has no pentest bundle at {}",
p.display()
)));
}
if let Ok(exe) = std::env::current_exe() {
if let Some(parent) = exe.parent() {
for rel in &["pentest", "../pentest", "../share/cert-x-gen/pentest"] {
let p = parent.join(rel);
if p.join("cxg_pentest.py").exists() {
return Ok(p);
}
}
}
}
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let cwd_p = cwd.join("pentest");
if cwd_p.join("cxg_pentest.py").exists() {
return Ok(cwd_p);
}
Err(Error::Config(
"could not locate pentest source dir. Set CXG_SOURCE=<cxg-repo> to override.".into(),
))
}
async fn handle_auto_update(cli: &Cli) -> Result<()> {
use cert_x_gen::template::AutoUpdater;
let mut updater = AutoUpdater::new()?;
if cli.update_templates_on_startup {
tracing::info!("Forced template update on startup enabled");
updater.perform_update()?;
return Ok(());
}
if cli.auto_update_templates {
tracing::info!("Auto-updating templates before running...");
updater.perform_update()?;
return Ok(());
}
if cli.disable_update_check {
tracing::debug!("Auto-update checks disabled by user");
updater.disable_auto_check()?;
return Ok(());
}
if updater.needs_initial_install() {
updater.auto_install()?;
return Ok(());
}
if updater.should_check_for_updates() {
tracing::debug!("Checking for template updates...");
let _ = updater.check_for_updates(); }
Ok(())
}
async fn run_scan(args: cli::ScanArgs, config_path: Option<PathBuf>) -> Result<bool> {
let mut config = if let Some(path) = config_path {
Config::from_file(path)?
} else {
Config::default()
};
apply_scan_args_to_config(&mut config, &args);
tracing::info!("Starting CERT-X-GEN v{}", env!("CARGO_PKG_VERSION"));
tracing::info!("Configuration loaded and validated");
let engine = CertXGen::new(config.clone()).await?;
let (direct_template_paths, filter_ids) = if !args.templates.is_empty() {
tracing::debug!("Processing --templates argument: {:?}", args.templates);
separate_template_entries(&args.templates, &config.templates.directories)?
} else {
(Vec::new(), Vec::new())
};
let has_direct_paths = !direct_template_paths.is_empty();
let has_filter_ids = !filter_ids.is_empty();
tracing::info!("Loading templates...");
let mut discovery_issues = Vec::new();
let mut selection_error = None;
let templates: Vec<Box<dyn Template>> = if has_direct_paths {
tracing::info!(
"Loading {} template(s) from direct paths",
direct_template_paths.len()
);
let mut direct_templates: Vec<Box<dyn Template>> = Vec::new();
for path in &direct_template_paths {
tracing::debug!("Loading template from: {}", path.display());
match engine.template_loader().load_template(path).await {
Ok(template) => {
tracing::info!(
"Loaded template: {} ({}) from {}",
template.id(),
template.metadata().language,
path.display()
);
direct_templates.push(template);
}
Err(e) => {
tracing::error!("Failed to load template from {}: {}", path.display(), e);
return Err(Error::config(format!(
"Failed to load template '{}': {}",
path.display(),
e
)));
}
}
}
if direct_templates.is_empty() {
return Err(Error::config(
"No templates could be loaded from the specified paths.",
));
}
direct_templates
} else {
let mut discovered = engine.load_templates_with_report().await?;
discovery_issues = discovered.issues;
if has_filter_ids {
let mut matched_selectors = HashSet::new();
discovered.templates.retain(|template| {
let metadata = template.metadata();
let mut matched = false;
for filter_id in &filter_ids {
if metadata.id.eq_ignore_ascii_case(filter_id)
|| metadata.name.eq_ignore_ascii_case(filter_id)
|| metadata.file_path.to_string_lossy().contains(filter_id)
|| metadata
.file_path
.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|s| s.eq_ignore_ascii_case(filter_id))
{
matched_selectors.insert(filter_id);
matched = true;
}
}
matched
});
for filter_id in &filter_ids {
if !matched_selectors.contains(filter_id) {
tracing::warn!("Template not found: {}", filter_id);
}
}
if discovered.templates.is_empty() {
selection_error = Some(Error::config(format!(
"No templates found matching: {:?}. Use 'cxg template list' to see available templates.",
filter_ids
)));
}
}
discovered.templates
};
tracing::info!("Total templates to use: {}", templates.len());
for template in &templates {
let metadata = template.metadata();
tracing::debug!(
"Available template: {} ({})",
metadata.id,
metadata.language
);
}
if templates.is_empty() && discovery_issues.is_empty() {
return Err(selection_error.unwrap_or_else(|| {
Error::config("No templates loaded. Please add templates to the templates directory.")
}));
}
let no_templates_loaded =
templates.is_empty() && discovery_issues.iter().any(|issue| issue.error.is_some());
let mut targets = parse_targets(&args)?;
if targets.is_empty() {
return Err(Error::config(
"No scope provided. Use --scope (aliases: --target, --targets, --target-file, --domain, --cidr, etc.).",
));
}
tracing::info!("Parsed {} targets", targets.len());
let mut additional_ports = Vec::new();
if !args.ports.is_empty() {
additional_ports = parse_port_entries(&args.ports)?;
if !additional_ports.is_empty() {
targets = expand_targets_for_ports(targets, &additional_ports);
tracing::info!(
"Expanded to {} targets with additional ports: {:?}",
targets.len(),
additional_ports
);
}
}
let mut top_ports = Vec::new();
if let Some(count) = args.top_ports {
top_ports = select_top_ports(count);
if !top_ports.is_empty() {
targets = expand_targets_for_ports(targets, &top_ports);
tracing::info!(
"Expanded to {} targets with top ports: {:?}",
targets.len(),
top_ports
);
}
}
let skip_id_filter = has_direct_paths || has_filter_ids;
let filter = create_template_filter(&args, skip_id_filter)?;
if !filter.ids.is_empty() {
tracing::info!("Filtering templates by IDs: {:?}", filter.ids);
}
if !filter.tags.is_empty() {
tracing::info!("Filtering templates by tags: {:?}", filter.tags);
}
if !filter.severities.is_empty() {
tracing::info!("Filtering templates by severities: {:?}", filter.severities);
}
if !filter.languages.is_empty() {
tracing::info!("Filtering templates by languages: {:?}", filter.languages);
}
if !filter.exclude_ids.is_empty() {
tracing::info!("Excluding templates: {:?}", filter.exclude_ids);
}
let mut job = engine.create_scan_job(targets, templates);
let templates_before = job.templates.len();
job.filter_templates(&filter);
if args.safe {
let dangerous_tags = [
"dos",
"resource-exhaustion",
"intrusive",
"destructive",
"brute-force",
"exploit",
];
let before_safe = job.templates.len();
job.templates.retain(|template| {
let metadata = template.metadata();
!dangerous_tags
.iter()
.any(|tag| metadata.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)))
});
let after_safe = job.templates.len();
if before_safe != after_safe {
tracing::info!(
"Safe mode: Excluded {} dangerous templates (DoS, resource-exhaustion, etc.)",
before_safe - after_safe
);
}
}
if args.passive {
let active_tags = ["active", "probe", "intrusive", "exploit"];
let before_passive = job.templates.len();
job.templates.retain(|template| {
let metadata = template.metadata();
let has_passive_tag = metadata
.tags
.iter()
.any(|t| t.eq_ignore_ascii_case("passive"));
let has_active_tag = active_tags
.iter()
.any(|tag| metadata.tags.iter().any(|t| t.eq_ignore_ascii_case(tag)));
has_passive_tag || !has_active_tag
});
let after_passive = job.templates.len();
if before_passive != after_passive {
tracing::info!(
"Passive mode: Excluded {} active probe templates",
before_passive - after_passive
);
}
}
let templates_after = job.templates.len();
tracing::info!(
"Templates selected: {} (total available: {})",
templates_after,
templates_before
);
if templates_after > 0 && templates_after <= 10 {
for template in &job.templates {
tracing::info!(
" - {} ({})",
template.metadata().id,
template.metadata().language
);
}
}
if !additional_ports.is_empty() || !top_ports.is_empty() {
let mut combined = additional_ports.clone();
combined.extend(top_ports.iter().copied());
combined.sort_unstable();
combined.dedup();
job.context.additional_ports = combined;
tracing::info!(
"Adding {} additional ports to scan (custom + top): {:?}",
job.context.additional_ports.len(),
job.context.additional_ports
);
}
if let Some(ref override_ports) = args.override_ports {
let override_ports = parse_ports(override_ports)?;
job.context.override_ports = Some(override_ports.clone());
tracing::info!(
"Overriding template default ports with: {:?}",
override_ports
);
}
if let Some(ref context_json) = args.context {
match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(context_json) {
Ok(map) => {
for (key, value) in map {
let str_value = match value {
serde_json::Value::String(s) => s,
other => other.to_string(),
};
job.context.variables.insert(key, str_value);
}
tracing::info!(
"Injected {} context variables from --context flag",
job.context.variables.len()
);
}
Err(e) => {
tracing::warn!(
"Failed to parse --context JSON '{}': {}. Context variables not set.",
context_json,
e
);
}
}
}
apply_probe_input(&args, &mut job.context)?;
let (probe_templates, scanner_templates): (Vec<_>, Vec<_>) = std::mem::take(&mut job.templates)
.into_iter()
.partition(|template| template.is_js_probe());
job.templates = scanner_templates;
let has_probes = !probe_templates.is_empty();
if !has_probes
&& (!args.probe_inputs.auth.is_empty()
|| args.probe_inputs.scope_file.is_some()
|| args.probe_inputs.auth_inputs.is_some())
{
return Err(Error::config("--auth, --auth-inputs and --scope-file apply to JS probes; no probe-contract templates were selected"));
}
tracing::info!(
"Scan job created: {} targets × {} templates = {} total checks",
job.targets.len(),
job.templates.len(),
job.total_work_units()
);
let mut plugin_manager = PluginManager::new();
plugin_manager.register(Arc::new(LoggingPlugin::new()));
plugin_manager.notify_scan_start(job.id);
if let Some(progress) = get_progress().filter(|_| !job.templates.is_empty()) {
progress.init(job.targets.len(), job.templates.len());
}
tracing::info!("Starting scan execution...");
let start = std::time::Instant::now();
let mut results = if job.templates.is_empty() {
let mut results = cert_x_gen::types::ScanResults::new(job.id);
results.statistics.network_requests = Some(0);
results.complete();
results
} else {
engine.execute_scan(job).await?
};
results.add_discovery_issues(discovery_issues);
let probe_exit = if has_probes {
for finding in &mut results.findings {
finding.verdict_source = Some("template-reported".into());
}
let code = scan_probes::execute(&args, probe_templates, &mut results).await?;
results.complete();
code
} else {
0
};
let duration = start.elapsed();
if let Some(progress) = get_progress() {
progress.finish();
}
tracing::info!("Scan completed in {:.2}s", duration.as_secs_f64());
tracing::info!("Found {} total findings", results.findings.len());
plugin_manager.notify_scan_complete(&results);
let output_manager = OutputManager::new();
let mut formats: Vec<String> = args
.output_format
.split(',')
.map(|s| s.trim().to_string())
.collect();
if has_probes && !formats.iter().any(|format| format == "json") {
formats.push("json".into());
}
let output_path = PathBuf::from(&args.output);
output_manager.write_results(&results, &output_path, &formats)?;
print_scan_summary(&results);
maybe_print_star_nag(args.quiet);
if let Some(error) = selection_error {
return Err(error);
}
if probe_exit != 0 {
use std::io::Write;
std::io::stdout().flush()?;
std::process::exit(probe_exit);
}
let gate_failed = results.executions.iter().any(|execution| {
args.fail_on
.iter()
.any(|status| status.status() == execution.status)
});
if no_templates_loaded && !gate_failed {
return Err(Error::config(
"No templates could be loaded from the specified directories.",
));
}
Ok(gate_failed)
}
fn apply_scan_args_to_config(config: &mut Config, args: &cli::ScanArgs) {
config.execution.parallel_targets = args.parallel_targets;
config.execution.parallel_templates = args.parallel_templates;
config.execution.max_retries = args.retry;
config.execution.aggressive_mode = args.aggressive;
config.execution.stealth_mode = args.stealth;
if args.aggressive {
config.execution.parallel_targets *= 2;
config.execution.parallel_templates *= 2;
config.execution.max_retries *= 2;
config.network.rate_limit = None; tracing::info!("Aggressive mode: Increased concurrency and retries, removed rate limits");
}
if args.stealth {
config.execution.parallel_targets = std::cmp::max(1, config.execution.parallel_targets / 3);
config.execution.parallel_templates =
std::cmp::max(1, config.execution.parallel_templates / 2);
if config.network.rate_limit.is_none() {
config.network.rate_limit = Some(10);
}
if args.user_agent.is_none() {
config.network.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36".to_string();
}
tracing::info!(
"Stealth mode: Reduced concurrency, enforced rate limiting, using browser user agent"
);
}
if args.passive {
config.execution.parallel_targets = std::cmp::max(1, config.execution.parallel_targets / 5);
config.execution.parallel_templates = 1; tracing::info!("Passive mode: Minimal concurrency, sequential template execution");
}
if args.safe {
config.execution.parallel_targets =
std::cmp::max(1, (config.execution.parallel_targets * 3) / 4);
config.execution.parallel_templates =
std::cmp::max(1, (config.execution.parallel_templates * 3) / 4);
if config.network.rate_limit.is_none() {
config.network.rate_limit = Some(50);
}
tracing::info!("Safe mode: Reduced concurrency, rate limiting enabled");
}
match utils::parse_duration(&args.timeout) {
Ok(duration) => {
config.network.timeout_secs = duration.as_secs();
if duration.as_secs() > 0 {
config.templates.timeout_secs = duration.as_secs();
}
}
Err(e) => {
tracing::warn!(
"Failed to parse timeout '{}': {}. Using default.",
args.timeout,
e
);
}
}
if let Some(proxy) = &args.proxy {
config.network.proxy = Some(proxy.clone());
}
if let Some(user_agent) = &args.user_agent {
config.network.user_agent = user_agent.clone();
}
config.network.follow_redirects = args.follow_redirects;
config.network.max_redirects = args.max_redirects;
if let Some(rate_limit) = args.rate_limit {
config.network.rate_limit = Some(rate_limit);
}
if let Some(template_dir) = &args.template_dir {
config.templates.directories = vec![template_dir.clone()];
}
if let Some(headers) = &args.header {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
config
.network
.headers
.push((key.trim().to_string(), value.trim().to_string()));
}
}
}
if let Some(cookies) = &args.cookie {
for cookie in cookies {
if let Some((key, value)) = cookie.split_once('=') {
config
.network
.cookies
.push((key.trim().to_string(), value.trim().to_string()));
}
}
if !config.network.cookies.is_empty() {
tracing::info!(
"Using {} cookie(s) for authenticated scanning",
config.network.cookies.len()
);
}
}
}
fn expand_targets_for_ports(targets: Vec<Target>, ports: &[u16]) -> Vec<Target> {
if ports.is_empty() {
return targets;
}
let mut expanded = Vec::new();
for target in targets {
if target.port.is_some() {
expanded.push(target.clone());
}
for &port in ports {
if target.port == Some(port) {
continue;
}
let mut new_target = target.clone();
new_target.port = Some(port);
expanded.push(new_target);
}
}
expanded
}
fn apply_probe_input(args: &cli::ScanArgs, context: &mut cert_x_gen::types::Context) -> Result<()> {
if !args.arg.is_empty() {
context.probe_argv = args.arg.clone();
tracing::info!(
"Probe argv: {} argument(s) delivered as CERT_X_GEN_ARGV",
context.probe_argv.len()
);
}
if let Some(ref path) = args.stdin_file {
if !path.is_file() {
return Err(Error::config(format!(
"--stdin-file '{}' is not a readable file",
path.display()
)));
}
let resolved = path.canonicalize().unwrap_or_else(|_| path.clone());
tracing::info!("Probe stdin file: {}", resolved.display());
context.probe_stdin_file = Some(resolved);
}
if let Some(ref path) = args.input {
if !path.is_dir() {
return Err(Error::config(format!(
"--input '{}' is not a directory",
path.display()
)));
}
let resolved = path.canonicalize().unwrap_or_else(|_| path.clone());
tracing::info!("Probe input dir: {}", resolved.display());
context.probe_input_dir = Some(resolved);
}
for kv in &args.target_env {
let Some((key, value)) = kv.split_once('=') else {
return Err(Error::config(format!(
"--target-env '{}' is not KEY=VALUE",
kv
)));
};
if key.is_empty() {
return Err(Error::config(format!(
"--target-env '{}' has an empty key",
kv
)));
}
context.probe_env.push((key.to_string(), value.to_string()));
}
if !context.probe_env.is_empty() {
tracing::info!(
"Probe target environment: {} variable(s) delivered as CERT_X_GEN_TARGET_ENV",
context.probe_env.len()
);
}
context.require_instrumentation = args.require_instrumentation;
if context.require_instrumentation {
tracing::info!(
"Instrumentation preflight enabled: against a cli:// target with no detectable \
instrumentation, a template whose oracles needed it is skipped rather than \
reported as no-findings"
);
}
for path in &args.instrumented_manifest {
let (binary, instrumentation) = read_instrumented_manifest(path)?;
tracing::info!(
"Instrumentation provenance for {}: {} (from {})",
binary,
instrumentation.join(","),
path.display()
);
context
.instrumentation_provenance
.insert(binary, instrumentation);
}
Ok(())
}
fn read_instrumented_manifest(path: &std::path::Path) -> Result<(String, Vec<String>)> {
use cert_x_gen::build::Manifest;
let raw = std::fs::read_to_string(path).map_err(|e| {
Error::config(format!(
"--instrumented-manifest '{}' is not readable: {e}",
path.display()
))
})?;
let manifest: Manifest = serde_json::from_str(&raw).map_err(|e| {
Error::config(format!(
"--instrumented-manifest '{}' is not a cxg build manifest: {e}",
path.display()
))
})?;
match manifest {
Manifest::Instrumented(built) => {
let binary = built
.binary
.canonicalize()
.unwrap_or_else(|_| built.binary.clone());
if built.instrumentation.is_empty() {
return Err(Error::config(format!(
"--instrumented-manifest '{}' records no instrumentation for {}",
path.display(),
built.binary.display()
)));
}
Ok((binary.to_string_lossy().to_string(), built.instrumentation))
}
Manifest::Skipped(skipped) => Err(Error::config(format!(
"--instrumented-manifest '{}' records a build that was SKIPPED ({}); there is no \
instrumented binary to trust",
path.display(),
skipped.reason
))),
}
}
fn canonical_cli_path(path: &str) -> String {
std::fs::canonicalize(path)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| path.to_string())
}
fn parse_target_string(target_str: &str) -> Target {
if let Some(rest) = target_str
.strip_prefix("cli://")
.or_else(|| target_str.strip_prefix("cli:"))
{
return Target::new(canonical_cli_path(rest), Protocol::Cli);
}
if let Ok(url) = url::Url::parse(target_str) {
if let Some(host) = url.host_str() {
let protocol = match url.scheme().to_lowercase().as_str() {
"http" => Protocol::Http,
"https" => Protocol::Https,
"tcp" => Protocol::Tcp,
"udp" => Protocol::Udp,
other => Protocol::Custom(other.to_string()),
};
let mut target = Target::new(host, protocol);
if let Some(port) = url.port() {
target.port = Some(port);
}
return target;
}
}
match utils::parse_target(target_str) {
Ok((host, port)) => {
if let Some(port) = port {
let protocol = match port {
80 | 8000 | 8080 => Protocol::Http,
443 | 8443 => Protocol::Https,
_ => Protocol::Https,
};
Target::with_port(host, port, protocol)
} else {
Target::new(host, Protocol::Https)
}
}
Err(_) => Target::new(target_str, Protocol::Https),
}
}
fn parse_targets(args: &cli::ScanArgs) -> Result<Vec<Target>> {
let mut expanded_entries = Vec::new();
let mut in_progress_files = HashSet::new();
for entry in &args.scope {
expand_scope_entry(entry, &mut expanded_entries, &mut in_progress_files)?;
}
let mut seen = HashSet::new();
let mut targets = Vec::new();
for raw in expanded_entries {
let trimmed = raw.trim();
if trimmed.is_empty() {
continue;
}
if !seen.insert(trimmed.to_string()) {
continue;
}
targets.push(parse_target_string(trimmed));
}
Ok(targets)
}
fn expand_scope_entry(
entry: &str,
acc: &mut Vec<String>,
file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
let trimmed = entry.trim();
if trimmed.is_empty() {
return Ok(());
}
if trimmed.starts_with("cli://") || trimmed.starts_with("cli:") {
acc.push(trimmed.to_string());
return Ok(());
}
if trimmed.contains(',') {
for part in trimmed.split(',') {
expand_scope_entry(part, acc, file_stack)?;
}
return Ok(());
}
let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file://") {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file:") {
(rest, true)
} else {
(trimmed, false)
};
let path = Path::new(candidate);
if forced_file || path.exists() {
if !path.exists() {
return Err(Error::config(format!(
"Scope file not found: {}",
candidate
)));
}
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if !file_stack.insert(canonical.clone()) {
return Err(Error::config(format!(
"Recursive scope file reference detected: {}",
canonical.display()
)));
}
let content = fs::read_to_string(path).map_err(|e| {
Error::config(format!("Failed to read scope file '{}': {}", candidate, e))
})?;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
expand_scope_entry(line, acc, file_stack)?;
}
file_stack.remove(&canonical);
return Ok(());
}
if trimmed.contains('/') && !trimmed.contains("://") {
if let Ok(addresses) = utils::parse_cidr(trimmed) {
for ip in addresses {
acc.push(ip.to_string());
}
return Ok(());
}
}
acc.push(trimmed.to_string());
Ok(())
}
fn create_template_filter(args: &cli::ScanArgs, skip_id_filter: bool) -> Result<TemplateFilter> {
let mut filter = TemplateFilter::new();
if !skip_id_filter && !args.templates.is_empty() {
let template_entries = parse_template_entries(&args.templates)?;
filter.ids.extend(template_entries);
}
if let Some(tags) = &args.tags {
filter.tags = tags.split(',').map(|s| s.trim().to_string()).collect();
}
if let Some(severities) = &args.severity {
filter.severities = severities.iter().map(|s| (*s).into()).collect();
}
if let Some(languages) = &args.template_language {
filter.languages = languages.iter().map(|l| (*l).into()).collect();
}
if let Some(exclude) = &args.exclude_templates {
for pattern in exclude.split(',') {
filter.exclude_ids.push(pattern.trim().to_string());
}
}
if let Some(bg) = &args.batch_group {
filter.batch_group = Some(bg.clone());
}
Ok(filter)
}
fn parse_ports(port_spec: &str) -> Result<Vec<u16>> {
let mut ports = Vec::new();
for part in port_spec.split(',') {
let part = part.trim();
if part.contains('-') {
let range_parts: Vec<&str> = part.split('-').collect();
if range_parts.len() != 2 {
return Err(Error::config(format!("Invalid port range: {}", part)));
}
let start: u16 = range_parts[0]
.trim()
.parse()
.map_err(|_| Error::config(format!("Invalid port number: {}", range_parts[0])))?;
let end: u16 = range_parts[1]
.trim()
.parse()
.map_err(|_| Error::config(format!("Invalid port number: {}", range_parts[1])))?;
if start > end {
return Err(Error::config(format!(
"Invalid port range: {} > {}",
start, end
)));
}
for port in start..=end {
ports.push(port);
}
} else {
let port: u16 = part
.parse()
.map_err(|_| Error::config(format!("Invalid port number: {}", part)))?;
ports.push(port);
}
}
ports.sort_unstable();
ports.dedup();
Ok(ports)
}
fn parse_port_entries(entries: &[String]) -> Result<Vec<u16>> {
let mut collected = Vec::new();
let mut file_stack = HashSet::new();
for entry in entries {
expand_port_entry(entry, &mut collected, &mut file_stack)?;
}
collected.sort_unstable();
collected.dedup();
Ok(collected)
}
fn expand_port_entry(
entry: &str,
acc: &mut Vec<u16>,
file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
let trimmed = entry.trim();
if trimmed.is_empty() {
return Ok(());
}
if trimmed.contains(',') {
for part in trimmed.split(',') {
expand_port_entry(part, acc, file_stack)?;
}
return Ok(());
}
let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file://") {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file:") {
(rest, true)
} else {
(trimmed, false)
};
let path = Path::new(candidate);
if forced_file || path.exists() {
if !path.exists() {
return Err(Error::config(format!("Port file not found: {}", candidate)));
}
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if !file_stack.insert(canonical.clone()) {
return Err(Error::config(format!(
"Recursive port file reference detected: {}",
canonical.display()
)));
}
let content = fs::read_to_string(path).map_err(|e| {
Error::config(format!("Failed to read port file '{}': {}", candidate, e))
})?;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
expand_port_entry(line, acc, file_stack)?;
}
file_stack.remove(&canonical);
return Ok(());
}
acc.extend(parse_ports(trimmed)?);
Ok(())
}
fn select_top_ports(count: u16) -> Vec<u16> {
utils::top_ports(count)
}
fn is_template_source_file(path: &Path) -> bool {
match path.extension().and_then(|ext| ext.to_str()) {
Some(ext) => matches!(
ext.to_ascii_lowercase().as_str(),
"yaml" | "yml" | "py" | "js" | "rs" | "c" | "cpp" | "cc" | "cxx" | "java" | "go" | "rb" | "pl" | "php" | "sh" | "bash" ),
None => false,
}
}
fn separate_template_entries(
entries: &[String],
template_dirs: &[PathBuf],
) -> Result<(Vec<PathBuf>, Vec<String>)> {
let mut direct_paths = Vec::new();
let mut filter_ids = Vec::new();
tracing::debug!(
"Separating {} template entries (template_dirs: {:?})",
entries.len(),
template_dirs
);
for entry in entries {
let trimmed = entry.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.contains(',') {
for part in trimmed.split(',') {
let (mut paths, mut ids) =
separate_template_entries(&[part.to_string()], template_dirs)?;
direct_paths.append(&mut paths);
filter_ids.append(&mut ids);
}
continue;
}
let path = Path::new(trimmed);
let exists = path.exists();
let is_file = path.is_file();
let is_template = is_template_source_file(path);
let is_abs = path.is_absolute();
tracing::debug!(
"Entry '{}': exists={}, is_file={}, is_template={}, is_absolute={}",
trimmed,
exists,
is_file,
is_template,
is_abs
);
if exists && is_file && is_template {
tracing::info!("Detected direct template path: {}", trimmed);
direct_paths.push(path.to_path_buf());
} else if is_abs && is_template && !exists {
return Err(Error::config(format!(
"Template file not found: {}",
trimmed
)));
} else if !is_abs && (trimmed.contains('/') || trimmed.contains('\\')) && is_template {
let mut found = false;
for template_dir in template_dirs {
let resolved_path = template_dir.join(trimmed);
tracing::debug!(
"Trying to resolve relative path: {} -> {}",
trimmed,
resolved_path.display()
);
if resolved_path.exists() && resolved_path.is_file() {
tracing::info!(
"Resolved relative template path: {} -> {}",
trimmed,
resolved_path.display()
);
direct_paths.push(resolved_path);
found = true;
break;
}
}
if !found {
let searched_dirs: Vec<String> = template_dirs
.iter()
.map(|d| d.display().to_string())
.collect();
return Err(Error::config(format!(
"Template file not found: {} (searched in: {})",
trimmed,
if searched_dirs.is_empty() {
"current directory".to_string()
} else {
searched_dirs.join(", ")
}
)));
}
} else {
tracing::debug!("Treating as filter ID: {}", trimmed);
filter_ids.push(trimmed.to_string());
}
}
tracing::info!(
"Separated template entries: {} direct paths, {} filter IDs",
direct_paths.len(),
filter_ids.len()
);
Ok((direct_paths, filter_ids))
}
fn parse_template_entries(entries: &[String]) -> Result<Vec<String>> {
let mut collected = Vec::new();
let mut file_stack = HashSet::new();
for entry in entries {
expand_template_entry(entry, &mut collected, &mut file_stack)?;
}
let mut seen = HashSet::new();
let mut unique = Vec::new();
for entry in collected {
if seen.insert(entry.clone()) {
unique.push(entry);
}
}
Ok(unique)
}
fn expand_template_entry(
entry: &str,
acc: &mut Vec<String>,
file_stack: &mut HashSet<PathBuf>,
) -> Result<()> {
let trimmed = entry.trim();
if trimmed.is_empty() {
return Ok(());
}
if trimmed.contains(',') {
for part in trimmed.split(',') {
expand_template_entry(part, acc, file_stack)?;
}
return Ok(());
}
let (candidate, forced_file) = if let Some(rest) = trimmed.strip_prefix('@') {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file://") {
(rest, true)
} else if let Some(rest) = trimmed.strip_prefix("file:") {
(rest, true)
} else {
(trimmed, false)
};
let path = Path::new(candidate);
if forced_file || (path.exists() && path.is_file() && is_template_list_file(path)) {
if !path.exists() {
return Err(Error::config(format!(
"Template list file not found: {}",
candidate
)));
}
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if !file_stack.insert(canonical.clone()) {
return Err(Error::config(format!(
"Recursive template file reference detected: {}",
canonical.display()
)));
}
let content = fs::read_to_string(path).map_err(|e| {
Error::config(format!(
"Failed to read template list '{}': {}",
candidate, e
))
})?;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
expand_template_entry(line, acc, file_stack)?;
}
file_stack.remove(&canonical);
return Ok(());
}
acc.push(trimmed.to_string());
Ok(())
}
fn is_template_list_file(path: &Path) -> bool {
match path.extension().and_then(|ext| ext.to_str()) {
Some(ext) => matches!(
ext.to_ascii_lowercase().as_str(),
"txt" | "list" | "lst" | "cfg"
),
None => false,
}
}
async fn run_validate_command(
path: PathBuf,
recursive: bool,
_show_score: bool,
strict: bool,
format: String,
_summary: bool,
_language: Option<cli::LanguageArg>,
_min_score: u8,
) -> Result<()> {
use cert_x_gen::ai::validator::{DiagnosticSeverity, TemplateDiagnostic};
use console::style;
use std::fs;
println!("{}", style("═".repeat(80)).dim());
println!("{}", style("CERT-X-GEN Template Validator").bold().cyan());
println!("{}", style("═".repeat(80)).dim());
println!();
let validator = TemplateValidator::new();
let mut template_files = Vec::new();
if path.is_file() {
template_files.push(path.clone());
} else if path.is_dir() {
if recursive {
for entry in walkdir::WalkDir::new(&path)
.into_iter()
.filter_map(|e| e.ok())
{
let entry_path = entry.path();
if entry_path.is_file() {
if let Some(ext) = entry_path.extension() {
let ext_str = ext.to_string_lossy();
if [
"py", "js", "sh", "rb", "pl", "php", "rs", "c", "cpp", "go", "java",
"yaml", "yml",
]
.contains(&ext_str.as_ref())
{
template_files.push(entry_path.to_path_buf());
}
}
}
}
} else if let Ok(entries) = fs::read_dir(&path) {
for entry in entries.filter_map(|e| e.ok()) {
let entry_path = entry.path();
if entry_path.is_file() {
if let Some(ext) = entry_path.extension() {
let ext_str = ext.to_string_lossy();
if [
"py", "js", "sh", "rb", "pl", "php", "rs", "c", "cpp", "go", "java",
"yaml", "yml",
]
.contains(&ext_str.as_ref())
{
template_files.push(entry_path);
}
}
}
}
}
}
if template_files.is_empty() {
println!("{}", style("No template files found!").red().bold());
return Ok(());
}
println!(
"Found {} template(s) to validate",
style(template_files.len()).cyan().bold()
);
println!();
#[derive(serde::Serialize)]
struct ValidationResult {
template_path: String,
language: Option<TemplateLanguage>,
passed: bool,
diagnostics: Vec<TemplateDiagnostic>,
error: Option<String>,
}
let mut results = Vec::new();
let mut passed_count = 0;
let mut failed_count = 0;
for template_path in &template_files {
let content = match fs::read_to_string(template_path) {
Ok(c) => c,
Err(e) => {
let msg = format!("Failed to read file: {}", e);
let diag = TemplateDiagnostic {
code: "io.read_error".to_string(),
message: msg.clone(),
severity: DiagnosticSeverity::Error,
line: None,
column: None,
};
let result = ValidationResult {
template_path: template_path.display().to_string(),
language: None,
passed: false,
diagnostics: vec![diag],
error: Some(msg),
};
results.push(result);
failed_count += 1;
continue;
}
};
let language = match template_path.extension().and_then(|e| e.to_str()) {
Some("py") => TemplateLanguage::Python,
Some("js") => TemplateLanguage::JavaScript,
Some("sh") => TemplateLanguage::Shell,
Some("rb") => TemplateLanguage::Ruby,
Some("pl") => TemplateLanguage::Perl,
Some("php") => TemplateLanguage::Php,
Some("rs") => TemplateLanguage::Rust,
Some("c") => TemplateLanguage::C,
Some("cpp") | Some("cc") | Some("cxx") => TemplateLanguage::Cpp,
Some("go") => TemplateLanguage::Go,
Some("java") => TemplateLanguage::Java,
Some("yaml") | Some("yml") => TemplateLanguage::Yaml,
_ => {
let msg = "Unknown file extension".to_string();
let diag = TemplateDiagnostic {
code: "template.unknown_extension".to_string(),
message: msg.clone(),
severity: DiagnosticSeverity::Error,
line: None,
column: None,
};
let result = ValidationResult {
template_path: template_path.display().to_string(),
language: None,
passed: false,
diagnostics: vec![diag],
error: Some(msg),
};
results.push(result);
failed_count += 1;
continue;
}
};
let mut diagnostics =
match validator.validate_with_diagnostics(&content, language, Some(template_path)) {
Ok(diags) => diags,
Err(e) => {
vec![TemplateDiagnostic {
code: "validator.internal_error".to_string(),
message: e.to_string(),
severity: DiagnosticSeverity::Error,
line: None,
column: None,
}]
}
};
if let TemplateLanguage::Yaml = language {
if let Ok(yaml_value) = serde_yaml::from_str::<serde_yaml::Value>(&content) {
if let Some(id_val) = yaml_value.get("id").and_then(|v| v.as_str()) {
if let Some(stem) = template_path.file_stem().and_then(|s| s.to_str()) {
if id_val != stem {
let line = content
.lines()
.enumerate()
.find(|(_, line)| line.contains("id:"))
.map(|(idx, _)| idx + 1);
diagnostics.push(TemplateDiagnostic {
code: "yaml.id_filename_mismatch".to_string(),
message: format!(
"YAML template id '{}' does not match filename '{}'. For best results, keep them aligned.",
id_val, stem
),
severity: DiagnosticSeverity::Warning,
line,
column: None,
});
}
}
}
}
}
let has_error = diagnostics
.iter()
.any(|d| matches!(d.severity, DiagnosticSeverity::Error));
let error_summary = if has_error {
let messages: Vec<String> = diagnostics
.iter()
.filter(|d| matches!(d.severity, DiagnosticSeverity::Error))
.map(|d| format!("{}: {}", d.code, d.message))
.collect();
if messages.is_empty() {
None
} else {
Some(messages.join(" | "))
}
} else {
None
};
let result = ValidationResult {
template_path: template_path.display().to_string(),
language: Some(language),
passed: !has_error,
diagnostics,
error: error_summary,
};
if result.passed {
passed_count += 1;
} else {
failed_count += 1;
}
results.push(result);
}
match format.as_str() {
"json" => {
println!("{}", serde_json::to_string_pretty(&results)?);
}
"table" | "text" => {
for result in &results {
let filename = PathBuf::from(&result.template_path)
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
if result.passed {
println!("{} {}", style("✓").green().bold(), style(&filename).green());
} else {
println!("{} {}", style("✗").red().bold(), style(&filename).red());
}
for diag in &result.diagnostics {
let sev_label = match diag.severity {
DiagnosticSeverity::Error => style("error").red().bold(),
DiagnosticSeverity::Warning => style("warning").yellow().bold(),
DiagnosticSeverity::Info => style("info").blue().bold(),
};
let location = match (diag.line, diag.column) {
(Some(line), Some(col)) => format!("{}:{}: ", line, col),
(Some(line), None) => format!("{}: ", line),
_ => String::new(),
};
println!(
" [{}] {}{}: {}",
sev_label, location, diag.code, diag.message
);
}
if !result.diagnostics.is_empty() {
println!();
}
}
println!();
println!("{}", style("═".repeat(80)).dim());
println!("{}", style("Validation Summary").bold().cyan());
println!("{}", style("═".repeat(80)).dim());
println!();
println!(" Total Templates: {}", style(results.len()).bold());
println!(
" {} {}",
style("✓").green().bold(),
style(format!("Passed: {}", passed_count)).green()
);
println!(
" {} {}",
style("✗").red().bold(),
style(format!("Failed: {}", failed_count)).red()
);
if !results.is_empty() {
println!(
" Success Rate: {}%",
style(passed_count * 100 / results.len()).bold()
);
}
println!();
}
_ => {
eprintln!("Unknown format: {}", format);
return Err(Error::Validation(format!("Invalid format: {}", format)));
}
}
if strict && failed_count > 0 {
return Err(Error::Validation(format!(
"{} template(s) failed validation",
failed_count
)));
}
Ok(())
}
async fn run_template_command(cmd: cli::TemplateCommand) -> Result<()> {
use cli::TemplateAction;
match cmd.action {
TemplateAction::List {
language,
severity,
tags,
batch_group,
} => {
let config = Config::default();
let engine = CertXGen::new(config).await?;
let templates = engine.load_templates().await?;
let mut filtered_templates = templates;
if let Some(lang) = language {
let target_language: cert_x_gen::types::TemplateLanguage = lang.into();
filtered_templates
.retain(|template| template.metadata().language == target_language);
}
if let Some(sev) = severity {
let target_severity: cert_x_gen::types::Severity = sev.into();
filtered_templates
.retain(|template| template.metadata().severity == target_severity);
}
if let Some(tag_filter) = tags {
let target_tags: Vec<String> = tag_filter
.split(',')
.map(|s| s.trim().to_string())
.collect();
filtered_templates.retain(|template| {
target_tags
.iter()
.any(|tag| template.metadata().tags.contains(tag))
});
}
if let Some(bg) = batch_group {
filtered_templates.retain(|template| {
template
.metadata()
.batch_group
.as_deref()
.map(|g| g.eq_ignore_ascii_case(&bg))
.unwrap_or(false)
});
}
println!("Found {} templates:", filtered_templates.len());
println!();
for template in filtered_templates {
let metadata = template.metadata();
println!("ID: {}", metadata.id);
println!("Name: {}", metadata.name);
println!("Language: {:?}", metadata.language);
println!("Severity: {:?}", metadata.severity);
println!("Author: {}", metadata.author.name);
println!("Description: {}", metadata.description);
println!("Tags: {}", metadata.tags.join(", "));
println!("File: {}", metadata.file_path.display());
println!("---");
}
Ok(())
}
TemplateAction::Validate {
path,
recursive,
json,
} => {
let format = if json {
"json".to_string()
} else {
"text".to_string()
};
run_validate_command(
path, recursive, false, true, format, false, None, 0, )
.await?;
Ok(())
}
TemplateAction::Update { force: _ } => {
use cert_x_gen::template::AutoUpdater;
let mut updater = AutoUpdater::new()
.map_err(|e| Error::config(format!("Failed to initialize updater: {}", e)))?;
if updater.needs_initial_install() {
updater
.auto_install()
.map_err(|e| Error::config(format!("Failed to install templates: {}", e)))?;
} else {
updater
.perform_update()
.map_err(|e| Error::config(format!("Failed to update templates: {}", e)))?;
let stats = updater.get_stats();
println!();
println!("✅ Templates ready: {}", stats.summary());
}
Ok(())
}
TemplateAction::Info { template_id } => {
let config = Config::default();
let engine = CertXGen::new(config).await?;
let templates = engine.load_templates().await?;
let matching: Vec<_> = templates
.iter()
.filter(|t| t.id().to_lowercase().contains(&template_id.to_lowercase()))
.collect();
if matching.is_empty() {
println!("❌ No template found matching: {}", template_id);
println!("\nTry: cxg search --query \"{}\"", template_id);
return Ok(());
}
if matching.len() > 1 {
println!(
"Found {} templates matching '{}':\n",
matching.len(),
template_id
);
for t in &matching {
println!(" • {} ({:?})", t.id(), t.metadata().language);
}
println!("\nPlease specify a more exact template ID.");
return Ok(());
}
let template = matching[0];
let meta = template.metadata();
println!("\n╔════════════════════════════════════════════════════════════════╗");
println!("║ Template Information ║");
println!("╚════════════════════════════════════════════════════════════════╝\n");
println!(" ID: {}", template.id());
println!(" Name: {}", meta.name);
println!(" Language: {:?}", meta.language);
println!(" Severity: {:?}", meta.severity);
println!(" Author: {}", meta.author.name);
println!(" Description: {}", meta.description);
if !meta.tags.is_empty() {
println!(" Tags: {}", meta.tags.join(", "));
}
if let Some(ref vc) = meta.vuln_class {
println!(" Vuln Class: {}", vc);
}
if !meta.hypothesis_tags.is_empty() {
println!(" Hyp. Tags: {}", meta.hypothesis_tags.join(", "));
}
if let Some(ref bg) = meta.batch_group {
println!(" Batch Group: {}", bg);
}
if meta.auto_probe {
println!(" Auto-Probe: yes (template can self-acquire missing context)");
}
if !meta.context_vars.is_empty() {
println!("\n Context Variables:");
for cv_str in &meta.context_vars {
let parts: Vec<&str> = cv_str.splitn(2, ':').collect();
let (name, qualifier) = if parts.len() == 2 {
(parts[0], parts[1])
} else {
(cv_str.as_str(), "optional")
};
let marker = if qualifier == "required" {
"✓"
} else {
"○"
};
println!(" {} {:<30} [{}]", marker, name, qualifier);
}
}
if !meta.file_path.as_os_str().is_empty() {
println!(" File: {}", meta.file_path.display());
if let Ok(file_meta) = std::fs::metadata(&meta.file_path) {
let size = file_meta.len();
if size > 1024 {
println!(" Size: {:.1} KB", size as f64 / 1024.0);
} else {
println!(" Size: {} bytes", size);
}
}
}
println!();
Ok(())
}
TemplateAction::Create {
id,
language,
name,
output,
} => {
use cli::LanguageArg;
let (ext, skeleton_name) = match language {
LanguageArg::Python => ("py", "python-template-skeleton.py"),
LanguageArg::Rust => ("rs", "rust-template-skeleton.rs"),
LanguageArg::C => ("c", "c-template-skeleton.c"),
LanguageArg::Cpp => ("cpp", "cpp-template-skeleton.cpp"),
LanguageArg::Java => ("java", "java-template-skeleton.java"),
LanguageArg::Go => ("go", "go-template-skeleton.go"),
LanguageArg::JavaScript => ("js", "javascript-template-skeleton.js"),
LanguageArg::Ruby => ("rb", "ruby-template-skeleton.rb"),
LanguageArg::Perl => ("pl", "perl-template-skeleton.pl"),
LanguageArg::Php => ("php", "php-template-skeleton.php"),
LanguageArg::Shell => ("sh", "shell-template-skeleton.sh"),
LanguageArg::Yaml => ("yaml", "yaml-template-skeleton.yaml"),
};
let skeleton_paths = vec![
std::path::PathBuf::from("templates/skeleton").join(skeleton_name),
dirs::home_dir()
.unwrap_or_default()
.join(".cert-x-gen/templates/official/templates/skeleton")
.join(skeleton_name),
];
let skeleton_content = skeleton_paths
.iter()
.find_map(|p| std::fs::read_to_string(p).ok())
.ok_or_else(|| {
Error::config(format!(
"Skeleton template '{}' not found. Run 'cxg --ut' to download templates.",
skeleton_name
))
})?;
let template_name = if name.is_empty() {
id.split('-')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
Some(c) => c.to_uppercase().chain(chars).collect(),
None => String::new(),
}
})
.collect::<Vec<_>>()
.join(" ")
} else {
name.clone()
};
let content = skeleton_content
.replace("template-skeleton", &id)
.replace("Template Skeleton", &template_name);
let output_path = output.join(format!("{}.{}", id, ext));
std::fs::write(&output_path, &content)
.map_err(|e| Error::config(format!("Failed to write template: {}", e)))?;
println!("✅ Created template: {}", output_path.display());
println!(" Language: {:?}", language);
println!(" ID: {}", id);
println!("\nNext steps:");
println!(" 1. Edit the template to add your detection logic");
println!(
" 2. Validate: cxg template validate {}",
output_path.display()
);
println!(
" 3. Test: cxg scan --scope <target> --templates {}",
output_path.display()
);
Ok(())
}
TemplateAction::Test {
template,
target,
debug: _,
} => {
println!("Testing template {} against {}", template.display(), target);
Ok(())
}
TemplateAction::Search {
query,
language,
severity,
tags,
content,
detailed,
limit,
} => {
use cert_x_gen::search::{
SearchArgs as LibSearchArgs, SearchFormat, SearchResultFormatter, SearchSort,
TemplateSearchEngine,
};
let config = Config::default();
let engine = CertXGen::new(config).await?;
let templates = engine.load_templates().await?;
let search_args = LibSearchArgs {
query: Some(query),
language: language.map(|l| l.into()),
severity: severity.map(|s| s.into()),
tags,
author: None,
cwe: None,
content,
case_sensitive: false,
regex: false,
limit,
format: SearchFormat::Table,
detailed,
sort: SearchSort::Relevance,
reverse: false,
ids_only: false,
stats: false,
};
let search_engine = TemplateSearchEngine::new(templates);
let (results, stats) = search_engine.search(&search_args);
let output = SearchResultFormatter::format_results(
&results,
&stats,
search_args.format,
detailed,
false,
);
print!("{}", output);
Ok(())
}
TemplateAction::Pwd => {
use cert_x_gen::template::PathResolver;
println!("\n📂 Template Directories (priority order):\n");
let dirs = vec![
("Local (project)", PathResolver::local_template_dir()),
("User", PathResolver::user_template_dir()),
("System", PathResolver::system_template_dir()),
];
for (label, dir) in &dirs {
let exists = dir.exists();
let marker = if exists { "✓" } else { "✗" };
let abs_path = if dir.is_relative() {
let stripped = dir.strip_prefix("./").unwrap_or(dir);
let joined = std::env::current_dir()
.map(|cwd| cwd.join(stripped))
.unwrap_or_else(|_| dir.clone());
joined.canonicalize().unwrap_or(joined)
} else {
dir.clone()
};
println!(" [{}] {:<18} {}", marker, label, abs_path.display());
}
println!();
Ok(())
}
TemplateAction::Skeleton { language } => {
use cli::LanguageArg;
let skeleton_name = match language {
LanguageArg::Python => "python-template-skeleton.py",
LanguageArg::Rust => "rust-template-skeleton.rs",
LanguageArg::C => "c-template-skeleton.c",
LanguageArg::Cpp => "cpp-template-skeleton.cpp",
LanguageArg::Java => "java-template-skeleton.java",
LanguageArg::Go => "go-template-skeleton.go",
LanguageArg::JavaScript => "javascript-template-skeleton.js",
LanguageArg::Ruby => "ruby-template-skeleton.rb",
LanguageArg::Perl => "perl-template-skeleton.pl",
LanguageArg::Php => "php-template-skeleton.php",
LanguageArg::Shell => "shell-template-skeleton.sh",
LanguageArg::Yaml => "yaml-template-skeleton.yaml",
};
let skeleton_paths = vec![
std::path::PathBuf::from("templates/skeleton").join(skeleton_name),
dirs::home_dir()
.unwrap_or_default()
.join(".cert-x-gen/templates/official/templates/skeleton")
.join(skeleton_name),
];
match skeleton_paths.iter().find_map(|p| {
std::fs::read_to_string(p)
.ok()
.map(|content| (p.clone(), content))
}) {
Some((path, content)) => {
println!(
"📄 Skeleton template for {:?} ({})\n",
language,
path.display()
);
println!("{}", content);
}
None => {
eprintln!("❌ Skeleton template '{}' not found.", skeleton_name);
eprintln!(" Run 'cxg template update' to download templates.");
}
}
Ok(())
}
TemplateAction::Add { file, dest } => {
use cert_x_gen::template::PathResolver;
if !file.exists() {
eprintln!("❌ File not found: {}", file.display());
return Err(Error::config(format!(
"Template file does not exist: {}",
file.display()
)));
}
let file_name = file
.file_name()
.ok_or_else(|| Error::config("Invalid file path".to_string()))?;
let user_dir = PathResolver::user_template_dir();
let target_dir = match &dest {
Some(sub) => user_dir.join(sub),
None => user_dir.clone(),
};
std::fs::create_dir_all(&target_dir).map_err(|e| {
Error::config(format!(
"Failed to create directory {}: {}",
target_dir.display(),
e
))
})?;
let target_path = target_dir.join(file_name);
if target_path.exists() {
println!("⚠️ File already exists: {}", target_path.display());
println!(" Overwriting...");
}
std::fs::copy(&file, &target_path).map_err(|e| {
Error::config(format!(
"Failed to copy {} → {}: {}",
file.display(),
target_path.display(),
e
))
})?;
println!("✅ Template added: {}", target_path.display());
println!(" Source: {}", file.display());
println!("\nNext steps:");
println!(
" 1. Validate: cxg template validate {}",
target_path.display()
);
println!(" 2. List: cxg template list");
Ok(())
}
}
}
async fn run_search_command(args: cli::SearchArgs) -> Result<()> {
use cert_x_gen::search::{
SearchArgs as LibSearchArgs, SearchFormat, SearchResultFormatter, SearchSort,
TemplateSearchEngine,
};
use std::fs;
tracing::info!("Starting template search...");
let config = Config::default();
let engine = CertXGen::new(config).await?;
let templates = engine.load_templates().await?;
tracing::info!("Loaded {} templates", templates.len());
let search_args = LibSearchArgs {
query: args.query,
language: args.language.map(|l| l.into()),
severity: args.severity.map(|s| s.into()),
tags: args.tags,
author: args.author,
cwe: args.cwe,
content: args.content,
case_sensitive: args.case_sensitive,
regex: args.regex,
limit: args.limit,
format: match args.format {
cli::SearchFormat::Table => SearchFormat::Table,
cli::SearchFormat::Json => SearchFormat::Json,
cli::SearchFormat::Yaml => SearchFormat::Yaml,
cli::SearchFormat::Csv => SearchFormat::Csv,
cli::SearchFormat::List => SearchFormat::List,
cli::SearchFormat::Detailed => SearchFormat::Detailed,
},
detailed: args.detailed,
sort: match args.sort {
cli::SearchSort::Relevance => SearchSort::Relevance,
cli::SearchSort::Name => SearchSort::Name,
cli::SearchSort::Language => SearchSort::Language,
cli::SearchSort::Severity => SearchSort::Severity,
cli::SearchSort::Author => SearchSort::Author,
cli::SearchSort::Date => SearchSort::Date,
cli::SearchSort::Popularity => SearchSort::Popularity,
},
reverse: args.reverse,
ids_only: args.ids_only,
stats: args.stats,
};
let search_engine = TemplateSearchEngine::new(templates);
let (results, stats) = search_engine.search(&search_args);
let output = SearchResultFormatter::format_results(
&results,
&stats,
search_args.format,
args.detailed,
args.ids_only,
);
if let Some(output_file) = args.output {
fs::write(&output_file, &output)?;
println!("Search results written to: {}", output_file.display());
} else {
print!("{}", output);
}
if args.stats {
println!("\nSearch Statistics:");
println!(" Total templates: {}", stats.total_templates);
println!(" Matching templates: {}", stats.matching_templates);
println!(" Search time: {}ms", stats.search_time_ms);
if !stats.languages.is_empty() {
println!(" Languages:");
for (language, count) in &stats.languages {
println!(" {:?}: {}", language, count);
}
}
if !stats.severities.is_empty() {
println!(" Severities:");
for (severity, count) in &stats.severities {
println!(" {:?}: {}", severity, count);
}
}
}
Ok(())
}
async fn run_server(args: cli::ServerArgs) -> Result<()> {
tracing::info!("Starting API server on {}:{}", args.bind, args.port);
Err(Error::NotImplemented(
"API server not yet implemented".to_string(),
))
}
fn run_config_command(cmd: cli::ConfigCommand) -> Result<()> {
use cli::ConfigAction;
match cmd.action {
ConfigAction::Generate { output, format: _ } => {
let config = Config::default();
config.save(&output)?;
println!("Configuration generated: {}", output.display());
Ok(())
}
ConfigAction::Validate { config } => {
let (cfg, obsolete) = Config::from_file_reporting_obsolete(&config)?;
cfg.validate()?;
if obsolete.is_empty() {
println!("Configuration is valid");
} else {
println!(
"Configuration is loadable, but contains {} obsolete section(s) with no \
effect: {}. See the warning above; remove them.",
obsolete.len(),
obsolete.join(", ")
);
}
Ok(())
}
ConfigAction::Show => {
let config = Config::default();
let yaml =
serde_yaml::to_string(&config).map_err(|e| Error::Serialization(e.to_string()))?;
println!("{}", yaml);
Ok(())
}
}
}
async fn run_sandbox_command(cmd: cli::SandboxCommand) -> Result<()> {
use cert_x_gen::sandbox::{Sandbox, SandboxConfig};
use cli::SandboxAction;
use console::{style, Term};
let term = Term::stdout();
match cmd.action {
SandboxAction::Init {
force,
languages,
directory,
} => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::{
current_sandbox_name, inside_sandbox, DockerSandbox,
};
use cert_x_gen::sandbox::Sandbox;
if inside_sandbox() {
if let Some(sandbox_name) = current_sandbox_name() {
term.write_line(&format!(
"\n{} Running inside Docker sandbox: {}",
style("🐳").cyan(),
style(&sandbox_name).yellow()
))?;
term.write_line(
&" Initializing package environment inside the container...".to_string(),
)?;
term.write_line("")?;
}
} else {
if let Ok(cfg) = SandboxConfigFile::load() {
if let Some((name, config)) = cfg.get_default_sandbox() {
if config.auto_start {
term.write_line(&format!(
"\n{} Default Docker sandbox detected: {}",
style("🐳").cyan(),
style(name).yellow()
))?;
term.write_line(
&" This command will run INSIDE the Docker container.".to_string(),
)?;
term.write_line(
&" You'll stay on your host, but init happens in the sandbox."
.to_string(),
)?;
term.write_line("")?;
}
}
}
if DockerSandbox::docker_available()
&& DockerSandbox::docker_running()
&& SandboxConfigFile::load()
.ok()
.and_then(|c| c.default_sandbox)
.is_none()
{
term.write_line(&format!("\n{} Docker detected!", style("ℹ").blue()))?;
term.write_line(
&" For fresh runtimes instead of your host's, consider a Docker environment:"
.to_string(),
)?;
term.write_line(&format!(
" {}",
style("cxg sandbox create my-env").yellow()
))?;
term.write_line(&format!(
" {}",
style("cxg sandbox set-default my-env").yellow()
))?;
term.write_line("")?;
term.write_line(&" This command (init) creates package directories using your host's language runtimes.".to_string())?;
term.write_line(&" A Docker environment gives you fresh runtimes inside a container you can 'enter'.".to_string())?;
term.write_line(&" Neither confines template execution: templates run as ordinary child processes".to_string())?;
term.write_line(&" with your privileges and full network and filesystem access. Review templates first.".to_string())?;
term.write_line("")?;
term.write_line(&format!(
" Run {} for more info.",
style("cxg sandbox info").cyan()
))?;
term.write_line("")?;
}
}
let mut config = SandboxConfig::default();
if let Some(dir) = directory {
config.root_dir = dir;
}
if let Some(langs) = languages {
config.enable_python = langs.contains("python");
config.enable_javascript = langs.contains("javascript") || langs.contains("js");
config.enable_ruby = langs.contains("ruby");
config.enable_perl = langs.contains("perl");
config.enable_php = langs.contains("php");
config.enable_rust = langs.contains("rust");
config.enable_go = langs.contains("go");
config.enable_java = langs.contains("java");
}
let mut sandbox = Sandbox::with_config(config.clone());
let already_initialized = sandbox.is_initialized();
if already_initialized && !force {
term.write_line(&format!(
"{} Sandbox already initialized at: {}",
style("✓").green(),
sandbox.root_dir().display()
))?;
let status = sandbox.status();
let mut existing_langs = Vec::new();
if status.python_ready {
existing_langs.push("Python");
}
if status.javascript_ready {
existing_langs.push("JavaScript");
}
if status.ruby_ready {
existing_langs.push("Ruby");
}
if status.perl_ready {
existing_langs.push("Perl");
}
if status.php_ready {
existing_langs.push("PHP");
}
if status.rust_ready {
existing_langs.push("Rust");
}
if status.go_ready {
existing_langs.push("Go");
}
if status.java_ready {
existing_langs.push("Java");
}
term.write_line(&format!(
" Existing languages: {}",
if existing_langs.is_empty() {
"None".to_string()
} else {
existing_langs.join(", ")
}
))?;
let mut languages_to_add = Vec::new();
if config.enable_python && !status.python_ready {
languages_to_add.push("Python");
}
if config.enable_javascript && !status.javascript_ready {
languages_to_add.push("JavaScript");
}
if config.enable_ruby && !status.ruby_ready {
languages_to_add.push("Ruby");
}
if config.enable_perl && !status.perl_ready {
languages_to_add.push("Perl");
}
if config.enable_php && !status.php_ready {
languages_to_add.push("PHP");
}
if config.enable_rust && !status.rust_ready {
languages_to_add.push("Rust");
}
if config.enable_go && !status.go_ready {
languages_to_add.push("Go");
}
if config.enable_java && !status.java_ready {
languages_to_add.push("Java");
}
if languages_to_add.is_empty() {
term.write_line(&format!(
"\n{} All requested languages are already initialized!",
style("✓").green()
))?;
term.write_line(&format!(
" Nothing to do. Use {} to rebuild everything.",
style("--force").yellow()
))?;
return Ok(());
} else {
term.write_line(&format!(
"\n{} Adding new languages: {}",
style("→").cyan(),
style(languages_to_add.join(", ")).yellow()
))?;
}
} else if force {
term.write_line(&format!(
"{} Force re-initialization requested",
style("→").cyan()
))?;
term.write_line(
&" Rebuilding all language environments from scratch...".to_string(),
)?;
}
term.write_line(&format!(
"{} Initializing sandbox environment...",
style("→").cyan()
))?;
sandbox.init().await?;
let status = sandbox.status();
let mut initialized_langs = Vec::new();
if status.python_ready {
initialized_langs.push("Python");
}
if status.javascript_ready {
initialized_langs.push("JavaScript");
}
if status.ruby_ready {
initialized_langs.push("Ruby");
}
if status.perl_ready {
initialized_langs.push("Perl");
}
if status.php_ready {
initialized_langs.push("PHP");
}
if status.rust_ready {
initialized_langs.push("Rust");
}
if status.go_ready {
initialized_langs.push("Go");
}
if status.java_ready {
initialized_langs.push("Java");
}
if !initialized_langs.is_empty() {
term.write_line(&format!(
"{} Sandbox initialized successfully!",
style("✓").green()
))?;
term.write_line(&format!(
" Initialized languages: {}",
style(initialized_langs.join(", ")).cyan()
))?;
} else {
term.write_line(&format!(
"{} Sandbox initialization completed with warnings",
style("⚠").yellow()
))?;
term.write_line(
&" No language environments were successfully initialized".to_string(),
)?;
term.write_line(&" Check logs above for details on what failed".to_string())?;
}
term.write_line("")?;
term.write_line(&format!(
"{} Note: Some packages may have failed to install due to:",
style("ℹ").blue()
))?;
term.write_line(" - Missing system dependencies (build tools, compilers)")?;
term.write_line(" - Outdated runtime versions (e.g., Ruby < 3.0)")?;
term.write_line(" - Package incompatibilities")?;
term.write_line("")?;
term.write_line(&format!(
"{} The sandbox will continue to work with successfully installed packages.",
style("ℹ").blue()
))?;
term.write_line(&format!(
"{} You can install missing packages manually if needed.",
style("ℹ").blue()
))?;
term.write_line(&format!(" Location: {}", sandbox.root_dir().display()))?;
Ok(())
}
SandboxAction::Status => {
let sandbox = Sandbox::new();
let status = sandbox.status();
term.write_line(&format!("\n{}", style("Sandbox Status").bold().cyan()))?;
term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;
term.write_line(&format!("Location: {}", status.root_dir.display()))?;
term.write_line(&format!(
"Initialized: {}",
if status.initialized {
style("Yes").green()
} else {
style("No").red()
}
))?;
term.write_line(&format!("\n{}", style("Language Runtimes:").bold()))?;
term.write_line(&format!(
" Python: {}",
if status.python_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" JavaScript: {}",
if status.javascript_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" Ruby: {}",
if status.ruby_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" Perl: {}",
if status.perl_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" PHP: {}",
if status.php_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" Rust: {}",
if status.rust_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" Go: {}",
if status.go_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line(&format!(
" Java: {}",
if status.java_ready {
style("✓").green()
} else {
style("✗").red()
}
))?;
term.write_line("")?;
Ok(())
}
SandboxAction::Install { language, packages } => {
let sandbox = Sandbox::new();
if !sandbox.is_initialized() {
return Err(Error::config(
"Sandbox not initialized. Run 'cxg sandbox init' first.",
));
}
term.write_line(&format!(
"{} Installing {} packages for {}...",
style("→").cyan(),
packages.len(),
style(&language).yellow()
))?;
let packages_str: Vec<&str> = packages.iter().map(|s| s.as_str()).collect();
match language.as_str() {
"python" | "py" => {
cert_x_gen::sandbox::python::install_packages(&sandbox, &packages_str).await?;
}
"javascript" | "js" | "node" => {
cert_x_gen::sandbox::javascript::install_packages(&sandbox, &packages_str)
.await?;
}
"ruby" | "rb" => {
cert_x_gen::sandbox::ruby::install_gems(&sandbox, &packages_str).await?;
}
"perl" | "pl" => {
cert_x_gen::sandbox::perl::install_modules(&sandbox, &packages_str).await?;
}
"php" => {
cert_x_gen::sandbox::php::install_packages(&sandbox, &packages_str).await?;
}
_ => {
return Err(Error::config(format!("Unsupported language: {}", language)));
}
}
term.write_line(&format!(
"{} Packages installed successfully!",
style("✓").green()
))?;
Ok(())
}
SandboxAction::Clean { language: _, force } => {
let sandbox = Sandbox::new();
if !force {
term.write_line(&format!(
"{} This will delete the sandbox environment.",
style("⚠").yellow()
))?;
term.write_line("Use --force to confirm.")?;
return Ok(());
}
term.write_line(&format!("{} Cleaning sandbox...", style("→").cyan()))?;
sandbox.clean()?;
term.write_line(&format!(
"{} Sandbox cleaned successfully!",
style("✓").green()
))?;
Ok(())
}
SandboxAction::Shell { language } => {
let sandbox = Sandbox::new();
if !sandbox.is_initialized() {
return Err(Error::config(
"Sandbox not initialized. Run 'cxg sandbox init' first.",
));
}
term.write_line(&format!(
"{} Opening {} shell in sandbox...",
style("→").cyan(),
style(&language).yellow()
))?;
term.write_line(&format!("Location: {}", sandbox.root_dir().display()))?;
term.write_line("Type 'exit' to return.\n")?;
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
std::process::Command::new(shell)
.current_dir(sandbox.root_dir())
.envs(sandbox.get_env_vars())
.status()
.map_err(|e| Error::command(format!("Failed to open shell: {}", e)))?;
Ok(())
}
SandboxAction::Path => {
let sandbox = Sandbox::new();
println!("{}", sandbox.root_dir().display());
Ok(())
}
SandboxAction::Update { language: _ } => {
term.write_line(&format!("{} Updating packages...", style("→").cyan()))?;
term.write_line(&format!("{} Update complete!", style("✓").green()))?;
Ok(())
}
SandboxAction::Export {
output,
description,
author,
} => {
let sandbox = Sandbox::new();
if !sandbox.is_initialized() {
return Err(Error::config(
"Sandbox not initialized. Run 'cxg sandbox init' first.",
));
}
term.write_line(&format!(
"{} Exporting sandbox configuration...",
style("→").cyan()
))?;
let mut export =
cert_x_gen::sandbox::import_export::SandboxExport::from_sandbox(&sandbox)?;
if let Some(desc) = description {
export.metadata.description = Some(desc);
}
if let Some(auth) = author {
export.metadata.author = Some(auth);
}
export.save(&output)?;
term.write_line(&format!(
"{} Sandbox exported to: {}",
style("✓").green(),
output.display()
))?;
term.write_line(&format!(
" Python packages: {}",
export.python_packages.len()
))?;
term.write_line(&format!(
" JavaScript packages: {}",
export.javascript_packages.len()
))?;
term.write_line(&format!(" Ruby gems: {}", export.ruby_gems.len()))?;
Ok(())
}
SandboxAction::Import { file, force } => {
term.write_line(&format!(
"{} Importing sandbox configuration from: {}",
style("→").cyan(),
file.display()
))?;
let export = cert_x_gen::sandbox::import_export::SandboxExport::load(&file)?;
term.write_line(&format!(" Version: {}", export.metadata.version))?;
term.write_line(&format!(" Exported: {}", export.metadata.exported_at))?;
if let Some(desc) = &export.metadata.description {
term.write_line(&format!(" Description: {}", desc))?;
}
if !force {
term.write_line(&format!(
"\n{} This will replace your current sandbox. Use --force to confirm.",
style("⚠").yellow()
))?;
return Ok(());
}
let mut sandbox = Sandbox::new();
export.apply_to_sandbox(&mut sandbox).await?;
term.write_line(&format!(
"{} Sandbox imported successfully!",
style("✓").green()
))?;
Ok(())
}
SandboxAction::Templates => {
term.write_line(&format!(
"\n{}",
style("Available Sandbox Templates").bold().cyan()
))?;
term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;
let templates = vec![
cert_x_gen::sandbox::import_export::SandboxTemplate::web_security(),
cert_x_gen::sandbox::import_export::SandboxTemplate::network_security(),
cert_x_gen::sandbox::import_export::SandboxTemplate::api_testing(),
];
for template in templates {
term.write_line(&format!("\n{}", style(&template.name).yellow().bold()))?;
term.write_line(&format!(" {}", template.description))?;
term.write_line(&format!(
" Python: {} packages",
template.export.python_packages.len()
))?;
term.write_line(&format!(
" JavaScript: {} packages",
template.export.javascript_packages.len()
))?;
term.write_line(&format!(
" Usage: cxg sandbox use-template {}",
template.name
))?;
}
term.write_line("")?;
Ok(())
}
SandboxAction::UseTemplate { template } => {
term.write_line(&format!(
"{} Loading template: {}",
style("→").cyan(),
style(&template).yellow()
))?;
let sandbox_template = match template.as_str() {
"web-security" => {
cert_x_gen::sandbox::import_export::SandboxTemplate::web_security()
}
"network-security" => {
cert_x_gen::sandbox::import_export::SandboxTemplate::network_security()
}
"api-testing" => cert_x_gen::sandbox::import_export::SandboxTemplate::api_testing(),
_ => {
return Err(Error::config(format!("Unknown template: {}. Use 'cxg sandbox templates' to list available templates.", template)));
}
};
let mut sandbox = Sandbox::new();
sandbox_template
.export
.apply_to_sandbox(&mut sandbox)
.await?;
term.write_line(&format!(
"{} Template applied successfully!",
style("✓").green()
))?;
Ok(())
}
SandboxAction::List { language } => {
let sandbox = Sandbox::new();
if !sandbox.is_initialized() {
return Err(Error::config(
"Sandbox not initialized. Run 'cxg sandbox init' first.",
));
}
term.write_line(&format!(
"\n{} Installed Packages",
style(&language).bold().cyan()
))?;
term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;
let export = cert_x_gen::sandbox::import_export::SandboxExport::from_sandbox(&sandbox)?;
let packages = match language.as_str() {
"python" | "py" => export.python_packages,
"javascript" | "js" | "node" => export.javascript_packages,
"ruby" | "rb" => export.ruby_gems,
"perl" | "pl" => export.perl_modules,
"php" => export.php_packages,
_ => {
return Err(Error::config(format!("Unsupported language: {}", language)));
}
};
for (i, package) in packages.iter().enumerate() {
term.write_line(&format!("{}. {}", i + 1, package))?;
}
term.write_line(&format!(
"\n{} Total: {} packages",
style("✓").green(),
packages.len()
))?;
Ok(())
}
SandboxAction::Create {
name,
languages,
persist,
auto_start,
} => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::{DockerConfig, DockerSandbox, ResourceLimits};
if !DockerSandbox::docker_available() {
term.write_line(&format!(
"{} Docker is not installed or not available",
style("✗").red()
))?;
term.write_line(&"\nTo use Docker sandboxes, please install Docker:".to_string())?;
term.write_line(
&" macOS: https://docs.docker.com/desktop/install/mac-install/".to_string(),
)?;
term.write_line(&" Linux: https://docs.docker.com/engine/install/".to_string())?;
term.write_line(
&" Windows: https://docs.docker.com/desktop/install/windows-install/"
.to_string(),
)?;
return Ok(());
}
if !DockerSandbox::docker_running() {
term.write_line(&format!(
"{} Docker is installed but not running",
style("⚠").yellow()
))?;
term.write_line(&" Please start Docker Desktop and try again".to_string())?;
return Ok(());
}
term.write_line(&format!(
"{} Creating Docker sandbox: {}",
style("→").cyan(),
style(&name).yellow()
))?;
let selected_languages = languages.unwrap_or_else(|| {
vec![
"python".to_string(),
"ruby".to_string(),
"node".to_string(),
"go".to_string(),
"java".to_string(),
"perl".to_string(),
"php".to_string(),
"rust".to_string(),
]
});
let current_dir = std::env::current_dir()?;
let templates_dir = current_dir.join("templates");
let mut volumes = std::collections::HashMap::new();
if templates_dir.exists() {
volumes.insert(
templates_dir.to_str().unwrap().to_string(),
"/workspace/templates".to_string(),
);
}
let config = DockerConfig {
name: name.clone(),
image: format!("cert-x-gen/sandbox:{}", name),
languages: selected_languages.clone(),
persist,
auto_start,
resources: ResourceLimits {
memory: "4g".to_string(),
cpus: "2".to_string(),
},
volumes,
environment: std::collections::HashMap::new(),
network_mode: "bridge".to_string(), };
let mut sandbox = DockerSandbox::new(config.clone());
term.write_line(&format!(
" Building Docker image with languages: {}",
selected_languages.join(", ")
))?;
sandbox.build_image(None).await?;
term.write_line(&" Creating container...".to_string())?;
sandbox.create().await?;
let mut cfg = SandboxConfigFile::load()?;
cfg.set_sandbox(name.clone(), config);
cfg.save()?;
term.write_line(&format!(
"{} Sandbox '{}' created successfully!",
style("✓").green(),
name
))?;
term.write_line(&format!(
" Set as default: cxg sandbox set-default {}",
name
))?;
term.write_line(&format!(" Enter sandbox: cxg sandbox enter {}", name))?;
Ok(())
}
SandboxAction::Delete { name, force } => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::DockerSandbox;
if !force {
term.write_line(&format!(
"{} This will delete the sandbox '{}'",
style("⚠").yellow(),
name
))?;
term.write_line(&" Use --force to confirm deletion".to_string())?;
return Ok(());
}
term.write_line(&format!("{} Deleting sandbox: {}", style("→").cyan(), name))?;
match DockerSandbox::load(&name) {
Ok(mut sandbox) => {
sandbox.delete().await?;
term.write_line(&" Container deleted".to_string())?;
}
Err(_) => {
term.write_line(&format!(
" {} Container not found (may already be deleted)",
style("⚠").yellow()
))?;
}
}
let mut cfg = SandboxConfigFile::load()?;
cfg.remove_sandbox(&name);
cfg.save()?;
term.write_line(&format!(
"{} Sandbox '{}' deleted",
style("✓").green(),
name
))?;
Ok(())
}
SandboxAction::Enter { name } => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::DockerSandbox;
let cfg = SandboxConfigFile::load()?;
let sandbox_name = name.or_else(|| cfg.default_sandbox.clone())
.ok_or_else(|| Error::config("No sandbox specified and no default set. Use: cxg sandbox set-default <name>"))?;
term.write_line(&format!(
"{} Entering sandbox: {}",
style("→").cyan(),
sandbox_name
))?;
let mut sandbox = DockerSandbox::load(&sandbox_name)?;
if !sandbox.is_running() {
term.write_line(&" Starting container...".to_string())?;
sandbox.start().await?;
}
sandbox.shell().await?;
Ok(())
}
SandboxAction::SetDefault { name } => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
let mut cfg = SandboxConfigFile::load()?;
if let Some(sandbox_name) = name {
if !cfg.sandboxes.contains_key(&sandbox_name) {
return Err(Error::config(format!(
"Sandbox '{}' not found",
sandbox_name
)));
}
cfg.set_default(Some(sandbox_name.clone()));
cfg.save()?;
term.write_line(&format!(
"{} Default sandbox set to: {}",
style("✓").green(),
sandbox_name
))?;
} else {
cfg.set_default(None);
cfg.save()?;
term.write_line(&format!("{} Default sandbox cleared", style("✓").green()))?;
}
Ok(())
}
SandboxAction::Info => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::DockerSandbox;
term.write_line(&format!(
"\n{}",
style("Docker Sandbox Information").bold().cyan()
))?;
term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;
if DockerSandbox::docker_available() {
term.write_line(&format!("{} Docker: Installed", style("✓").green()))?;
if let Some(version) = DockerSandbox::docker_version() {
term.write_line(&format!(" Version: {}", version))?;
}
if DockerSandbox::docker_running() {
term.write_line(&format!("{} Docker Daemon: Running", style("✓").green()))?;
} else {
term.write_line(&format!(
"{} Docker Daemon: Not running",
style("⚠").yellow()
))?;
term.write_line(&" Please start Docker Desktop".to_string())?;
}
} else {
term.write_line(&format!("{} Docker: Not installed", style("✗").red()))?;
term.write_line(&"\nInstallation:".to_string())?;
term.write_line(
&" macOS: https://docs.docker.com/desktop/install/mac-install/".to_string(),
)?;
term.write_line(&" Linux: https://docs.docker.com/engine/install/".to_string())?;
term.write_line(
&" Windows: https://docs.docker.com/desktop/install/windows-install/"
.to_string(),
)?;
}
let cfg = SandboxConfigFile::load()?;
term.write_line(&format!(
"\n{}",
style("Configured Sandboxes").bold().cyan()
))?;
term.write_line(&format!("{}", style("═".repeat(60)).dim()))?;
if cfg.sandboxes.is_empty() {
term.write_line(&" No sandboxes configured".to_string())?;
term.write_line(&"\nCreate one: cxg sandbox create my-sandbox".to_string())?;
} else {
for (name, config) in &cfg.sandboxes {
let is_default = cfg.default_sandbox.as_ref() == Some(name);
let marker = if is_default { "* " } else { " " };
term.write_line(&format!("{}{}", marker, style(name).yellow().bold()))?;
term.write_line(&format!(" Image: {}", config.image))?;
term.write_line(&format!(" Languages: {}", config.languages.join(", ")))?;
term.write_line(&format!(" Persist: {}", config.persist))?;
term.write_line(&format!(" Auto-start: {}", config.auto_start))?;
if let Ok(sandbox) = DockerSandbox::load(name) {
if sandbox.is_running() {
term.write_line(&format!(" Status: {}", style("Running").green()))?;
} else {
term.write_line(&format!(" Status: {}", style("Stopped").dim()))?;
}
}
term.write_line("")?;
}
if let Some(default) = &cfg.default_sandbox {
term.write_line(&format!("* Default sandbox: {}", style(default).cyan()))?;
}
}
Ok(())
}
SandboxAction::Build { dockerfile } => {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::DockerSandbox;
term.write_line(&format!("{} Building Docker image...", style("→").cyan()))?;
let cfg = SandboxConfigFile::load()?;
let (_name, config) = cfg.get_default_sandbox().ok_or_else(|| {
Error::config("No default sandbox set. Use: cxg sandbox set-default <name>")
})?;
let sandbox = DockerSandbox::new(config.clone());
sandbox.build_image(dockerfile.as_deref()).await?;
term.write_line(&format!("{} Image built successfully!", style("✓").green()))?;
Ok(())
}
}
}
async fn check_and_enter_sandbox(cli: &Cli) -> Result<()> {
use cert_x_gen::sandbox::config::SandboxConfigFile;
use cert_x_gen::sandbox::docker::{inside_sandbox, DockerSandbox};
if inside_sandbox() {
tracing::debug!("Already inside sandbox, skipping auto-enter");
return Ok(());
}
if matches!(cli.command, Some(Commands::Sandbox(_))) {
if !matches!(cli.command, Some(Commands::Sandbox(ref cmd)) if matches!(cmd.action, cli::SandboxAction::Init { .. }))
{
return Ok(());
}
}
if !DockerSandbox::docker_available() {
tracing::debug!("Docker not available, skipping sandbox auto-enter");
return Ok(());
}
if !DockerSandbox::docker_running() {
tracing::debug!("Docker not running, skipping sandbox auto-enter");
return Ok(());
}
let cfg = match SandboxConfigFile::load() {
Ok(c) => c,
Err(_) => {
tracing::debug!("No sandbox config found, skipping auto-enter");
return Ok(());
}
};
if let Some((name, config)) = cfg.get_default_sandbox() {
if config.auto_start {
tracing::info!("Auto-entering sandbox: {}", name);
let mut sandbox = match DockerSandbox::load(name) {
Ok(s) => s,
Err(e) => {
tracing::warn!("Failed to load default sandbox '{}': {}", name, e);
return Ok(()); }
};
if !sandbox.is_running() {
tracing::info!("Starting sandbox container...");
if let Err(e) = sandbox.start().await {
tracing::warn!("Failed to start sandbox: {}", e);
return Ok(()); }
}
sandbox
.exec_cli(&std::env::args().collect::<Vec<_>>())
.await?;
tracing::info!(
"Started Docker environment '{}'; this command still runs on the host",
name
);
eprintln!(
"note: Docker environment '{}' is running, but this command executes on the \
host, not inside it. Templates run as ordinary child processes with your \
privileges and full network and filesystem access. To run inside the \
container, use `cxg sandbox enter {}`.",
name, name
);
}
}
Ok(())
}
fn print_version() {
println!("CERT-X-GEN v{}", env!("CARGO_PKG_VERSION"));
println!("Advanced Multi-Language Security Scanning Engine");
println!();
println!("Build Information:");
println!(" Version: {}", env!("CARGO_PKG_VERSION"));
println!(
" Target: {}-{}",
std::env::consts::ARCH,
std::env::consts::OS
);
println!();
println!("Links:");
println!(" Repository: https://github.com/Bugb-Technologies/cert-x-gen");
println!(" Documentation: https://docs.bugb.io/cxg/");
println!(" Issues: https://github.com/Bugb-Technologies/cert-x-gen/issues");
}
fn maybe_print_star_nag(quiet: bool) {
const NAG_INTERVAL_SECS: u64 = 7 * 24 * 60 * 60;
if quiet
|| std::env::var("CXG_NO_BANNER").is_ok()
|| std::env::var("CXG_NO_NAG").is_ok()
|| !std::io::stdout().is_terminal()
{
return;
}
let Some(stamp) = dirs::home_dir().map(|h| h.join(".cert-x-gen").join(".star-nag")) else {
return;
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
if let Ok(contents) = std::fs::read_to_string(&stamp) {
if let Ok(last) = contents.trim().parse::<u64>() {
if now.saturating_sub(last) < NAG_INTERVAL_SECS {
return;
}
}
}
if let Some(parent) = stamp.parent() {
let _ = std::fs::create_dir_all(parent);
}
if std::fs::write(&stamp, now.to_string()).is_err() {
return;
}
println!(
"{}",
console::style(
"★ Enjoying cxg? A star helps others find it: https://github.com/Bugb-Technologies/cert-x-gen"
)
.dim()
);
}
fn print_scan_summary(results: &cert_x_gen::types::ScanResults) {
use console::{style, Term};
let _term = Term::stdout();
println!();
println!("{}", style("═".repeat(80)).dim());
println!("{}", style("Scan Summary").bold().cyan());
println!("{}", style("═".repeat(80)).dim());
println!();
println!(" Scan ID: {}", style(&results.scan_id).yellow());
println!(
" Duration: {:.2}s",
results.statistics.duration.as_secs_f64()
);
println!(" Targets Scanned: {}", results.statistics.targets_scanned);
println!(
" Templates Executed: {}",
results.statistics.templates_executed
);
println!();
println!("{}", style("Findings by Severity:").bold());
let critical = results
.statistics
.findings_by_severity
.get(&cert_x_gen::types::Severity::Critical)
.unwrap_or(&0);
let high = results
.statistics
.findings_by_severity
.get(&cert_x_gen::types::Severity::High)
.unwrap_or(&0);
let medium = results
.statistics
.findings_by_severity
.get(&cert_x_gen::types::Severity::Medium)
.unwrap_or(&0);
let low = results
.statistics
.findings_by_severity
.get(&cert_x_gen::types::Severity::Low)
.unwrap_or(&0);
let info = results
.statistics
.findings_by_severity
.get(&cert_x_gen::types::Severity::Info)
.unwrap_or(&0);
println!(
" {} {}",
style("CRITICAL:").red().bold(),
style(critical).red().bold()
);
println!(" {} {}", style("HIGH: ").red(), style(high).red());
println!(
" {} {}",
style("MEDIUM: ").yellow(),
style(medium).yellow()
);
println!(" {} {}", style("LOW: ").blue(), style(low).blue());
println!(" {} {}", style("INFO: ").cyan(), style(info).cyan());
println!();
println!(
" {} {}",
style("TOTAL:").bold(),
style(results.findings.len()).bold()
);
println!();
print_execution_ledger(results);
println!("{}", style("═".repeat(80)).dim());
}
const LEDGER_ROW_LIMIT: usize = 25;
fn execution_verdict_source(record: &cert_x_gen::types::ExecutionRecord) -> &'static str {
if record.declared_by_template {
"template-declared"
} else if record
.detail
.as_deref()
.is_some_and(|detail| detail.starts_with("engine-adjudicated:"))
{
"engine-adjudicated"
} else {
"cxg-inferred"
}
}
fn print_execution_ledger(results: &cert_x_gen::types::ScanResults) {
use cert_x_gen::types::ExecutionStatus;
use console::style;
if results.executions.is_empty() {
return;
}
println!("{}", style("Execution Status:").bold());
for status in ExecutionStatus::ALL {
let count = results
.executions
.iter()
.filter(|e| e.status == status)
.count();
let declared = results
.executions
.iter()
.filter(|e| e.status == status && e.declared_by_template)
.count();
let engine = results
.executions
.iter()
.filter(|e| e.status == status && execution_verdict_source(e) == "engine-adjudicated")
.count();
let mut value = format!(
"{} ({} declared, {} inferred)",
count,
declared,
count - declared - engine
);
if engine > 0 {
value.pop();
value.push_str(&format!(", {} engine-adjudicated)", engine));
}
let label = format!("{}:", status.to_string().to_uppercase());
let styled = match status {
ExecutionStatus::Confirmed => style(format!("{:<11}{}", label, value)).red(),
ExecutionStatus::Refuted => style(format!("{:<11}{}", label, value)).green(),
ExecutionStatus::Skipped => style(format!("{:<11}{}", label, value)).yellow(),
ExecutionStatus::Errored | ExecutionStatus::TimedOut => {
style(format!("{:<11}{}", label, value)).magenta()
}
};
println!(" {}", styled);
}
println!();
for e in results.executions.iter().take(LEDGER_ROW_LIMIT) {
println!(
" {:<10} {} → {}{}{}",
style(e.status.to_string()).bold(),
e.template_id,
e.target,
e.detail
.as_ref()
.map(|d| format!(" [{}]", d))
.unwrap_or_default(),
style(format!(" ({})", execution_verdict_source(e))).dim()
);
}
if results.executions.len() > LEDGER_ROW_LIMIT {
println!(
" {}",
style(format!(
"… and {} more execution(s); the full ledger is in the JSON output",
results.executions.len() - LEDGER_ROW_LIMIT
))
.dim()
);
}
println!();
}
async fn run_ai_command(cmd: cli::AiCommand) -> Result<()> {
use cli::AiAction;
match cmd.action {
AiAction::Generate {
prompt,
language,
provider,
model,
output,
test,
test_target,
force,
estimate_cost,
api_key,
} => {
handle_ai_generate(
prompt,
language,
provider,
model,
output,
test,
test_target,
force,
estimate_cost,
api_key,
)
.await?;
}
AiAction::Providers { action } => {
handle_providers_command(action).await?;
}
}
Ok(())
}
async fn handle_ai_generate(
prompt: String,
language: cli::LanguageArg,
provider: Option<String>,
model: Option<String>,
output: Option<PathBuf>,
test: bool,
test_target: Option<String>,
force: bool,
estimate_cost: bool,
api_key: Option<String>,
) -> Result<()> {
use console::{style, Term};
use std::fs;
if let Some(ref key) = api_key {
let env_var = match provider.as_deref() {
Some("anthropic") => "ANTHROPIC_API_KEY",
Some("openai") => "OPENAI_API_KEY",
Some("deepseek") => "DEEPSEEK_API_KEY",
Some("ollama") => "", _ => {
if key.starts_with("sk-ant-") {
"ANTHROPIC_API_KEY"
} else if key.starts_with("sk-") {
"OPENAI_API_KEY"
} else {
"ANTHROPIC_API_KEY" }
}
};
if !env_var.is_empty() {
std::env::set_var(env_var, key);
tracing::info!("Injected --api-key into {} for this session", env_var);
}
}
let term = Term::stdout();
let template_lang: TemplateLanguage = language.into();
println!();
println!("{}", style("🤖 AI Template Generation").bold().cyan());
println!("{}", style("═".repeat(60)).dim());
println!();
println!(" {} {}", style("Prompt:").bold(), prompt);
println!(" {} {:?}", style("Language:").bold(), template_lang);
if let Some(ref p) = provider {
println!(" {} {}", style("Provider:").bold(), p);
}
if let Some(ref m) = model {
println!(" {} {}", style("Model:").bold(), m);
}
println!();
term.write_line(&format!(
"{} Initializing AI manager...",
style("[1/5]").dim()
))?;
let manager = AIManager::new()
.map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;
if estimate_cost {
term.write_line(&format!("{} Estimating cost...", style("[2/5]").dim()))?;
println!(
" {} Cost estimation not yet implemented",
style("ℹ").blue()
);
println!();
}
term.write_line(&format!("{} Generating template...", style("[2/5]").dim()))?;
term.write_line(" This may take 10-30 seconds depending on the model...")?;
let template_code = manager
.generate_template(&prompt, template_lang, provider.as_deref())
.await
.map_err(|e| Error::Ai(format!("Template generation failed: {}", e)))?;
term.write_line(&format!(
" {} Template generated successfully!",
style("✓").green()
))?;
println!();
term.write_line(&format!("{} Validating template...", style("[3/5]").dim()))?;
let validator = TemplateValidator::new();
validator
.validate(&template_code, template_lang)
.map_err(|e| Error::Ai(format!("Template validation failed: {}", e)))?;
term.write_line(&format!(" {} Template is valid!", style("✓").green()))?;
println!();
let output_path = if let Some(path) = output {
path
} else {
let filename = manager.generate_filename(&prompt, template_lang);
let ai_templates_dir = dirs::home_dir()
.ok_or_else(|| Error::Internal("Could not determine home directory".to_string()))?
.join(".cert-x-gen")
.join("templates")
.join("ai-generated");
ai_templates_dir.join(filename)
};
if output_path.exists() && !force {
return Err(Error::Internal(format!(
"File already exists: {}. Use --force to overwrite",
output_path.display()
)));
}
term.write_line(&format!("{} Saving template...", style("[4/5]").dim()))?;
if let Some(parent) = output_path.parent() {
fs::create_dir_all(parent)
.map_err(|e| Error::Internal(format!("Failed to create directory: {}", e)))?;
}
fs::write(&output_path, &template_code)
.map_err(|e| Error::Internal(format!("Failed to write template: {}", e)))?;
term.write_line(&format!(
" {} Template saved to: {}",
style("✓").green(),
output_path.display()
))?;
println!();
if test {
term.write_line(&format!("{} Testing template...", style("[5/5]").dim()))?;
if let Some(target) = test_target {
println!(" Testing against target: {}", target);
println!(
" {} Template testing not yet implemented",
style("ℹ").blue()
);
} else {
println!(
" {} No test target specified, skipping test",
style("ℹ").yellow()
);
}
println!();
}
println!("{}", style("═".repeat(60)).dim());
println!(
"{}",
style("✓ Template Generation Complete!").bold().green()
);
println!("{}", style("═".repeat(60)).dim());
println!();
println!(" {} {}", style("Location:").bold(), output_path.display());
println!(
" {} {} lines",
style("Size:").bold(),
template_code.lines().count()
);
println!(" {} {:?}", style("Language:").bold(), template_lang);
println!();
println!("Next steps:");
println!(" • View template: cat {}", output_path.display());
println!(
" • Run scan: cert-x-gen scan --template {} --target <host>",
output_path.display()
);
println!(" • Edit template: $EDITOR {}", output_path.display());
println!();
Ok(())
}
async fn handle_providers_command(action: cli::ProviderAction) -> Result<()> {
use cert_x_gen::ai::AIManager;
use cli::ProviderAction;
use console::style;
match action {
ProviderAction::List { detailed } => {
println!();
println!("{}", style("Available LLM Providers").bold().cyan());
println!("{}", style("═".repeat(60)).dim());
println!();
let manager = AIManager::new()
.map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;
let providers = manager.list_providers();
if providers.is_empty() {
println!(" {} No providers configured", style("ℹ").yellow());
println!();
println!("To get started:");
println!(" 1. Install Ollama: curl -fsSL https://ollama.com/install.sh | sh");
println!(" 2. Download model: ollama pull codellama:13b");
println!(" 3. Start Ollama: ollama serve");
println!();
return Ok(());
}
for (provider_name, enabled) in providers {
let icon = if provider_name == "ollama" && enabled {
style("✓").green()
} else if enabled {
style("○").cyan()
} else {
style("○").dim()
};
println!(" {} {}", icon, style(&provider_name).bold());
if detailed {
println!(
" Type: {}",
if provider_name == "ollama" {
"Local"
} else {
"Cloud"
}
);
println!(
" Status: {}",
if enabled { "Enabled" } else { "Disabled" }
);
}
}
println!();
println!("Use 'cxg ai providers test <name>' to test a provider");
println!();
Ok(())
}
ProviderAction::Test { provider } => {
println!();
println!(
"{}",
style(format!("Testing Provider: {}", provider))
.bold()
.cyan()
);
println!("{}", style("═".repeat(60)).dim());
println!();
let manager = AIManager::new()
.map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;
println!(" {} Running health checks...", style("⚙").cyan());
println!();
match manager.test_provider(&provider).await {
Ok(status) => {
let conn_icon = if status.connection.is_ok() {
style("✓").green()
} else {
style("✗").red()
};
println!(
" {} Connection: {}",
conn_icon,
match status.connection {
cert_x_gen::ai::providers::ConnectionStatus::Connected =>
style("OK").green(),
cert_x_gen::ai::providers::ConnectionStatus::Failed =>
style("Failed").red(),
cert_x_gen::ai::providers::ConnectionStatus::Untested =>
style("Not tested").yellow(),
}
);
let auth_icon = if status.authentication.is_ok() {
style("✓").green()
} else if matches!(
status.authentication,
cert_x_gen::ai::providers::AuthStatus::NotRequired
) {
style("○").dim()
} else {
style("✗").red()
};
println!(
" {} Authentication: {}",
auth_icon,
match status.authentication {
cert_x_gen::ai::providers::AuthStatus::Authenticated =>
style("Valid").green(),
cert_x_gen::ai::providers::AuthStatus::Failed => style("Invalid").red(),
cert_x_gen::ai::providers::AuthStatus::NotRequired =>
style("Not required").dim(),
cert_x_gen::ai::providers::AuthStatus::NotConfigured =>
style("Not configured").yellow(),
cert_x_gen::ai::providers::AuthStatus::Untested =>
style("Not tested").yellow(),
}
);
if let Some(rt) = status.response_time_ms {
let rt_style = if rt < 1000 {
style(format!("{}ms", rt)).green()
} else if rt < 5000 {
style(format!("{}ms", rt)).yellow()
} else {
style(format!("{}ms", rt)).red()
};
println!(" {} Response time: {}", style("⚡").cyan(), rt_style);
}
if let Some(count) = status.models_available {
println!(
" {} Models available: {}",
style("📦").cyan(),
style(count).bold()
);
if !status.models.is_empty() {
println!();
println!(" Available models:");
for model in &status.models {
let size_info = if let Some(_size) = model.size {
format!(" ({})", model.size_human_readable())
} else {
String::new()
};
println!(
" • {}{}",
style(&model.name).dim(),
style(size_info).dim()
);
}
}
}
if !status.messages.is_empty() {
println!();
println!(" Messages:");
for msg in &status.messages {
if msg.starts_with("⚠") || msg.starts_with("Hint:") {
println!(" {}", style(msg).yellow());
} else if msg.contains("✓") || msg.contains("Success") {
println!(" {}", style(msg).green());
} else {
println!(" {}", style(msg).dim());
}
}
}
println!();
if status.healthy {
println!(
" {} Status: {}",
style("✓").green().bold(),
style("Ready").green().bold()
);
} else {
println!(
" {} Status: {}",
style("✗").red().bold(),
style("Not Ready").red().bold()
);
}
println!();
}
Err(e) => {
println!(" {} Error testing provider: {}", style("✗").red(), e);
println!();
}
}
Ok(())
}
ProviderAction::Status => {
println!();
println!("{}", style("Provider Status").bold().cyan());
println!("{}", style("═".repeat(60)).dim());
println!();
let manager = AIManager::new()
.map_err(|e| Error::Ai(format!("Failed to initialize AI manager: {}", e)))?;
let providers = manager.list_providers();
if providers.is_empty() {
println!(" {} No providers configured", style("ℹ").yellow());
println!();
return Ok(());
}
println!(
" {} Testing {} providers...",
style("⚙").cyan(),
providers.len()
);
println!();
for (provider_name, enabled) in providers {
let icon = if enabled {
style("●").green()
} else {
style("○").dim()
};
println!(" {} {}", icon, style(&provider_name).bold());
println!(
" Enabled: {}",
if enabled {
style("Yes").green()
} else {
style("No").dim()
}
);
if enabled {
match manager.test_provider(&provider_name).await {
Ok(status) => {
let conn_status = match status.connection {
cert_x_gen::ai::providers::ConnectionStatus::Connected => {
style("Connected").green()
}
cert_x_gen::ai::providers::ConnectionStatus::Failed => {
style("Failed").red()
}
_ => style("Unknown").yellow(),
};
println!(" Connection: {}", conn_status);
let auth_status = match status.authentication {
cert_x_gen::ai::providers::AuthStatus::Authenticated => {
style("Valid").green()
}
cert_x_gen::ai::providers::AuthStatus::NotRequired => {
style("Not required").dim()
}
cert_x_gen::ai::providers::AuthStatus::Failed => {
style("Invalid").red()
}
cert_x_gen::ai::providers::AuthStatus::NotConfigured => {
style("Not configured").yellow()
}
_ => style("Unknown").yellow(),
};
println!(" Authentication: {}", auth_status);
if let Some(rt) = status.response_time_ms {
println!(" Response time: {}ms", rt);
}
if let Some(count) = status.models_available {
println!(" Models: {}", count);
}
let health = if status.healthy {
style("✓ Ready").green()
} else {
style("✗ Not Ready").red()
};
println!(" Status: {}", health);
}
Err(e) => {
println!(" Status: {} ({})", style("Error").red(), e);
}
}
} else {
println!(" Status: {}", style("Disabled").dim());
}
println!();
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn engine_adjudication_is_not_labelled_as_scanner_inference() {
let mut record: cert_x_gen::types::ExecutionRecord =
serde_json::from_value(serde_json::json!({
"target": "127.0.0.1", "template_id": "probe", "status": "confirmed", "findings": 1,
"detail": "engine-adjudicated: engine-confirmed finding"
}))
.unwrap();
assert_eq!(execution_verdict_source(&record), "engine-adjudicated");
record.detail = None;
assert_eq!(execution_verdict_source(&record), "cxg-inferred");
record.declared_by_template = true;
assert_eq!(execution_verdict_source(&record), "template-declared");
}
#[test]
fn parse_target_string_accepts_cli_scheme_with_authority() {
let target = parse_target_string("cli:///opt/build/toy");
assert_eq!(target.protocol, Protocol::Cli);
assert_eq!(target.address, "/opt/build/toy");
assert_eq!(target.port, None);
}
#[test]
fn parse_target_string_accepts_bare_cli_scheme() {
let target = parse_target_string("cli:/opt/build/toy");
assert_eq!(target.protocol, Protocol::Cli);
assert_eq!(target.address, "/opt/build/toy");
}
fn scan_args(extra: &[&str]) -> cli::ScanArgs {
let mut argv = vec!["scan"];
argv.extend_from_slice(extra);
<cli::ScanArgs as clap::Parser>::parse_from(argv)
}
#[test]
fn probe_arguments_accept_hyphen_leading_values() {
let args = scan_args(&["--arg", "--label", "--arg", "AAAA"]);
assert_eq!(args.arg, vec!["--label", "AAAA"]);
let mut context = cert_x_gen::types::Context::default();
apply_probe_input(&args, &mut context).unwrap();
assert_eq!(context.probe_argv, vec!["--label", "AAAA"]);
}
#[test]
fn target_env_splits_on_the_first_equals_only() {
let args = scan_args(&["--target-env", "ASAN_OPTIONS=abort_on_error=1"]);
let mut context = cert_x_gen::types::Context::default();
apply_probe_input(&args, &mut context).unwrap();
assert_eq!(
context.probe_env,
vec![("ASAN_OPTIONS".to_string(), "abort_on_error=1".to_string())]
);
}
#[test]
fn target_env_without_an_equals_is_an_error_not_a_silent_drop() {
let args = scan_args(&["--target-env", "NOEQUALS"]);
let mut context = cert_x_gen::types::Context::default();
let err = apply_probe_input(&args, &mut context)
.unwrap_err()
.to_string();
assert!(err.contains("NOEQUALS"), "error was {err}");
}
#[test]
fn a_missing_stdin_file_is_rejected_before_the_scan_starts() {
let args = scan_args(&["--stdin-file", "/definitely/not/here.bin"]);
let mut context = cert_x_gen::types::Context::default();
let err = apply_probe_input(&args, &mut context)
.unwrap_err()
.to_string();
assert!(err.contains("not a readable file"), "error was {err}");
}
#[test]
fn an_input_path_that_is_not_a_directory_is_rejected() {
let file = tempfile::NamedTempFile::new().unwrap();
let args = scan_args(&["--input", file.path().to_str().unwrap()]);
let mut context = cert_x_gen::types::Context::default();
let err = apply_probe_input(&args, &mut context)
.unwrap_err()
.to_string();
assert!(err.contains("not a directory"), "error was {err}");
}
#[test]
fn probe_paths_are_canonicalised() {
let dir = tempfile::tempdir().unwrap();
let stdin_file = dir.path().join("case.bin");
std::fs::write(&stdin_file, b"probe").unwrap();
let indirect = dir.path().join(".").join("case.bin");
let args = scan_args(&["--stdin-file", indirect.to_str().unwrap()]);
let mut context = cert_x_gen::types::Context::default();
apply_probe_input(&args, &mut context).unwrap();
assert_eq!(
context.probe_stdin_file.unwrap(),
stdin_file.canonicalize().unwrap()
);
}
#[test]
fn no_probe_flags_leaves_the_context_empty() {
let args = scan_args(&[]);
let mut context = cert_x_gen::types::Context::default();
apply_probe_input(&args, &mut context).unwrap();
assert!(context.probe_argv.is_empty());
assert!(context.probe_stdin_file.is_none());
assert!(context.probe_input_dir.is_none());
assert!(context.probe_env.is_empty());
}
#[test]
fn cli_target_paths_are_canonicalised_so_spellings_deduplicate() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("toy");
std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
let canonical = bin.canonicalize().unwrap().to_string_lossy().to_string();
let dotted = dir.path().join(".").join("toy");
for spelling in [
format!("cli://{}", bin.display()),
format!("cli:{}", bin.display()),
format!("cli://{}", dotted.display()),
] {
let target = parse_target_string(&spelling);
assert_eq!(target.protocol, Protocol::Cli);
assert_eq!(
target.address, canonical,
"spelling {spelling} did not canonicalise"
);
}
}
#[test]
fn an_unresolvable_cli_path_is_kept_verbatim() {
let target = parse_target_string("cli:///definitely/not/here");
assert_eq!(target.address, "/definitely/not/here");
}
#[test]
fn a_cli_scope_entry_with_a_comma_is_not_split_in_half() {
let mut acc = Vec::new();
let mut stack = HashSet::new();
expand_scope_entry("cli:///opt/my,build/toy", &mut acc, &mut stack).unwrap();
assert_eq!(acc, vec!["cli:///opt/my,build/toy".to_string()]);
}
#[test]
fn a_cli_scope_entry_is_never_read_as_a_target_file() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("toy");
std::fs::write(&bin, b"example.com\nother.example\n").unwrap();
let mut acc = Vec::new();
let mut stack = HashSet::new();
let entry = format!("cli://{}", bin.display());
expand_scope_entry(&entry, &mut acc, &mut stack).unwrap();
assert_eq!(acc, vec![entry]);
}
#[test]
fn ordinary_scope_entries_still_split_on_commas() {
let mut acc = Vec::new();
let mut stack = HashSet::new();
expand_scope_entry("example.com,other.example", &mut acc, &mut stack).unwrap();
assert_eq!(acc, vec!["example.com", "other.example"]);
}
#[test]
fn parse_target_string_leaves_network_targets_alone() {
let target = parse_target_string("https://example.com:8443");
assert_eq!(target.protocol, Protocol::Https);
assert_eq!(target.address, "example.com");
assert_eq!(target.port, Some(8443));
}
}