//! Command-line interface for CERT-X-GEN
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use std::ffi::OsString;
use std::path::PathBuf;
/// Execution outcomes that can make a completed scan fail in CI.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum FailOnArg {
Confirmed,
Refuted,
Errored,
Skipped,
TimedOut,
}
impl FailOnArg {
pub fn status(self) -> cert_x_gen::types::ExecutionStatus {
use cert_x_gen::types::ExecutionStatus;
match self {
Self::Confirmed => ExecutionStatus::Confirmed,
Self::Refuted => ExecutionStatus::Refuted,
Self::Errored => ExecutionStatus::Errored,
Self::Skipped => ExecutionStatus::Skipped,
Self::TimedOut => ExecutionStatus::TimedOut,
}
}
}
const SCAN_SCOPE_ALIASES: &[&str] = &[
"target",
"targets",
"target-file",
"domain",
"domains",
"domain-file",
"cidr",
];
#[derive(Parser, Debug)]
#[command(
name = "cxg",
version,
about = "Advanced Multi-Language Security Scanning Engine",
long_about = "CERT-X-GEN is a next-generation security scanning engine that supports \
12 programming languages for template creation. Write security scanning \
templates in Python, JavaScript, Rust, Shell, YAML, C, C++, Java, Go, Ruby, \
Perl, or PHP - whatever works best for your use case!\n\n\
Local CLI binaries: cxg scan --scope cli://<binary> with CLI Security Baseline templates.\n\
Tauri apps: cxg pentest run --target-type tauri --codebase <repo> maps IPC commands \
and capability grants; --tauri-prove opts into in-process command proof.",
after_help = "Run 'cxg <command> --help' for full details on any command.\n\
\n\
Repository: https://github.com/Bugb-Technologies/cert-x-gen\n\
Documentation: https://docs.bugb.io/cxg/\n\
Issues: https://github.com/Bugb-Technologies/cert-x-gen/issues",
after_long_help = "KEY FEATURES:
🎯 12 Programming Languages: Python, JavaScript, Rust, C, C++, Java, Go, Ruby, Perl, PHP, Shell, YAML
🔧 Flexible Port Configuration: Add or override ports per scan
🔍 Powerful Template Search: Full-text search, regex, content search, multiple filters
⚡ High Performance: Parallel execution, compilation caching for compiled languages
📊 Multiple Output Formats: JSON, CSV, SARIF, HTML, Markdown
🔌 Extensible: Custom templates in any supported language
EXAMPLES:
# Local CLI binary (CLI Security Baseline from the detection-template repository)
cxg template update
cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation
# Tauri source map, then optional in-process command proof (no live webview)
cxg pentest install
cxg pentest run --target-type tauri --codebase ./app-repo
cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove
# Basic scanning
cxg scan --scope example.com
cxg scan --scope https://api.example.com:8443 --ports 80,443,8080
cxg scan --scope 192.168.1.0/24 --top-ports 1000
# Bulk input
cxg scan --scope @targets.txt
cxg scan --scope file://scopes/internal.txt
# Advanced scanning with filters
cxg scan --scope example.com --template-language python,rust
cxg scan --scope example.com --severity critical,high
cxg scan --scope example.com --tags database,unauthenticated
# Template search
cxg search --query \"redis\"
cxg search --language python --severity high
cxg search --query \"injection\" --content --regex
cxg search --tags \"database,unauthenticated\" --format json
# Template management
cxg template list
cxg template list --language c --severity critical
cxg template info redis-unauthenticated
# Template search
cxg search --query \"redis\"
cxg search --language python --severity high
cxg search --tags \"injection,sql\" --format json
# Configuration
cxg config generate --output config.yaml
cxg scan --config config.yaml --scope example.com
# Output formats
cxg scan --scope example.com --output-format json,csv,sarif
cxg scan --scope example.com --output results --output-format json
# Performance tuning
cxg scan --scope example.com --parallel-targets 100 --parallel-templates 20
cxg scan --scope example.com --timeout 60s --retry 5
# Stealth and safety
cxg scan --scope example.com --stealth --rate-limit 10
cxg scan --scope example.com --safe --passive
For detailed help on any command, use: cxg <command> --help
LINKS:
Repository: https://github.com/Bugb-Technologies/cert-x-gen
Documentation: https://docs.bugb.io/cxg/
Issues: https://github.com/Bugb-Technologies/cert-x-gen/issues"
)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Commands>,
/// Enable verbose output (-v: info+warn, -vv: +trace, -vvv: +debug)
#[arg(short, long, action = clap::ArgAction::Count, global = true)]
pub verbose: u8,
/// Disable colored output
#[arg(long, global = true)]
pub no_color: bool,
/// Configuration file path
#[arg(short, long, global = true, value_name = "FILE")]
pub config: Option<PathBuf>,
/// Update templates (shorthand for 'cxg template update')
#[arg(
long = "ut",
visible_alias = "update-templates",
global = true,
help = "Update templates from repository (shorthand for 'cxg template update')"
)]
pub update_templates: bool,
/// Auto-update templates before running (like Nuclei's behavior)
#[arg(
long,
global = true,
help = "Automatically update templates before running scan"
)]
pub auto_update_templates: bool,
/// Disable automatic template update check (like Nuclei's -duc flag)
#[arg(
long,
global = true,
help = "Disable automatic template update check on startup"
)]
pub disable_update_check: bool,
/// Update templates on every startup (aggressive mode)
#[arg(
long,
global = true,
conflicts_with = "disable_update_check",
help = "Force template update on every startup (aggressive)"
)]
pub update_templates_on_startup: bool,
}
impl Cli {
pub fn parse() -> Self {
Self::try_parse_from(std::env::args_os()).unwrap_or_else(|e| e.exit())
}
/// Build the pentest scan front door from the existing argument definitions.
/// Ordinary invocations retain clap's original parser and defaults.
pub fn try_parse_from<I, T>(args: I) -> Result<Self, clap::Error>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
let root = Self::command().mut_subcommand("pentest", |cmd| {
cmd.mut_subcommand("run", |run| {
run.mut_arg("no_author", |arg| arg.requires("template_dir"))
.mut_arg("codebase", |arg| {
arg.default_value(clap::builder::Resettable::Reset)
.required(true)
})
})
});
let run_definition = root
.find_subcommand("pentest")
.unwrap()
.find_subcommand("run")
.unwrap()
.clone();
let replay_options: Vec<_> = run_definition
.get_arguments()
.filter(|arg| !authoring_option(arg.get_id().as_str()) && arg.get_id() != "target")
.cloned()
.collect();
let root = root.mut_subcommand("scan", |mut scan| {
for arg in replay_options {
if !scan
.get_arguments()
.any(|existing| existing.get_id() == arg.get_id())
{
scan =
scan.arg(arg.help_heading("Probe engine (scanner contracts unaffected)"));
}
}
scan
});
if !args.iter().any(|arg| arg == "--pentest") {
return Self::with_scan_replay_inputs(
&root.try_get_matches_from(args)?,
run_definition,
);
}
let normal = root.clone();
let scan = root.find_subcommand("scan").unwrap();
let mut front = root
.find_subcommand("pentest")
.unwrap()
.find_subcommand("run")
.unwrap()
.clone()
.name("scan")
.bin_name("cxg scan --pentest");
let mut scan_only = Vec::new();
for arg in scan.get_arguments() {
if front
.get_arguments()
.any(|existing| existing.get_id() == arg.get_id())
{
continue;
}
let shared = matches!(arg.get_id().as_str(), "scope" | "templates" | "pentest");
if !shared {
scan_only.push((
arg.get_id().clone(),
format!("--{}", arg.get_long().unwrap()),
));
}
front = front.arg(arg.clone().hide(!shared));
}
// `scope`'s legacy --target alias collides with pentest's --target.
// Keep the actual target option and the identical --scope/-s/-t spellings.
front = front
.mut_arg("scope", |arg| {
arg.alias(None::<&str>).aliases(
SCAN_SCOPE_ALIASES
.iter()
.copied()
.filter(|alias| *alias != "target"),
)
})
.group(clap::ArgGroup::new("supplied_templates").args(["templates", "template_dir"]))
.mut_arg("no_author", |arg| {
arg.requires(clap::builder::Resettable::Reset)
.requires("supplied_templates")
});
let command = root.mut_subcommand("scan", |_| front);
// Select using clap itself so a value such as `--arg --pentest` cannot
// switch engines. Relax validation and make help inert for this pass;
// the selected parser performs all validation and renders its own help.
let selection = command
.clone()
.ignore_errors(true)
.mut_subcommand("scan", |cmd| {
cmd.disable_help_flag(true).arg(
clap::Arg::new("scan_help")
.long("help")
.short('h')
.action(clap::ArgAction::SetTrue),
)
})
.try_get_matches_from(args.clone())?;
let is_pentest = selection
.subcommand()
.is_some_and(|(name, sub)| name == "scan" && sub.get_flag("pentest"));
if !is_pentest {
return Self::with_scan_replay_inputs(
&normal.try_get_matches_from(args)?,
run_definition,
);
}
let mut matches = command.try_get_matches_from(args)?;
let (_, sub) = matches.remove_subcommand().unwrap();
for (id, flag) in scan_only {
if sub.value_source(id.as_str()) == Some(clap::parser::ValueSource::CommandLine) {
return Err(front_door_error(&format!("{flag} is a scan-only option that --pentest cannot honour; use `cxg scan --pentest --help` for pentest options")));
}
}
let mut run = PentestRunArgs::from_arg_matches(&sub)?;
let scopes = sub
.get_many::<String>("scope")
.map(|v| v.collect::<Vec<_>>())
.unwrap_or_default();
if !scopes.is_empty() {
if scopes.len() != 1 || run.target.is_some() {
return Err(front_door_error(
"--pentest requires one target; use either --scope URL or --target URL",
));
}
run.target = Some(scopes[0].clone());
}
if let Some(target) = &run.target {
let url = url::Url::parse(target).ok();
if !url.as_ref().is_some_and(|u| {
matches!(u.scheme(), "http" | "https")
&& u.host_str().is_some_and(|host| !host.contains(','))
}) {
return Err(front_door_error("--pentest requires one http:// or https:// target URL; hosts, CIDR, target lists/files and cli:// scopes are scan-only"));
}
}
let templates = sub
.get_many::<String>("templates")
.map(|v| v.collect::<Vec<_>>())
.unwrap_or_default();
if !templates.is_empty() {
if templates.len() != 1
|| run.template_dir.is_some()
|| !std::path::Path::new(templates[0]).is_dir()
{
return Err(front_door_error("--templates with --pentest requires one existing JS probe directory; template IDs, individual files and @lists are scan-only. Use --template-dir DIR. Convert scanner templates separately with `guardlink translate --from <template> --contract probe` using a GuardLink version that supports probe translation; --no-author never runs conversion"));
}
run.template_dir = Some(PathBuf::from(templates[0]));
}
let mut cli = Self::from_arg_matches(&matches)?;
cli.command = Some(Commands::Pentest(PentestCommand {
action: PentestAction::Run(run),
}));
Ok(cli)
}
fn with_scan_replay_inputs(
matches: &clap::ArgMatches,
definition: clap::Command,
) -> Result<Self, clap::Error> {
let mut cli = Self::from_arg_matches(matches)?;
if let Some(Commands::Scan(scan)) = &mut cli.command {
let (_, selected) = matches.subcommand().unwrap();
let selected_ids: std::collections::HashSet<_> =
selected.ids().map(|id| id.as_str()).collect();
let mut argv = vec![OsString::from("cxg-probe-inputs")];
for arg in definition.get_arguments() {
let id = arg.get_id().as_str();
if authoring_option(id)
|| !selected_ids.contains(id)
|| selected.value_source(id) != Some(clap::parser::ValueSource::CommandLine)
{
continue;
}
let flag = OsString::from(format!(
"--{}",
arg.get_long().expect("pentest option has a long name")
));
if matches!(
arg.get_action(),
clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
) {
argv.push(flag);
} else if let Some(values) = selected.get_raw(id) {
for value in values {
argv.push(flag.clone());
argv.push(value.to_os_string());
}
} else {
argv.push(flag);
}
}
let parser = definition
.mut_arg("codebase", |arg| arg.required(false).default_value("."))
.mut_arg("no_author", |arg| {
arg.requires(clap::builder::Resettable::Reset)
});
scan.probe_run = Some(Box::new(PentestRunArgs::from_arg_matches(
&parser.try_get_matches_from(argv)?,
)?));
}
Ok(cli)
}
}
// All other engine inputs are replay controls and reuse their original clap definitions.
fn authoring_option(id: &str) -> bool {
matches!(
id,
"goal"
| "max_templates"
| "mutation_retries"
| "ai_provider"
| "ai"
| "generation_timeout"
| "batch_size"
| "deterministic_templates"
| "skills_file"
)
}
fn front_door_error(message: &str) -> clap::Error {
clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, message)
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Run templates against network targets or local CLI binaries (cli://<binary>)
Scan(ScanArgs),
/// Build a target with instrumentation so a scan can earn its verdict
///
/// `cxg scan` inspects a binary and refuses; it never builds the target.
/// This is the deliberate opt-in on the other side of that line, and it is
/// a separate verb rather than a scan flag for three reasons: building
/// runs the project's own build system (`build.rs`, `configure`, arbitrary
/// `Makefile` recipes) as you, which is a different trust decision from
/// reading a file; it costs minutes and gigabytes, which is a bad surprise
/// as a side effect and a fine one as a decision; and one instrumented
/// build feeds many scans.
///
/// It prints one JSON manifest and nothing else. There is no path from
/// "I could not instrument this" to "here is a binary": every precondition
/// failure is a `skipped` with a machine-readable reason, and the last
/// check re-reads the binary that was just produced, so a build that
/// accepted the flags and silently dropped them skips rather than passes.
Build(BuildCommand),
/// Manage templates
Template(TemplateCommand),
/// AI-powered template generation
Ai(AiCommand),
/// Search templates
///
/// After `cxg template update`, use `cxg template search baseline --tags cli`
/// to discover CLI Security Baseline templates from cert-x-gen-templates.
Search(SearchArgs),
/// Run as API server [NOT IMPLEMENTED — returns an error]
Server(ServerArgs),
/// Generate configuration file
Config(ConfigCommand),
/// Manage per-language dependency environments (does not confine execution)
Sandbox(SandboxCommand),
/// MCP (Model Context Protocol) server for AI agent integration
Mcp(McpCommand),
/// Whitebox pentests for web/Electron; Tauri source maps and optional in-process proof
///
/// Web/Electron: reads `whitebox/findings.sarif` produced by guardlink, ranks threats against an
/// operator goal, and asks your local AI CLI (claude / codex / gemini) to write
/// JavaScript probe templates that read the target's source to craft code-aware
/// payloads. Those templates execute in N parallel authenticated Chromium contexts,
/// emitting confirmed/refuted/ambiguous findings to a JSON report plus a JSONL audit
/// log of every HTTP request.
///
/// Tauri instead maps IPC commands and capability grants against the threat model;
/// --tauri-prove opts into command proof in a headless harness, without a live webview.
///
/// Web/Electron capabilities:
/// • Interactive auth capture for SSO/MFA flows (no need to script logins)
/// • Chained-auth probes (IDOR cross-user) via `--auth-numbers 2+`
/// • Pre-flight identity inspection — landing-test based, no /me-path required
/// • Goal-driven LLM ranking of guardlink hypotheses
/// • Validator-guarded code-generation with hard 240s timeout per AI call
/// • Retry-with-mutation on AMBIGUOUS triage (max N retries, env-bound skip)
/// • Scope enforcement (URL/method allowlist, per-endpoint budget, 5xx hard-kill)
/// • Cookie-jar primitives in templates (HttpOnly-aware via Playwright)
/// • Out-of-band callbacks in two modes: inject a canary cxg cannot read
/// (`--oast`), or register one cxg owns and polls (`--oast-interactsh`) —
/// only the second yields an in-band blind-vuln confirmation
/// • Per-profile custom headers (WAF bypass, internal-test headers)
/// • Split report: confirmed_findings vs mitigation_verifications vs ambiguous
Pentest(PentestCommand),
/// Update cxg to the latest released build
Update(UpdateCommand),
/// Display version information
Version,
}
/// `cxg build` — produce an instrumented build of a compiled target.
///
/// Cargo/Rust is the only back end today; every other recognised build system
/// skips with `build-system-not-implemented`, which is the honest answer
/// rather than a hidden limitation.
// @comment -- "CLI options for the instrumented build-assist; drives the target's own build system"
#[derive(Parser, Debug, Clone)]
pub struct BuildCommand {
#[arg(
long,
help = "Build the target with sanitizer instrumentation",
long_help = "Build the target with sanitizer instrumentation. Required: `cxg build` has \
no other mode, and demanding the word keeps room for one without changing \
what this invocation means."
)]
pub instrument: bool,
#[arg(
long,
value_name = "DIR",
default_value = ".",
help = "Project directory whose build system to drive",
long_help = "Directory holding the project to build. The build system is detected from \
its marker files in priority order (Cargo.toml, CMakeLists.txt, go.mod, \
configure, Makefile, meson.build); Cargo.toml first, so a polyglot \
repository such as a Tauri app instruments its Rust binary. A tree matching \
none of them skips with unknown-build-system rather than being guessed at."
)]
pub project: PathBuf,
#[arg(
long,
value_name = "NAME",
help = "Which binary target to build",
long_help = "Which binary target to build. Inferred when the project has exactly one; a \
workspace with several skips with binary-target-ambiguous rather than \
instrumenting one nobody asked for."
)]
pub bin: Option<String>,
#[arg(
long,
value_name = "LIST",
default_value = "address",
help = "Comma-separated sanitizers to build with",
long_help = "Comma-separated sanitizers, in rustc's vocabulary: address, thread, memory. \
Capability is asked of rustc per target rather than guessed, so a request \
the target cannot serve (MSan on arm64 macOS) skips with \
sanitizer-unsupported-on-target. Note that Rust has NO UBSan -- \
-Zsanitizer=undefined does not exist on any target -- so `undefined` skips \
with a note naming the Rust equivalent for the integer class, \
-C overflow-checks=on, which cxg passes on every instrumented build anyway."
)]
pub sanitizer: String,
#[arg(
long,
value_name = "DIR",
help = "Where to put the instrumented build tree",
long_help = "Where to put the instrumented build tree; defaults to \
<project>/target-instrumented. Never the project's own target/: RUSTFLAGS \
is part of cargo's fingerprint, so sharing one forces a full rebuild in \
both directions every time you alternate between an instrumented scan and \
ordinary work. Budget several gigabytes per instrumented project."
)]
pub out: Option<PathBuf>,
#[arg(
long,
help = "Rebuild std with the sanitizer (-Zbuild-std)",
long_help = "Rebuild std with the sanitizer. Needs the rust-src component. Mandatory for \
MSan, whose uninstrumented std reports uninitialised reads everywhere, and \
merely better for ASan, which interposes the allocator and so catches heap \
errors through a precompiled std. Off by default."
)]
pub build_std: bool,
#[arg(
long,
value_name = "PATH",
help = "Also write the manifest to this file",
long_help = "Write the manifest to this file as well as to stdout. Hand it back to a \
scan with `cxg scan --instrumented-manifest <path>` so the scan trusts what \
cxg recorded at build time instead of re-inspecting the artefact."
)]
pub manifest: Option<PathBuf>,
#[arg(
short = 'q',
long,
help = "Print only the path of the instrumented binary",
long_help = "Print only the path of the instrumented binary, and nothing at all on a \
skip, for `cxg scan --scope cli://$(cxg build --instrument --project . -q)`. \
The exit status still distinguishes the two: 0 instrumented, 3 skipped."
)]
pub quiet: bool,
}
/// `cxg update` — self-update the binary from the latest GitHub release.
// @comment -- "CLI options for the self-update command; downloads a release binary and replaces the running executable"
#[derive(Parser, Debug, Clone)]
pub struct UpdateCommand {
/// Only check whether a newer version exists; don't download or install
#[arg(long)]
pub check: bool,
/// Install a specific release tag (e.g. v1.2.0) instead of the latest
#[arg(long)]
pub version: Option<String>,
/// Skip the confirmation prompt before replacing the binary
#[arg(long, short = 'y')]
pub yes: bool,
#[arg(
long,
help = "Replace the binary even when a package manager owns it",
long_help = "Replace the binary even when a package manager owns it. Without this, a cxg \
installed by Homebrew, by `cargo install` or inside a container is left \
alone: `cxg update` prints the command that upgrades it through its manager \
and exits with status 3, because replacing the file behind the manager's \
back leaves the manager believing the old version is installed."
)]
pub force: bool,
}
#[derive(Parser, Debug, Clone)]
#[command(after_help = "TARGETS:
web: live browser probes; --codebase and --target required, --auth optional.
electron: live desktop probes; also requires --app-cmd or --app-binary.
tauri: source map of IPC commands and capability grants correlated with GuardLink.
Requires --codebase with whitebox/findings.sarif; no --target, --auth or launch command needed.
Default report: tauri_surface_mapped, caveat enumerated_not_live_probed.
An empty findings list does not establish safety: no commands were invoked.
--tauri-prove builds an app copy for headless in-process command proof, without a live webview.
Local CLI binaries use cxg scan --scope cli://<binary>, not pentest run.
EXAMPLES:
cxg pentest install
guardlink sarif ./app-repo -p my-app -o ./app-repo/whitebox/findings.sarif
cxg pentest run --target-type tauri --codebase ./app-repo
cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove --tauri-prove-timeout 1200")]
pub struct PentestCommand {
#[command(subcommand)]
pub action: PentestAction,
}
// Keep these argument builders out of the large PentestAction builder's frame.
// Nested auth help must also fit the native Windows main-thread stack.
#[derive(clap::Args, Debug, Clone)]
pub struct PentestUpdateArgs {
/// Print only a machine-readable result on stdout.
#[arg(long)]
pub json: bool,
/// Explicitly replace a source-derived installation with the embedded bundle.
#[arg(long)]
pub from_embedded: bool,
}
#[derive(clap::Args, Debug, Clone)]
pub struct PentestStatusArgs {
/// Print binary version, digests, origin, freshness and interrupted state.
#[arg(long)]
pub json: bool,
}
#[derive(Subcommand, Debug, Clone)]
// @comment -- "clippy::large_enum_variant, allowed deliberately. Run already carries ~35 operator flags and sat just under the lint's 200-byte spread; adding --oast-interactsh pushed it over. The lint's remedy is to box the variant's payload, which here would mean a Box around a clap-derived struct that main.rs destructures field-by-field — a churn of every pentest call site, and an allocation on a path that parses one command line and exits, to save bytes on a value that exists once per process. The size is a true statement about a subcommand with this many flags, not a defect."
#[allow(clippy::large_enum_variant)]
pub enum PentestAction {
/// Safely install the pipeline; check (but never install) Python dependencies.
/// Explicit development installs retain source discovery, including CXG_SOURCE.
Install {
/// Refresh even when current, preserving the previous tree as a backup.
#[arg(long)]
force: bool,
},
/// Refresh from this binary's embedded bundle, offline; preserve previous files.
Update(PentestUpdateArgs),
/// Inspect pipeline content without Python, filesystem writes, or recovery.
Status(PentestStatusArgs),
/// Print installed orchestrator capabilities as JSON (no target contact).
///
/// Reports protocol features such as exact-threat-id, not target-type support or
/// evidence that a target was tested. See `cxg pentest run --help` for web,
/// Electron and Tauri targets; local CLI binaries use `cxg scan --scope cli://<binary>`.
/// Requires `cxg pentest install` first. Example: cxg pentest capabilities
Capabilities,
/// Capture — or, via a subcommand, import/verify — an authenticated session profile
///
/// Capture supports web and Electron only. Tauri source maps and in-process
/// proofs need no captured profile; use `cxg pentest run --target-type tauri
/// --codebase ./app-repo`. Local CLI scans need no browser auth profile either.
///
/// With no subcommand this captures interactively: it spawns a real headed Chromium
/// window. You log in by ANY means — username/password, SSO redirect, MFA prompt,
/// hardware key, magic link, OAuth popup. When the app dashboard is showing, press
/// ENTER in the terminal (or close the browser) and cxg snapshots cookies +
/// localStorage + sessionStorage from every origin the browser touched. The profile
/// is saved at `~/.cert-x-gen/auth/<profile>.json` plus metadata at
/// `<profile>.meta.json`.
///
/// A post-capture landing-test verifies the session works: it re-opens a fresh
/// browser context with the saved state, navigates to --target, and checks whether
/// the final URL/page looks like a login or the app dashboard.
///
/// Use `--auth-numbers N` for chained-auth scenarios (e.g. IDOR testing needs two
/// different identities). cxg prompts for a human-readable label for each capture.
///
/// For CI, where no human can drive a browser, use the subcommands instead:
/// `cxg pentest auth import` replays a session captured once and exported as a
/// Playwright storage_state, with no browser; `cxg pentest auth verify` checks a
/// saved session is still alive (exit 0 alive / non-zero dead) before a run spends
/// any AI budget.
///
/// Examples:
/// # Single interactive capture (no subcommand)
/// cxg pentest auth --target https://app.example.com --profile admin
///
/// # Two identities for chained-auth (e.g. IDOR victim + attacker)
/// cxg pentest auth --target https://app.example.com --profile pentest --auth-numbers 2
///
/// # Scripted login (no browser pop-up)
/// cxg pentest auth --target https://app.example.com --profile bot \
/// --creds 'user@example.com:hunter2' --login-path /api/auth/login
///
/// # Capture a profile that sends a WAF-bypass header on every request
/// cxg pentest auth --target https://app.example.com --profile pentest \
/// --header "x-test-automation:abc123xyz"
///
/// # CI: import a session captured once, then verify it before a run
/// cxg pentest auth import --profile pentest --target https://staging.app \
/// --storage-state ./pentest.storage.json
/// cxg pentest auth verify --profile pentest
// @comment -- "auth carries the interactive-capture flags AND hosts the CI subcommands (import/verify). args_conflicts_with_subcommands keeps the two modes from being mixed on one line. This mirrors the Python surface, where cxg_pentest.py forwards `auth <rest>` verbatim to auth.py's own login|import|verify|list subparsers; bare `cxg pentest auth ...` maps to `auth login` exactly as before. --target/--profile are Option here rather than required-at-clap ONLY because clap's derive does not honour subcommand_negates_reqs (the builder method works, the #[command(...)] attribute is a no-op in clap 4.5), so a required --target would wrongly be demanded of `auth import`/`auth verify` too. Their required-ness for the capture path is enforced in main.rs's None branch, so the capture happy path and its errors are unchanged."
#[command(args_conflicts_with_subcommands = true)]
Auth {
/// Target URL where login happens (e.g. https://app.example.com).
/// After capture, the landing-test verifier opens this URL with the saved
/// cookies; if it doesn't bounce to a login page, the session is alive.
///
/// Required for interactive capture (no subcommand). The `import`/`verify`
/// subcommands take their own `--target` instead.
#[arg(long)]
target: Option<String>,
/// Profile name. If --auth-numbers > 1, this is the PREFIX and final profiles
/// are named `<profile>-1`, `<profile>-2`, etc. Use a stable name so subsequent
/// `cxg pentest run --auth <profile>` invocations can reload it.
///
/// Required for interactive capture (no subcommand).
#[arg(long)]
profile: Option<String>,
/// Number of profiles to capture in sequence. Each capture opens its own
/// Chromium window and prompts for a label (e.g. "victim", "attacker", "admin").
/// Required ≥2 for chained-auth probes like IDOR cross-user tests.
#[arg(long, default_value = "1")]
auth_numbers: usize,
/// Inline credentials `email:password` for scripted login (skips browser pop-up).
/// Only works for password-based auth — SSO/MFA flows MUST use interactive capture.
#[arg(long)]
creds: Option<String>,
/// File with `profile:email:password[:label]` per line for scripted batch capture.
/// Useful for re-auth between scans of password-only test apps.
#[arg(long)]
creds_file: Option<PathBuf>,
/// Endpoint path for scripted login POST. Only used with `--creds` or `--creds-file`.
/// The captured browser will POST {email, password} as JSON to <target><login-path>.
#[arg(long, default_value = "/api/auth/login")]
login_path: String,
/// Human-readable label for the profile (e.g. "admin", "low-priv-user").
/// Shown in scan output to make findings readable. Does not affect behavior.
#[arg(long)]
label: Option<String>,
/// Authenticated API liveness endpoint checked after capture and saved with
/// the profile for later verification. Defaults to /api/me.
#[arg(long)]
verify_url: Option<String>,
/// Custom HTTP header `NAME:VALUE` sent on every outbound request from this
/// profile's browser context — including login, every scan probe, every health
/// check. Repeatable for multiple headers. Saved with the profile so future
/// `cxg pentest run --auth <profile>` invocations reuse them automatically.
///
/// Use case: WAF-bypass tokens granted by infra (e.g. `x-test-automation`),
/// internal-test headers, custom forwarding hints.
///
/// SECURITY: header values are stored in plaintext under
/// `~/.cert-x-gen/auth/<profile>.meta.json`. Treat the file like a credential.
/// `chmod 600` if your machine has multiple users. Delete the profile when
/// the engagement ends. Header values are sent to EVERY origin the browser
/// touches, including IDPs — keep this in mind for SSO flows.
#[arg(long = "header", value_name = "NAME:VALUE")]
headers: Vec<String>,
/// Explicit privilege rank for this identity: an integer 0-100 or an alias
/// high/medium/low (= 90/50/10). Overrides the role-based heuristic and is fed to
/// the AI ranker so it selects the right identity per probe (lowest tier for
/// privesc, etc.). Omit to auto-derive from the app's role. In multi-capture
/// (--auth-numbers > 1) this pre-fills the per-identity prompt.
#[arg(long)]
tier: Option<String>,
/// Semantic role hint (e.g. "billing-analyst") passed to the AI as extra context —
/// useful when the app's /me endpoint exposes no clear role field.
#[arg(long)]
persona: Option<String>,
/// Peer-group name (e.g. "analyst-team-a"). Give two SAME-permission, DIFFERENT-user
/// sessions the same cohort so the AI treats them as peers and targets horizontal
/// IDOR / cross-tenant access between them.
#[arg(long)]
cohort: Option<String>,
/// Free-form `NAME=VALUE` context attached to the profile and shown to the AI.
/// Repeatable.
#[arg(long = "tag", value_name = "NAME=VALUE")]
tags: Vec<String>,
/// Target type to capture auth for.
///
/// `web` (default): the existing authenticated-browser capture against an HTTP
/// application. `electron`: launch the Electron desktop app and capture its
/// session state instead of a browser's.
///
/// Auth capture does not support Tauri. Its source map and optional in-process
/// proof need no captured profile; select tauri on `cxg pentest run` instead.
// @comment -- "selects which substrate auth capture launches against; an unknown value is rejected by clap so a typo can never silently downgrade a desktop capture to a web capture"
// requires_if (not required_if_eq on app_cmd) is deliberate: clap's required_if_eq/
// required_unless validation path skips the conflicts_with escape hatch, so pairing it
// with app_cmd's conflicts_with would wrongly demand --app-cmd even when --app-binary
// alone was supplied. requires_if instead feeds the required-arg resolution path that
// does consult conflicts_with. See desktop_flag_tests::auth_electron_with_app_binary_alone_parses.
#[arg(long, default_value = "web", value_parser = ["web", "electron"], requires_if("electron", "app_cmd"))]
target_type: String,
/// Command that launches the desktop app, e.g. "npm run electron:dev".
///
/// Required with `--target-type electron` unless `--app-binary` is given.
/// cxg appends `--remote-debugging-port` and a per-identity `--user-data-dir`.
// @comment -- "operator-supplied launch command forwarded to the orchestrator, which splits and executes it as a child process per identity"
// @g.source (#operator_app_cmd) -- "command string supplied by the operator on the command line"
#[arg(long, conflicts_with = "app_binary")]
app_cmd: Option<String>,
/// Path to a built desktop app, e.g. /Applications/Foo.app.
///
/// Alternative to `--app-cmd`; the two are mutually exclusive.
// @comment -- "operator-supplied path to a packaged application, executed directly instead of via a launch command"
#[arg(long, conflicts_with = "app_cmd")]
app_binary: Option<String>,
/// Non-interactive CI subcommand (`import` or `verify`). Absent = interactive
/// capture using the flags above.
// @comment -- "optional so bare `cxg pentest auth --target ... --profile ...` still means interactive capture; present it routes to the browser-free import/verify paths auth.py exposes for CI"
#[command(subcommand)]
auth_sub: Option<AuthSubcommand>,
/// Auth profile directory (also honours CERT_X_GEN_HOME).
#[arg(long)]
auth_dir: Option<PathBuf>,
},
/// List saved auth profiles under ~/.cert-x-gen/auth/
///
/// Shows profile name, label, target URL, and whether extra_headers are present.
/// Useful before running `cxg pentest run --auth <name>` to confirm which profile
/// you'll be scanning as.
AuthList {
/// Read saved profiles from this directory.
#[arg(long)]
auth_dir: Option<PathBuf>,
},
/// Write an example scope.yaml the operator can edit
///
/// scope.yaml controls the safety rails for a scan: method allowlist (default
/// GET/POST/HEAD/OPTIONS — DELETE/PUT/PATCH require `--destructive-ok`), URL
/// allow/blocklist regexes, per-endpoint and total request budgets, 5xx-streak
/// hard-kill threshold, and the `authorization_attestation` field that's recorded
/// in the audit log header.
///
/// Example:
/// cxg pentest scope-init -o my-engagement-scope.yaml
ScopeInit {
/// Output file path. Default: scope.yaml in the current directory.
#[arg(short, long, default_value = "scope.yaml")]
output: PathBuf,
},
/// Run the full end-to-end pentest pipeline against a target
///
/// Targets: web and Electron use live probes. Tauri maps IPC commands and JSON
/// capability grants from source, correlated with the GuardLink threat model.
/// Install with `cxg pentest install` and generate `whitebox/findings.sarif`
/// with `guardlink sarif . -p my-app -o whitebox/findings.sarif` in the app repository.
/// Tauri requires --codebase; no --target, --auth or app launch command is needed.
/// Keep the default --template-lang js: the legacy py pipeline rejects Tauri.
///
/// A default Tauri report is tauri_surface_mapped with enumerated_not_live_probed:
/// commands are not invoked, and empty findings do not establish safety.
/// Opt in with --tauri-prove for headless in-process command proof; this needs
/// a Rust toolchain and the app's build prerequisites, and does not drive a live webview.
///
/// Web/Electron pipeline steps:
/// [1] Load guardlink hypotheses from `<codebase>/whitebox/findings.sarif`
/// [1b] Inspect captured auth profiles via landing-test
/// (`profile_inspect.inspect_profiles_async`)
/// [2] LLM-rank hypotheses against --goal + profile coverage; AI generates JS
/// templates that read source via Claude/Codex/Gemini's own Read/Grep tools
/// [3] Load + statically validate templates (`validator.py`)
/// [4] Open N parallel authenticated Chromium contexts; inject the cxg JS bridge
/// [5] Run each template; triage findings (CONFIRMED / REFUTED / AMBIGUOUS);
/// mutate-and-retry on payload-fixable AMBIGUOUS, skip environment-bound
/// [6] Write `report.json` and `audit.jsonl` to --session-dir
///
/// The full set of probes available to templates is documented in
/// `pentest/docs/TEMPLATES.md`. The runtime intelligence layer (validator, scope,
/// session health, mutation, triage, audit) is in `pentest/docs/ARCHITECTURE.md`.
///
/// Examples:
/// # Single-profile read-only scan with default settings
/// cxg pentest run --codebase ./repo --target http://localhost:8000 \
/// --auth admin --ai --ai-provider claude
///
/// # Two identities for IDOR/chained-auth, AI off → built-in probes only
/// cxg pentest run --codebase ./repo --target http://localhost:8000 \
/// --auth victim,attacker
///
/// # Verify mitigations only (skips unmitigated threats so you can confirm
/// # declared defenses hold at runtime). Useful for well-annotated codebases.
/// cxg pentest run --codebase ./repo --target https://staging.app \
/// --auth pentest --ai --ai-provider claude \
/// --mitigation-mode mitigated --max-templates 16
///
/// # SSRF testing against a canary cxg OWNS — it registers the interactsh
/// # session and polls it, so a callback becomes a confirmed finding
/// cxg pentest run --codebase ./repo --target https://staging.app \
/// --auth pentest --ai --ai-provider claude \
/// --oast-interactsh \
/// --goal "verify SSRF on /slack/proxy via OAST callback"
///
/// # Same probes, but against a canary cxg can only inject into (e.g. a Burp
/// # Collaborator host). Templates build the URL; YOU read the hit in
/// # Collaborator. Findings stay unconfirmed as far as cxg is concerned.
/// cxg pentest run --codebase ./repo --target https://staging.app \
/// --auth pentest --ai --ai-provider claude \
/// --oast c4ca4238a0b92.oastify.com \
/// --goal "test SSRF on /slack/proxy; check Collaborator for callbacks"
///
/// Exit codes:
/// 0 → no confirmed findings (clean scan)
/// 1 → no templates available (guardlink output missing or empty, or every
/// template in a replayed --template-dir was withheld for carrying no
/// `// @attach_scheme: path` header); report.json is still written
/// 2 → confirmed findings present
/// 3 → scan was hard-killed (5xx streak, scope violation) OR, under
/// `--no-restart`, a desktop target died mid-scan and was not relaunched
/// 4 → mis-specified run, refused at pre-flight before any probing: a
/// `--scope-file` cxg cannot read (missing, unreadable, invalid YAML,
/// not a mapping, empty file, or PyYAML absent), `--scope-file` with
/// `--template-lang py`, `--target-type electron` without `--app-cmd`/
/// `--app-binary`, `--oast` together with `--oast-interactsh`, or an auth
/// profile whose kind does not match the target substrate
/// 5 → a selected auth profile or service is dead, expired, or unverified by
/// its configured liveness endpoint, with or without `--ci`; probes for
/// ready services still run, and the report is `complete: false`,
/// `status: incomplete`. A blocked or failed request does not change the
/// exit code; it is listed in `request_failures` and also makes the
/// report `status: incomplete`
#[command(after_help = "SCAN FRONT DOOR:
cxg scan --pentest accepts every option listed above through the same pentest engine.
--scope URL aliases --target URL; --templates DIR aliases --template-dir DIR.
Supply one HTTP(S) URL; ports, CIDR, cli:// targets and scan-only filters are refused.
JS probes only; any-language probes are not yet supported. The legacy --template-lang py path remains available.
Convert scanner templates separately: guardlink translate --from <template> --contract probe
(requires a GuardLink version with probe translation; --no-author never converts).
--no-author --template-dir DIR guarantees zero model calls (ranking, generation and mutation disabled).
Pentest verdicts are engine-confirmed; ordinary scan findings remain template-reported.
TAURI EXAMPLES:
# Prepare the source threat model (after cxg pentest install)
guardlink sarif ./app-repo -p my-app -o ./app-repo/whitebox/findings.sarif
# Source map only; no commands invoked
cxg pentest run --target-type tauri --codebase ./app-repo
# Opt in to headless in-process command proof
cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove --tauri-prove-timeout 1200")]
Run(PentestRunArgs),
}
/// Arguments shared by `pentest run` and `scan --pentest`.
#[derive(clap::Args, Debug, Clone)]
pub struct PentestRunArgs {
#[command(flatten)]
pub probe_inputs: ProbeInputs,
/// Running target app URL. Both `http://` and `https://` are supported.
/// Every identity's traffic and liveness check go to this target, unless a profile
/// was imported with `--service`, which opts it into its own saved origin.
///
/// Required for `--target-type web` and `electron`; omit it for
/// `--target-type tauri`, which maps the IPC surface from source and navigates
/// nowhere. A web/Electron run without --target is refused at preflight (exit 4).
// @comment -- "Optional at clap level ONLY so a tauri source-surface map can omit it. The Python preflight refuses a web/electron run with no --target, so the live-probe paths keep their 'you must say what to probe' guarantee; main.rs forwards --target only when it is present, so an absent one reaches the orchestrator as the empty default it treats as 'no live target'."
#[arg(
long,
help_heading = "Target",
display_order = 2,
help = "Running target app URL (http:// or https://); omit for --target-type tauri"
)]
pub target: Option<String>,
/// Open N headed browser windows for interactive login at scan start, then run
/// the pipeline with the resulting fresh profiles. Each capture prompts you for
/// a per-identity label. Use this when your captured profiles have expired or
/// when you don't want to manage profile lifecycle separately.
///
/// Profiles are saved as `<--auth-profile>-1`, `<--auth-profile>-2`, etc.
#[arg(
long,
default_value = "0",
help_heading = "Authentication",
display_order = 13,
help = "Capture N fresh identities interactively at start"
)]
pub interactive_auth: usize,
/// Name prefix for `--interactive-auth` captures. The final profile names are
/// `<auth_profile>-1`, `<auth_profile>-2`, etc.
#[arg(
long,
default_value = "pentest",
help_heading = "Authentication",
display_order = 12,
help = "Name prefix for --interactive-auth captures"
)]
pub auth_profile: String,
/// Minimum auth contexts the scan requires. If you pass `--auth a,b` but
/// `--auth-numbers 3`, chained-auth templates that need 3 contexts will be
/// skipped with a warning. Pure usability check — engine doesn't fabricate
/// extra contexts.
#[arg(
long,
help_heading = "Authentication",
display_order = 14,
help = "Minimum auth contexts the scan requires"
)]
pub auth_numbers: Option<usize>,
/// File of `profile:email:password[:label]` lines used to AUTO RE-AUTH a
/// dead session mid-scan (the session-health monitor detects death via the
/// landing test). Without this, a probe that kills its own session — e.g.
/// session_replay's logout — leaves remaining probes unable to run.
///
/// Recommended for any scan with `--mutation-retries > 0` or scans with
/// SessionReplay / Csrf class templates.
#[arg(
long,
help_heading = "Authentication",
display_order = 15,
help = "Creds file for auto re-auth of a dead session"
)]
pub creds_file: Option<PathBuf>,
/// Template language. `js` (default): AI generates copy-paste-runnable JS
/// templates that drive the cxg JS bridge — recommended for all interactive
/// pentests. `py`: Python probe path (legacy) — only built-in probes in
/// `pentest/payloads/`, no AI generation.
#[arg(
long,
default_value = "js",
help_heading = "AI Generation",
display_order = 27,
help = "Template language: js (default; required for Tauri/Electron) or py (legacy web)"
)]
pub template_lang: String,
/// Natural-language pentest goal. Used as context for both LLM-based hypothesis
/// ranking AND template generation. Be specific about which vuln classes,
/// endpoints, or claims you want tested.
///
/// Examples:
/// "test for IDOR in records and transactions APIs"
/// "verify each declared @mitigates actually holds at runtime"
/// "find unguarded admin endpoints accessible to non-admin tokens"
#[arg(
long,
help_heading = "AI Generation",
display_order = 23,
help = "Natural-language pentest goal (ranking + generation)"
)]
pub goal: Option<String>,
/// Exactly select imported hypotheses carrying this GuardLink id before ranking.
/// Unknown ids refuse before target contact. Requires JS generation on web/electron;
/// disables unrelated discovery, boundary and host probes. Not authorization.
#[arg(long, help_heading = "AI Generation")]
pub threat_id: Option<String>,
/// Reuse JS templates from a previously-generated session directory. Skips the
/// AI generation step entirely. Useful for re-running the same templates against
/// different targets, or after fixing engine bugs that affected template execution.
///
/// Template directories are at `~/.cert-x-gen/templates/session-<timestamp>-<pid>/`.
/// JS probes are discovered recursively, using scan's exclusions for build
/// artifacts, dependencies, disabled templates and skeleton directories.
/// Scanner templates are refused: convert them separately with
/// `guardlink translate --from <template> --contract probe` using a GuardLink
/// version that supports probe translation. cxg never converts on replay.
///
/// A template carrying no `// @attach_scheme: path` header is WITHHELD — never
/// executed — and named in a `templates_withheld` caveat in report.json, because
/// it may have been generated under a same-named file's intent context. See
/// `pentest/docs/ARCHITECTURE.md` for the rule and the remedy for each case.
#[arg(
long,
help_heading = "AI Generation",
display_order = 28,
help = "Reuse JS probes recursively (skip ranking and generation)"
)]
pub template_dir: Option<PathBuf>,
/// Maximum number of templates the LLM ranker is allowed to select per scan.
/// Each template = one AI generation call (~60-180s with claude/codex). Lower for
/// fast feedback loops; higher for engagement-grade coverage.
#[arg(
long,
default_value = "8",
help_heading = "AI Generation",
display_order = 24,
help = "Max templates the LLM ranker may select"
)]
pub max_templates: usize,
/// Maximum times the AI is allowed to mutate a template after AMBIGUOUS triage.
/// Environment-bound AMBIGUOUS (missing role, missing primitive) skip mutation
/// automatically; only payload-fixable ones consume retries.
/// 0 disables the loop entirely.
#[arg(
long,
default_value = "2",
help_heading = "AI Generation",
display_order = 25,
help = "Max AI mutation retries on AMBIGUOUS triage"
)]
pub mutation_retries: usize,
/// AI provider. `auto` prefers the editor bridge when $BUGB_BRIDGE_URL is set,
/// then the first available CLI tool (claude > codex > gemini), falling back to
/// ANTHROPIC_API_KEY / OPENAI_API_KEY HTTP APIs. Otherwise specify explicitly.
/// CLI providers don't need API keys — they use your existing CLI auth.
///
/// Options: auto | bridge | claude | codex | gemini | anthropic | openai
///
/// `bridge` posts each prompt to $BUGB_BRIDGE_URL (with Authorization: Bearer
/// $BUGB_BRIDGE_TOKEN when set) and reads the completion back — an editor/CI
/// integration point rather than a local CLI.
#[arg(
long,
default_value = "claude",
help_heading = "AI Generation",
display_order = 22,
help = "AI provider: auto|bridge|claude|codex|gemini|crush|anthropic|openai"
)]
pub ai_provider: String,
/// Enable AI-driven template generation. Without `--ai`, only built-in probes
/// from `pentest/payloads/` run. With `--ai`, the orchestrator invokes the
/// chosen `--ai-provider` to read the codebase and synthesize code-aware
/// templates per guardlink hypothesis.
#[arg(
long,
help_heading = "AI Generation",
display_order = 21,
help = "Enable AI-driven template generation"
)]
pub ai: bool,
/// Show Chromium windows during scan instead of running headless. Useful for
/// debugging probes, watching auth flows, or when WAF bot-detection is blocking
/// headless requests (real Chromium has a stronger fingerprint than headless).
#[arg(
long,
help_heading = "Execution",
display_order = 43,
help = "Show Chromium windows instead of running headless"
)]
pub headed: bool,
/// Allow DELETE/PUT/PATCH methods AND paths matching destructive regexes
/// (`/wipe`, `/delete-all`, `/factory-reset`, etc.) in scope.yaml.
/// Default OFF. Required for templates that test destructive-action authz.
///
/// USE WITH CARE on production targets. The engine emits a warning at startup
/// and every blocked request is still recorded in the audit log.
#[arg(
long,
help_heading = "Execution",
display_order = 42,
help = "Allow DELETE/PUT/PATCH + destructive paths (use with care)"
)]
pub destructive_ok: bool,
/// Free-text written authorization statement recorded in the audit log header.
/// Include engagement ID, operator name, change-management ticket, etc.
///
/// Example: "Engagement PT-2026-003, operator J. Doe, ticket CHG-1234"
///
/// Strongly recommended for any non-local scan. The audit log header is the
/// dispute-ready record of "I had authorization to do this scan."
#[arg(
long,
help_heading = "Execution",
display_order = 47,
help = "Written authorization statement for the audit log"
)]
pub attestation: Option<String>,
/// Hypothesis filter by declared-mitigation status from guardlink:
/// `any` — all HTTP-testable hypotheses (default)
/// `unmitigated` — only threats WITHOUT a declared @mitigates
/// (find unguarded holes)
/// `mitigated` — only threats WITH @mitigates declared
/// (verify defenses actually hold at runtime)
#[arg(
long,
default_value = "any",
help_heading = "AI Generation",
display_order = 29,
help = "Hypothesis filter: any|unmitigated|mitigated"
)]
pub mitigation_mode: String,
/// Authenticated API liveness endpoint. Per-profile liveness_check takes
/// precedence; 401/403 means dead, and a configured endpoint that does not answer
/// 2xx leaves the session unverified. When nothing is configured and the default
/// /api/me is absent (404, an HTML page, a redirect), the landing test decides
/// instead. The API JSON also supplies role/email/id.
#[arg(
long,
default_value = "/api/me",
help_heading = "Authentication",
display_order = 16,
help = "Authenticated API liveness endpoint (default /api/me; per-profile setting wins)"
)]
pub me_path: String,
/// Hard wall-clock timeout per AI generation call. The whole process tree is
/// killed if exceeded. Default 240s.
///
/// Claude CLI typically takes 60-170s per template; Codex 90-220s; Gemini 30-180s.
/// Bump to 600+ for very large codebases the AI has to grep through.
#[arg(
long,
default_value = "240",
help_heading = "AI Generation",
display_order = 26,
help = "Hard timeout per AI generation call, seconds (default 240)"
)]
pub generation_timeout: u64,
/// Skip periodic session health checks and re-authentication. Startup API
/// verification still runs, so a dead or expired profile still exits 5; this
/// flag supplies no proof for denial verdicts.
#[arg(
long,
help_heading = "Authentication",
display_order = 17,
help = "Skip periodic health checks (startup API verification still runs; a dead profile still exits 5)"
)]
pub skip_health_check: bool,
/// Ignore server TLS certificate errors for web browser and raw HTTP requests
#[arg(long)]
pub insecure_tls: bool,
/// Proxy server URL for web browser and raw HTTP requests
#[arg(long)]
pub proxy: Option<String>,
/// PEM client certificate for the target origin
#[arg(long, requires = "client_key")]
pub client_cert: Option<PathBuf>,
/// PEM private key for the client certificate
#[arg(long, requires = "client_cert")]
pub client_key: Option<PathBuf>,
/// An external out-of-band callback host cxg can INJECT INTO but cannot read
/// back (Burp Collaborator, a canary you host, an interactsh domain you
/// generated yourself). Exposed to templates as `cxg.oast.url(label, scheme?)`
/// so payloads carry a callback URL — but cxg never learns whether it fired,
/// so nothing here confirms anything: blind probes (SSRF, blind SQLi, blind
/// XXE, blind cmd-injection) still fall back to status-code heuristics and
/// timing, and the AI prompt is instructed to mark them `confirmed=false`.
/// Reading the callback is the operator's job, in their own tooling.
///
/// Want cxg to do the confirming? Use `--oast-interactsh` instead.
///
/// Example: `--oast c4ca4238a0b923820dcc.oastify.com`
///
/// If the host is an interactsh domain rather than a Collaborator one, run
/// `interactsh-client` in another terminal first and paste the hostname it
/// prints — that terminal is the only place these callbacks become visible.
///
/// (With `--oast-interactsh` there is no second terminal: cxg is the client.)
// @comment -- "operator-supplied callback host injected into payloads; kept exactly as it was, value and all, because every existing invocation and every template calling cxg.oast.url() depends on it"
// @comment -- "help text deliberately no longer claims 'definitive blind-vuln confirmation': cxg holds no session for a host it was merely handed, so it cannot poll it, and an operator who read the old wording would take an unconfirmed finding for a confirmed one"
#[arg(
long,
value_name = "HOST",
help_heading = "OAST",
display_order = 31,
help = "OAST canary cxg injects but cannot read back (unconfirmed)"
)]
pub oast: Option<String>,
/// Register an interactsh session cxg OWNS and poll it — the mode that can
/// actually confirm a blind vulnerability. Because cxg registered the session
/// it holds the correlation id, so templates can call `cxg.oast.poll(label)`,
/// read the interactions back in-band, and a callback becomes a genuine
/// `confirmed=true` finding with the interaction recorded as evidence. cxg is
/// the interactsh client here; you do not run one alongside it.
///
/// The optional value is the interactsh server to register against; omit it to
/// use interactsh's default public servers.
///
/// Mutually exclusive with `--oast`. Two canaries would split payloads between
/// a host cxg can poll and one it cannot, so "was this confirmed?" would have
/// no single answer per finding.
///
/// Examples: `--oast-interactsh` (default servers), or
/// `--oast-interactsh https://oast.example.internal` (your own instance).
// @comment -- "selects the OAST mode in which cxg registers and therefore can read the canary; the server URL, when given, is the interactsh instance the session is registered against"
// @comment -- "conflicts_with rather than a runtime if-both check, matching --app-cmd/--app-binary above: clap then rejects the pair during parse with the standard usage error, before any scan work, and the constraint is visible in --help instead of hiding in main()"
// @comment -- "num_args = 0..=1 with an empty default_missing_value keeps the value optional and distinguishes the three states the mode needs — absent (None, no session), bare (Some(\"\"), default servers), explicit (Some(url)). An Option<Option<String>> would encode the same thing while making every downstream match arm nested for no gain"
// @g.source (#operator_oast_server) -- "interactsh server URL supplied by the operator on the command line"
#[arg(
long,
value_name = "SERVER_URL",
num_args = 0..=1,
default_missing_value = "",
conflicts_with = "oast",
help_heading = "OAST",
display_order = 32,
help = "OAST canary cxg owns and polls (confirms blind vulns)"
)]
pub oast_interactsh: Option<String>,
/// Host a built-in OAST callback cxg OWNS and poll it, bound to an interface
/// the TARGET can reach rather than to loopback — the mode that confirms a
/// blind vulnerability (SSRF, XXE, command injection, SSTI, NoSQL, LDAP,
/// deserialization) against a target with no internet egress, such as an
/// `env up` sandbox or internal staging, where `--oast-interactsh` cannot
/// (its public servers need egress) and `--oast` cannot be read back.
///
/// cxg holds the listener, so templates call `cxg.oast.poll(label)` and a
/// callback becomes a `confirmed=true` finding with the interaction as
/// evidence. The label rides in the URL path (`http://<host>/<label>`), not a
/// subdomain, because the bind address has no wildcard DNS under it.
///
/// The optional value selects the bind: omit it or `docker-bridge` for the
/// docker bridge gateway (reachable from a container on the default bridge),
/// `host-docker-internal` for a Docker Desktop container, or an
/// address/hostname (e.g. `10.0.0.5`, or `ip:10.0.0.5`) for internal staging.
///
/// Mutually exclusive with `--oast` and `--oast-interactsh`: one canary per
/// run, or payloads split between callbacks nobody correlates per finding.
// @comment -- "forwarded as the OAST mode, not a session: pentest/oast_listener.py binds the socket and decides reachability, so the Rust and Python CLIs cannot disagree about whether this canary is pollable; the three states (absent/bare/explicit) are carried exactly as --oast-interactsh carries them"
#[arg(
long,
value_name = "BIND",
num_args = 0..=1,
default_missing_value = "",
conflicts_with_all = ["oast", "oast_interactsh"],
help_heading = "OAST",
display_order = 33,
help = "Built-in OAST listener cxg owns, reachable by an egress-less target"
)]
pub oast_listener: Option<String>,
/// Also start a DNS listener alongside `--oast-listener`, for a target whose
/// egress is filtered to DNS. Needs the target's resolver pointed at this host
/// and privilege to bind udp/53; a bind failure leaves the HTTP listener
/// working and notes the reason. No effect without `--oast-listener`.
#[arg(
long,
help_heading = "OAST",
display_order = 34,
help = "Add a DNS leg to --oast-listener (needs udp/53)"
)]
pub oast_listener_dns: bool,
/// Default Location URL for redirects staged with cxg.oast.redirect(label).
#[arg(
long,
requires = "oast_listener",
value_name = "URL",
help_heading = "OAST"
)]
pub oast_redirect_location: Option<String>,
/// Default HTTP redirect status (302 when omitted).
#[arg(long, requires = "oast_listener", value_parser = ["302", "307"], help_heading = "OAST")]
pub oast_redirect_status: Option<String>,
/// First A query per name returns the listener IPv4; later queries return
/// this IPv4, all with TTL 0. The target resolver must reach this DNS server.
#[arg(long, requires_all = ["oast_listener", "oast_listener_dns"], value_name = "IPV4", help_heading = "OAST")]
pub oast_dns_rebind_ip: Option<String>,
/// Target type to pentest.
///
/// `web` (default): the existing authenticated-browser pipeline against an HTTP
/// application. `electron`: launch N isolated instances of an Electron desktop
/// app, drive their renderers over CDP, and additionally probe IPC channels,
/// renderer configuration, and local data at rest.
///
/// `tauri`: map a Tauri app's IPC command and capability surface from source —
/// the `#[tauri::command]` handlers, their `generate_handler!` registration, and
/// the `capabilities/*.json` grants — and correlate it against the guardlink
/// threat model. This is a source-surface MAP, not a live probe: a Tauri app
/// exposes no CDP endpoint on macOS or Linux, so cxg cannot drive its webview the
/// way it drives an Electron renderer. `--target` is not required for it, and the
/// default report carries an `enumerated_not_live_probed` caveat. No command is
/// confirmed or refuted unless `--tauri-prove` opts into the in-process harness.
/// No --auth or app launch command is needed. Keep --template-lang js; py is rejected.
///
/// EXAMPLES:
///
/// cxg pentest run --target-type electron --app-cmd "npm run electron:dev" \
/// --codebase ./app-repo --target https://api.example.com --auth desk-1,desk-2
///
/// cxg pentest run --target-type tauri --codebase ./app-repo
// @comment -- "selects which substrate the orchestrator uses; an unknown value is rejected by clap so a typo can never silently downgrade a desktop scan to a web scan, nor a web scan to a source-only tauri map"
// requires_if (not required_if_eq on app_cmd) is deliberate: clap's required_if_eq/
// required_unless validation path skips the conflicts_with escape hatch, so pairing it
// with app_cmd's conflicts_with would wrongly demand --app-cmd even when --app-binary
// alone was supplied. requires_if instead feeds the required-arg resolution path that
// does consult conflicts_with. See desktop_flag_tests::electron_with_app_binary_alone_parses.
// tauri is accepted here but needs no launch mechanism (it never starts the app) and no
// --target (it never navigates); both facts are enforced in the Python preflight, which
// is the single place target-type-conditional requirements live.
#[arg(
long,
default_value = "web",
value_parser = ["web", "electron", "tauri"],
requires_if("electron", "app_cmd"),
help_heading = "Target",
display_order = 3,
help = "Target type: web, electron, or tauri (source map; optional --tauri-prove)"
)]
pub target_type: String,
/// Command that launches the desktop app, e.g. "npm run electron:dev".
///
/// Required with `--target-type electron` unless `--app-binary` is given.
/// cxg appends `--remote-debugging-port` and a per-identity `--user-data-dir`.
// @comment -- "operator-supplied launch command forwarded to the orchestrator, which splits and executes it as a child process per identity"
// @g.source (#operator_app_cmd) -- "command string supplied by the operator on the command line"
#[arg(
long,
conflicts_with = "app_binary",
help_heading = "Target",
display_order = 4,
help = "Command that launches the desktop app (electron)"
)]
pub app_cmd: Option<String>,
/// Path to a built desktop app, e.g. /Applications/Foo.app.
///
/// Alternative to `--app-cmd`; the two are mutually exclusive.
// @comment -- "operator-supplied path to a packaged application, executed directly instead of via a launch command"
#[arg(
long,
conflicts_with = "app_cmd",
help_heading = "Target",
display_order = 5,
help = "Path to a built desktop app (electron)"
)]
pub app_binary: Option<String>,
/// Additionally scan a real installation directory for data at rest.
///
/// By default host probes read only the isolated user-data directories cxg
/// created itself. Pass this to opt in to scanning an existing install.
// @comment -- "opt-in expansion of host-probe scan scope beyond cxg-created directories, since reading an operator's real install is host-level access"
#[arg(
long,
help_heading = "Target",
display_order = 6,
help = "Also scan a real install dir for data at rest (electron)"
)]
pub host_scan_path: Option<String>,
/// For `--target-type tauri`: after mapping the IPC surface, build an in-process
/// proof harness against the app's own crate (Tauri's `test` feature) and drive
/// ranked commands through `get_ipc_response` with hostile arguments, feeding
/// confirmed / refuted / unevaluated into the findings. Needs a Rust toolchain; a
/// command the harness cannot drive is skipped with a reason, never refuted.
///
/// Copies the app to the session's tauri-harness/ and runs cargo test using
/// a headless MockRuntime. Probes cover sentinel-based path traversal and
/// renderer-controlled authorization arguments. A confirmation proves observed
/// harness behavior; a refutation covers only attempted arguments. It does not
/// test live navigation, DOM behavior or clickjacking, nor reproduce the app's
/// full setup or capability configuration. Review caveats, ambiguous and
/// tauri_skipped_commands; build failures do not establish safety.
// @comment -- "opt-in because it builds the target crate (cargo test) and only applies to tauri; a plain tauri run stays a source-surface map. Forwarded to the Python orchestrator, which owns the harness."
#[arg(
long,
help_heading = "Target",
display_order = 7,
help = "tauri: prove commands in-process via Tauri's test harness"
)]
pub tauri_prove: bool,
/// Combined seconds budgeted for the `--tauri-prove` harness build and run.
///
/// Used only for Tauri proof; default 1200. Example: --tauri-prove-timeout 1200
#[arg(
long,
default_value = "1200",
help_heading = "Target",
display_order = 8,
help = "Timeout (s) for the --tauri-prove harness build+run"
)]
pub tauri_prove_timeout: u64,
/// Run cross-site probes (CSRF, CORS, clickjacking) from a loopback origin
/// cxg controls, in the same browsing context as the identity under test.
///
/// Without this, those classes are reported as NOT PROBED rather than tested
/// from the target's own origin. A same-origin probe of them is unsound: an
/// app defended only by an Origin check accepts cxg's own-origin request, so
/// the probe confirms an attack a real cross-site attacker could never land.
// @comment -- "Opt-in because it binds a listening socket on the operator's machine and performs REAL cross-site state changes against their application. Both are consequences an operator should choose rather than discover, which is why this is a flag and not a default even though it strictly improves verdict quality."
#[arg(
long,
help_heading = "Probe execution",
display_order = 7,
help = "Probe CSRF/CORS/clickjacking from a foreign origin cxg controls"
)]
pub attacker_origin: bool,
/// Generate templates for N hypotheses per AI call instead of one each.
///
/// Measured: 130-220s per AI template, so 105 routes cost ~4.5 hours.
/// Default 1 is the existing per-hypothesis path, byte-for-byte.
// @comment -- "Clamped to 5 inside the generator rather than here, so the blast radius of one timed-out call stays bounded: a failed batch costs a re-run of that chunk individually, and at 5 the worst case is five regenerations rather than fifty. Cached and deterministically-emittable hypotheses are excluded before batching, so a fully-cached run makes zero calls whatever this is set to."
#[arg(
long,
help_heading = "Hypothesis filtering",
display_order = 10,
default_value_t = 1,
help = "Hypotheses per AI generation call (1 = today's behaviour)"
)]
pub batch_size: usize,
/// Emit probes with no AI call at all for unambiguous shapes.
///
/// Covers cross-identity IDOR reads and missing collection authorization —
/// 47 of Juice Shop's 105 discovered routes. These probes read no source,
/// so they cannot cite a code-level cause; breadth, not depth.
// @comment -- "Opt-in because a deterministic probe is genuinely WEAKER than an AI-authored one: it cannot recognise an intentional design or name the guard that failed. An operator should choose that trade deliberately rather than inherit it from a default."
#[arg(
long,
help_heading = "Hypothesis filtering",
display_order = 11,
help = "Emit known-shape probes without an AI call (fast, source-blind)"
)]
pub deterministic_templates: bool,
/// Let a probe hand a fact it discovered to a later probe.
///
/// Templates declare `@provides: <name>` / `@requires_artifact: <name>`; cxg
/// orders providers before consumers and passes the value through a per-run
/// store. Edges are also derived automatically from guardlink `@flows`.
// @comment -- "Opt-in because it CHANGES TEMPLATE ORDER: a consumer waits for its provider, and one that declares an artifact nobody provides is skipped rather than run. With the flag off the order is the plain destructive_priority sort it has always been, so an existing run is unaffected."
#[arg(
long,
help_heading = "Probe execution",
display_order = 12,
help = "Allow multi-step chains: one probe hands a fact to the next"
)]
pub enable_chaining: bool,
/// Discover routes from source instead of requiring guardlink annotations.
///
/// guardlink only parses GAL annotations, so an un-annotated codebase yields
/// zero hypotheses and the scan exits with "no templates available" having
/// tested nothing. Measured on OWASP Juice Shop: guardlink 0, discovery 105.
// @comment -- "Opt-in because it changes WHAT gets tested: a discovered route is an attack SURFACE inferred from source, not a threat anybody declared, so its hypotheses are speculative in a way an annotated one is not. An annotated hypothesis always wins where both cover the same route. Default off keeps every existing run byte-identical."
#[arg(
long,
help_heading = "Hypothesis filtering",
display_order = 9,
help = "Also derive hypotheses from routes found in source (no annotations needed)"
)]
pub discover_routes: bool,
/// Do not read a code graph for this codebase.
///
/// By default, when `codegraph-mcp` or `bravos graph` is installed and a graph
/// has been built for the codebase, its route table leads `--discover-routes`
/// and its reachable-sink ranking orders which hypotheses get templates. With
/// no graph available the run is unchanged either way.
// @comment -- "Forwarded only, never interpreted here: the orchestrator owns the default and the detection, and this layer restating either would give the two CLIs two definitions of when the graph is read."
#[arg(
long,
help_heading = "Hypothesis filtering",
display_order = 12,
help = "Do not use a code graph for route discovery or ranking"
)]
pub no_code_graph: bool,
/// Test only the hypotheses whose route or enclosing function is listed in FILE.
///
/// Entries are `METHOD /path` (`ANY` or `*` for every method; path templates
/// and concrete paths match each other; a trailing `*` is a prefix), `/path`,
/// `file::Function` or `file:Function`, one per line, or JSON — including a code
/// graph's route or attack-surface answer as written. Everything else is
/// excluded before ranking and reported with its reason. An EMPTY list means
/// nothing is in scope: the run exits 0 without contacting the target.
// @comment -- "Forwarded only, never parsed here: the orchestrator owns the entry grammar, the empty-means-skip rule and the refusals, so this layer restating any of them would give the two CLIs two definitions of what the list admits."
#[arg(
long,
value_name = "FILE",
help_heading = "Hypothesis filtering",
display_order = 13,
help = "Test only the routes/functions listed in FILE (empty list = skip the run)"
)]
pub only_routes: Option<PathBuf>,
/// One allowlist entry in the `--only-routes` line form. Repeatable.
#[arg(
long = "only-route",
value_name = "ENTRY",
help_heading = "Hypothesis filtering",
display_order = 14,
help = "One allowlist entry, e.g. 'GET /api/users/{id}' (repeatable)"
)]
pub only_route: Vec<String>,
/// Append the operator skills in FILE to AI generation and mutation prompts.
///
/// Markdown written by a caller (bravos writes the skills its operator tagged
/// for template authoring). Appended last, under an untrusted heading: it is
/// advice on how to write a probe and never overrides the template rules.
// @comment -- "Forwarded only, never read here: the orchestrator owns the heading, the budget and the unreadable-file behaviour, so the two CLIs cannot disagree about what a skills file does."
#[arg(
long,
value_name = "FILE",
help_heading = "Hypothesis filtering",
display_order = 15,
help = "Append operator skills (untrusted guidance) to generation/mutation prompts"
)]
pub skills_file: Option<PathBuf>,
/// Permit `cxg.socket`: raw TCP/TLS bytes with no HTTP client in between.
///
/// Required for request smuggling, desync and header-order attacks, which no
/// HTTP client can express — both `window.fetch` and Playwright's
/// APIRequestContext normalise the framing that IS the payload for those
/// classes. Can desync connections or wedge a server.
// @comment -- "Permission, distinct from the substrate capability that says a socket is POSSIBLE. Byte-level traffic can wedge a target, and an operator must opt into that consequence rather than inherit it from their choice of --target-type. Without it, request_smuggling and http_desync hypotheses route to review_only_threats instead of consuming a template slot they could never conclude."
#[arg(
long,
help_heading = "Probe execution",
display_order = 8,
help = "Permit raw TCP/TLS byte-level probes (smuggling, desync)"
)]
pub allow_raw_socket: bool,
/// Save redacted per-template HARs and curl reproductions for web JS probes.
#[arg(long, help_heading = "Probe execution")]
pub capture_http: bool,
/// Permit native gRPC over HTTP/2, for services with no gRPC-Web proxy in
/// front of them. Requires grpcio. The call carries the identity's
/// --header values as gRPC metadata; cxg cannot borrow the browser
/// session on this transport.
// @comment -- "Permission, distinct from the substrate capability that says a native gRPC call is POSSIBLE from this process. cxg.grpc dials a host:port from outside the browser where no same-origin policy contains it, so an operator opts into that reach rather than inheriting it from --target-type. Without it, hypotheses whose route is a gRPC method go to review_only_threats instead of consuming a template slot they could never conclude."
// @comment -- "NOT the switch for gRPC-Web, which is an ordinary HTTP POST cxg.raw already sends on every run with no flag. This covers a BARE gRPC service, which nothing in cxg could reach at all before."
#[arg(
long,
help_heading = "Probe execution",
display_order = 9,
help = "Permit native gRPC (HTTP/2) probes against bare gRPC services"
)]
pub allow_grpc: bool,
/// A protoc-emitted FileDescriptorSet describing the target's gRPC
/// services, so probes can send real typed messages and decode responses.
/// Produce one with `protoc --descriptor_set_out=out.pb --include_imports`.
// @comment -- "The operator's own protoc output, and the only descriptor source cxg fully trusts: a service is free to describe itself inaccurately over reflection, so the result records which source produced each decoded field. Optional — without it cxg falls back to empty or raw-byte messages, which still answer an authorization question."
#[arg(
long,
value_name = "FILE",
help_heading = "Probe execution",
display_order = 10,
help = "protoc FileDescriptorSet for typed gRPC messages"
)]
pub grpc_descriptor_set: Option<String>,
/// Do not ask gRPC services to describe themselves over server reflection.
/// Without reflection, typed messages need --grpc-descriptor-set.
// @comment -- "An OFF-switch rather than an on-switch, matching the orchestrator: --allow-grpc is already the deliberate opt-in to gRPC traffic, and reflection is one cached read-only request per service of exactly the kind grpcurl makes by default. This exists for an engagement where every extra request must be accounted for."
#[arg(
long,
help_heading = "Probe execution",
display_order = 11,
help = "Do not use gRPC server reflection to learn message types"
)]
pub no_grpc_reflection: bool,
/// Absolute ceiling on one template's dispatch before it is abandoned and
/// treated as a dead target. Default 900s. This is a BACKSTOP only —
/// `--stall-timeout` is what actually catches a frozen app. 0 disables it,
/// which lets a wedged app hang the scan indefinitely.
// @comment -- "forwards the per-template ceiling to the orchestrator; without this the flag existed in Python only and was unreachable from the cxg binary, so an operator could not raise or disable the backstop at all"
#[arg(
long,
help_heading = "Execution",
display_order = 44,
help = "Per-template dispatch ceiling, seconds (backstop; default 900)"
)]
pub template_timeout: Option<f64>,
/// How long the run may go with NO completed dispatch before the surface is
/// corroborated against the other instances and, if it alone is silent,
/// treated as stalled. This is IDLE time, not template runtime: a probe that
/// keeps getting answers is never killed however long it runs. Default 90s,
/// 0 disables. Applies to `--target-type electron` only.
// @comment -- "forwards the stall threshold to the orchestrator; the measured freeze (a native modal blocking Electron's main process) produces no exception at all, so this is the only bound that ends such a run, and it was unreachable from the binary until now"
#[arg(
long,
help_heading = "Execution",
display_order = 45,
help = "Idle-time stall timeout, seconds (electron only; default 90)"
)]
pub stall_timeout: Option<f64>,
/// Do NOT relaunch a desktop target that dies mid-scan.
///
/// Default is to restart it (max 2 per instance, 3 per run), report the crash
/// as a `denial_of_service` finding, re-probe the suspected IPC channel once
/// and then quarantine it. With this flag a dead target ends the scan with a
/// truncation caveat and exit 3 — the pre-recovery behaviour.
// @comment -- "operator opt-out of crash recovery, because recovery lets cxg's own probes restart the application under test repeatedly and that side effect is an availability decision the operator owns, not cxg"
#[arg(
long,
help_heading = "Execution",
display_order = 46,
help = "Do not relaunch a desktop target that dies mid-scan"
)]
pub no_restart: bool,
/// Non-interactive CI mode: refuse a world-accessible `--auth-dir`.
///
/// When credentials are in use, a world-accessible `--auth-dir` is refused
/// (exit 4) rather than trusted. A dead or expired auth session exits 5 with or
/// without this flag, and `--skip-health-check` does not bypass that: startup
/// API verification still runs and a profile it cannot prove alive still fails
/// the run.
///
/// Also enabled by the environment variable CXG_CI=1, for pipelines that
/// cannot add the flag to the invocation.
// @comment -- "forwards the CI-mode selector as a flag when set; the hard-fail-on-dead-session and world-readable-auth-dir refusal both live in the Python orchestrator (cxg_pentest.py, auth.py), which also honours CXG_CI=1 on its own, so leaving the flag off here still lets the env var reach the orchestrator through the inherited environment"
#[arg(
long,
help_heading = "Authentication",
display_order = 19,
help = "CI mode: refuse a world-accessible --auth-dir. Also CXG_CI=1"
)]
pub ci: bool,
/// JSON report output path. Default: `report.json` under --session-dir.
/// The report contains: target, codebase, auth_profiles, goal, scope_stats,
/// confirmed_findings, ambiguous, mitigation_verifications, dead_profiles,
/// rejected_templates, retried_then_resolved.
#[arg(
long,
short,
help_heading = "Output",
display_order = 51,
help = "JSON report output path (default report.json in session dir)"
)]
pub output: Option<PathBuf>,
}
/// Inputs shared by automatic scan probes and explicit pentest runs.
#[derive(clap::Args, Debug, Clone)]
pub struct ProbeInputs {
/// Guarantee zero model calls. Plain scan already replays selected scanner
/// and JS probe templates without authoring. Explicit pentest runs require
/// --template-dir and disable ranking, generation and mutation.
#[arg(long, help_heading = "Generation")]
pub no_author: bool,
/// Source codebase root. Defaults to the current directory for scan;
/// pentest run requires an explicit value. Reads whitebox/findings.sarif
/// when present and supplies source context to the engine.
#[arg(
long,
default_value = ".",
help_heading = "Target",
display_order = 1,
help = "Source codebase root (contains whitebox/findings.sarif)"
)]
pub codebase: PathBuf,
/// Comma-separated auth profile names previously captured via `cxg pentest auth`.
/// Probes that need multiple identities (IDOR cross-user, session-replay-against-
/// victim) require ≥2 profiles. The lowest-privilege identity is auto-selected as
/// the actor for privesc-class probes.
///
/// Empty means a first-class anonymous (no-login) web/Electron run, not interactive capture.
/// Tauri source maps and in-process proofs need no --auth profile.
#[arg(
long,
default_value = "",
help_heading = "Authentication",
display_order = 11,
help = "Comma-separated captured auth profiles; empty = first-class anonymous (no-login) run on a clean unauthenticated surface with real anonymous probes and auth-only checks reported not-run. Empty does not imply interactive capture; use --interactive-auth"
)]
pub auth: String,
/// Path to scope.yaml. Default: safe permissive defaults (any URL, GET/POST/HEAD/
/// OPTIONS, 30 reqs/endpoint, 1500 reqs total, kill on 8-streak 5xx).
/// Generate one with `cxg pentest scope-init`.
///
/// If this flag is given and the file cannot be read — path does not exist,
/// unreadable, invalid YAML, not a mapping, empty, or PyYAML not installed —
/// the run is REFUSED with exit 4. It does not fall back to the defaults:
/// a bound cxg cannot read is not the same as no bound. Omitting the flag
/// entirely is the supported way to run on the defaults.
///
/// An empty value never reaches that check and is not ignored either:
/// `--scope-file "$SCOPE"` with `SCOPE` unset is rejected by the CLI parser
/// as a usage error (exit 2, `a value is required for '--scope-file
/// <SCOPE_FILE>' but none was supplied`) before the scan starts.
///
/// Refused with exit 4 on `--template-lang py` as well: the legacy Python probe
/// path enforces no scope at all, so a file accepted there would be discarded.
#[arg(
long,
help_heading = "Execution",
display_order = 41,
help = "Path to scope.yaml (URL/method allowlist, budgets)"
)]
pub scope_file: Option<PathBuf>,
/// Operator-owned configuration for IMAP and needs-you questions.
#[arg(long, value_name = "JSON", help_heading = "Probe execution")]
pub auth_inputs: Option<PathBuf>,
/// Read auth profiles from this directory instead of ~/.cert-x-gen/auth.
///
/// A CI pipeline restores a bundle of profiles (imported via
/// `cxg pentest auth import --auth-dir <dir>`) into its own directory and
/// points the run at the same directory here, so pre-flight, the engine, and
/// the health monitor all read the restored bundle rather than the operator's
/// home store.
// @comment -- "forwards the auth-store redirect to the orchestrator, which reassigns auth.AUTH_DIR before any profile is loaded; every profile consumer reaches the store only through auth.load_profile, so this one flag moves all of them. Forwarded only when set, so an unset flag leaves the orchestrator's ~/.cert-x-gen/auth default in force — one default, in one place the two CLIs cannot drift apart on."
#[arg(
long,
help_heading = "Authentication",
display_order = 18,
help = "Read auth profiles from this dir (CI profile bundle)"
)]
pub auth_dir: Option<PathBuf>,
/// Session directory where this scan's artifacts (audit.jsonl, report.json,
/// any captured screenshots) are written.
/// Explicit pentest default: ~/.cert-x-gen/sessions/pentest-<YYYYMMDD-HHMMSS>/
/// Plain scan groups probe inputs and per-target engine sessions under a scan-specific directory.
#[arg(
long,
help_heading = "Output",
display_order = 52,
help = "Session artifacts directory (audit.jsonl, report.json)"
)]
pub session_dir: Option<PathBuf>,
}
/// Non-interactive auth subcommands for CI — mirrors `pentest/auth.py`'s
/// `import`/`verify` subparsers exactly.
// @comment -- "the CI-replay half of the auth surface: a human captures a session once (SSO/MFA and all) and exports its Playwright storage_state; import writes a profile from that state with no browser, and verify gates on whether the saved session is still alive. Both were reachable only via `python3 cxg_pentest.py auth ...` until this surface was wired into clap; the defaults here are copied from auth.py's argparse, which is the specification."
// Like PentestAction, this clap enum is parsed once per process; keep named flags inline.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, Debug, Clone)]
pub enum AuthSubcommand {
/// Import a saved Playwright storage_state as a profile (no browser)
///
/// The CI-replay primitive: a human captures a session once locally (SSO, MFA and
/// all), exports the Playwright storage_state, and every pipeline run injects it
/// here without a display or a human. The written profile is byte-for-byte what an
/// interactive capture produces, so a later `cxg pentest run --auth <profile>`
/// cannot tell an imported profile from a captured one.
///
/// Examples:
/// # From a file on disk
/// cxg pentest auth import --profile pentest --target https://staging.app \
/// --storage-state ./pentest.storage.json
///
/// # From stdin (a CI secret piped straight in, never written to disk in the clear)
/// cat "$SESSION_SECRET" | cxg pentest auth import --profile pentest \
/// --target https://staging.app --storage-state -
///
/// # From the base64 env var, into a restored bundle dir, CI-strict
/// cxg pentest auth import --profile pentest --target https://staging.app \
/// --auth-dir ./ci-auth --ci
Import {
/// Profile name. A subsequent `cxg pentest run --auth <profile>` loads it
/// exactly like a captured one.
#[arg(long)]
profile: String,
/// Target URL this session authenticates against. Recorded in the profile. A run
/// sends this identity's traffic to its own `--scope`/`--target`; the saved
/// origin is used instead only when `--service` is also given.
#[arg(long)]
target: String,
/// Path to a Playwright storage_state JSON, or `-` to read it from stdin (a CI
/// secret pipes straight in, never touching disk in plaintext beyond the profile
/// dir). Omit to materialise it from the base64 env var CXG_AUTH_STATE_<NAME>
/// instead (NAME is the profile name uppercased with non-alphanumerics folded to
/// underscore — e.g. profile `pentest-alice` reads `CXG_AUTH_STATE_PENTEST_ALICE`).
// @g.source (#operator_storage_state) -- "storage_state source (path, '-' for stdin, or env fallback) supplied by the operator; forwarded verbatim to auth.py which resolves and redacts it — cxg never echoes its contents"
#[arg(long, value_name = "PATH|-")]
storage_state: Option<String>,
/// Human-readable label (e.g. 'admin'), shown in scan output.
#[arg(long)]
label: Option<String>,
/// Explicit privilege rank: an integer 0-100 or an alias high/medium/low. Same
/// meaning as on capture.
#[arg(long)]
tier: Option<String>,
/// Semantic role hint passed to the AI as extra context.
#[arg(long)]
persona: Option<String>,
/// Peer-group name for horizontal IDOR / cross-tenant tests.
#[arg(long)]
cohort: Option<String>,
/// Free-form `NAME=VALUE` context attached to the profile. Repeatable.
#[arg(long = "tag", value_name = "NAME=VALUE")]
tags: Vec<String>,
/// Custom HTTP header `NAME:VALUE` sent on every request from this profile
/// (e.g. a WAF-bypass token). Repeatable. Stored as a credential; values are
/// never echoed.
#[arg(long = "header", value_name = "NAME:VALUE")]
headers: Vec<String>,
/// Authenticated API liveness path on this service (default /api/me).
#[arg(long)]
liveness_path: Option<String>,
/// Expected HTTP status, repeatable (default any 2xx; 401/403 always fail).
#[arg(long = "liveness-status")]
liveness_status: Vec<u16>,
/// Service name included in readiness receipts. Opts this profile into
/// multi-service: its saved `--target` origin, not the run's target, receives
/// its traffic and liveness check.
#[arg(long)]
service: Option<String>,
/// Write into this auth directory instead of ~/.cert-x-gen/auth. A pipeline
/// restores a bundle of profiles into one dir and points the run at it with the
/// same flag.
#[arg(long)]
auth_dir: Option<PathBuf>,
/// Non-interactive CI mode: refuse a world-accessible `--auth-dir` rather than
/// write a credential a fellow user could read. Also enabled by CXG_CI=1.
// @comment -- "forwards CI-strictness to auth.py, which refuses a world-readable --auth-dir before persisting a session; the refusal lives in Python (assert_auth_dir_not_world_readable), honoured here and via CXG_CI=1 in the inherited environment"
#[arg(long)]
ci: bool,
},
/// Check a saved web session is still alive (exit 0 alive / non-zero dead)
///
/// An API liveness gate for a saved session, shared with scan-time pre-flight. A pipeline runs this before spending a whole run,
/// and re-captures (or re-imports) when it fails.
///
/// Example:
/// cxg pentest auth verify --profile pentest || echo "session expired, re-import"
Verify {
/// Profile name to verify.
#[arg(long)]
profile: String,
/// Override the profile's saved target (a profile imported with `--service`
/// keeps its own).
#[arg(long)]
target: Option<String>,
/// Authenticated API endpoint (default /api/me); per-profile liveness_check wins.
/// When neither is configured and /api/me is absent, the landing test decides.
#[arg(long, default_value = "/api/me")]
me_path: String,
/// Read the profile from this auth directory instead of ~/.cert-x-gen/auth.
#[arg(long)]
auth_dir: Option<PathBuf>,
},
}
#[derive(Parser, Debug)]
#[command(
about = "Run a security scan against targets using vulnerability detection templates",
long_about = "Execute comprehensive security scans against one or more targets using the multi-language \
template engine. CERT-X-GEN supports scanning single targets, multiple targets, CIDR ranges, \
and domains, or local CLI binaries via cli://<binary>, with advanced filtering and output customization.\n\n\
The scan command orchestrates template execution across targets, manages concurrency, \
filtered by language, severity, tags, and custom criteria to focus on specific \
vulnerability classes or compliance requirements.",
after_help = "Run 'cxg scan --help' for the full flag reference, worked examples, and common scenarios.\n\
Docs: https://docs.bugb.io/cxg/",
after_long_help = "LOCAL CLI TESTING:
Use cli://<binary> with an absolute executable path (cli:///absolute/path/to/my-tool).
Fetch the CLI Security Baseline pack from the detection-template repository:
https://github.com/Bugb-Technologies/cert-x-gen-templates/tree/main/templates/cli-baseline
With the default repository configuration:
cxg template update
cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation
This repository's templates/ contains skeletons, not the detection pack.
A skipped check provides no refutation; no findings alone does not establish safety.
Optional probe inputs (the selected template must consume this contract):
cxg scan --scope cli:///absolute/path/to/my-tool --templates /path/to/probe.sh --arg --format --arg json --stdin-file ./case.bin --input ./corpus --target-env ASAN_OPTIONS=abort_on_error=1 --require-instrumentation
cxg passes argv, stdin file, seed corpus and target environment to templates; it does
not automatically adapt every template to the target's syntax or mutate the corpus.
Templates declare @oracles and report confirmed/refuted/skipped/errored/timed-out.
A nonzero exit alone does not prove an unhandled exception.
--require-instrumentation checks binary markers and oracle requirements; unsupported
executions skip (no-instrumentation-detected, oracle-unavailable(...), target-not-found).
Build-independent oracles (exit, signal, timeout, exception, property) can run with none.
Interpreted scripts detect none; target-kind declarations apply even without preflight.
Scanning does not build the target: see cxg build --help for instrumented build options,
then use --instrumented-manifest <PATH> for provenance of the binary it names.
Tauri IPC testing uses cxg pentest run --target-type tauri --codebase <repo>.
DETAILED USAGE GUIDE:
TARGET SPECIFICATION:
Define scope once and let the engine figure out the rest.
--scope <SCOPE>
Smart selector that accepts:
• Single host or URL (example.com, https://api.example.com:8443)
• Comma-separated lists (example.com,test.com,192.168.1.1)
• Files via @targets.txt or file://path/to/targets.txt (one entry per line, # for comments)
• CIDR ranges (192.168.1.0/24, 10.0.0.0/8)
• Domains and subdomains (example.com, api.example.com)
• Mixed entries in a single invocation
Legacy flags (--target, --targets, --target-file, --domain, --domains, --domain-file, --cidr) remain as aliases.
The scanner automatically deduplicates and expands entries from files.
PORT SELECTION:
Customize which ports to scan.
--ports <PORT>
Smart selector that adds ports to template defaults. Supports:
• Single ports (8080)
• Ranges (8000-8100)
• Comma lists (80,443,8443)
• Files via @ports.txt or file://ports.txt (one per line, # for comments)
• Mixed entries in a single invocation
Adds to template default ports; combine with --override-ports to replace defaults entirely.
Example:
cxg scan --scope example.com --ports 80,443,8000-8010,@extra-ports.txt
--top-ports <N>
Add the top N most common ports (based on curated frequency data).
Example:
cxg scan --scope example.com --top-ports 100
--override-ports <PORTS>
Replace template default ports entirely with your custom list (same formats as --ports).
Example:
cxg scan --scope example.com --override-ports 80,443
TEMPLATE FILTERING:
Control which vulnerability templates are executed. Filter by ID, language, severity, or tags.
--templates <TEMPLATE>
Smart selector that understands template IDs, filenames, or file paths. Supports:
• Direct template IDs (redis-unauthenticated)
• File names or paths (templates/network/redis.yaml)
• Files containing template lists via @templates.txt or file://templates.txt (one per line, # for comments)
• Mixed entries in a single invocation
Legacy flags (--template, --template-file) remain as aliases.
Examples:
cxg scan --scope example.com --templates redis-unauthenticated
cxg scan --scope example.com --templates redis-unauthenticated,templates/network/redis.yaml
cxg scan --scope example.com --templates @compliance-templates.txt
--template-dir <DIR>
Use templates from a custom directory instead of the default location.
Example:
cxg scan --scope example.com --template-dir ./custom-templates
--template-language <LANGUAGES>
Filter templates by programming language. Useful for testing specific engine types.
Available: yaml, python, rust, shell, javascript, c, cpp, java, go, ruby, perl, php
Example:
cxg scan --scope example.com --template-language python --template-language rust
--severity <SEVERITIES>
Filter by severity level. Run only critical/high severity checks for quick assessments.
Available: critical, high, medium, low, info
Example:
cxg scan --scope example.com --severity critical,high
--tags <TAGS>
Filter templates by tags (comma-separated). Tags categorize vulnerabilities.
Common tags: database, injection, xss, authentication, authorization, rce, lfi, ssrf
Example:
cxg scan --scope example.com --tags database,unauthenticated
--exclude-templates <PATTERN>
Exclude templates matching a pattern. Supports wildcards.
Example:
cxg scan --scope example.com --exclude-templates test-*,experimental-*
OUTPUT AND REPORTING:
Customize how scan results are saved and displayed.
--output <BASENAME>
Set the output file basename. Any trailing extension is REPLACED by the chosen
format's extension — e.g. `--output report.txt --output-format json` writes report.json.
Default: scan-results
Example:
cxg scan --scope example.com --output my-scan --output-format json
# Writes: my-scan.json
--output-format <FORMATS>
Specify output formats (comma-separated). Multiple formats can be generated simultaneously.
Available: json, csv, sarif, html, markdown
- json: Machine-readable, ideal for automation and APIs
- csv: Spreadsheet-friendly, good for reporting and analysis
- sarif: Static Analysis Results Interchange Format (for CI/CD integration)
- html: Human-readable report with visualizations
- markdown: Human-readable Markdown report
Example:
cxg scan --scope example.com --output-format json,html,sarif
--quiet
Suppress the ASCII startup banner. Scan output itself is unchanged.
Example:
cxg scan --scope example.com --quiet
PERFORMANCE AND CONCURRENCY:
Tune scan performance based on your resources and target infrastructure.
--parallel-targets <N>
How many targets to scan simultaneously. Higher = faster but may trigger rate limits.
Default: 50
Recommendation: Lower for production systems (10-25), higher for internal scans (50-100)
Example:
cxg scan --scope example.com,test.com --parallel-targets 10
--parallel-templates <N>
How many templates to run concurrently per target. Balances speed vs. target load.
Default: 10
Recommendation: Lower for fragile targets (5), higher for robust systems (20)
Example:
cxg scan --scope example.com --parallel-templates 5
TIMEOUTS AND RETRIES:
Configure how the scanner handles slow responses and failures.
--timeout <DURATION>
Maximum time to wait for a response. Supports: s (seconds), m (minutes), h (hours)
Default: 30s
Recommendation: Increase for slow networks or complex checks
Example:
cxg scan --scope example.com --timeout 60s
cxg scan --scope example.com --timeout 2m
--retry <N>
Number of retry attempts for failed requests. Helps with transient network issues.
Default: 1
Recommendation: Increase for unreliable networks, decrease for fast scans
Example:
cxg scan --scope example.com --retry 5
--rate-limit <N>
Maximum requests per second. Prevents overwhelming targets and triggering WAF/IPS.
Default: None (unlimited)
Recommendation: Use 10-50 for production, 100+ for internal testing
Example:
cxg scan --scope example.com --rate-limit 10
SCANNING MODES:
Different modes for various scanning scenarios and requirements.
--aggressive
Enable aggressive scanning mode. Uses more intrusive checks and higher concurrency.
WARNING: May trigger security alerts or cause service disruption.
Use only with explicit permission on systems you control.
Example:
cxg scan --scope test-env.internal --aggressive
--stealth
Enable stealth mode. Reduces scan footprint, randomizes timing, and mimics normal traffic.
Slower but less likely to trigger detection systems (IDS/IPS/WAF).
Automatically reduces concurrency and adds random delays.
Example:
cxg scan --scope example.com --stealth
--safe
Safe mode - excludes potentially harmful checks (DoS, resource exhaustion, etc.).
Recommended for production systems where availability is critical.
Example:
cxg scan --scope production.example.com --safe
--passive
Passive mode - no active probing. Only analyzes responses from normal requests.
Safest option but limited detection capabilities. Good for initial reconnaissance.
Example:
cxg scan --scope example.com --passive
NETWORK CONFIGURATION:
Configure network-level settings for scanning through proxies, with custom headers, etc.
--proxy <URL>
Route all traffic through a proxy. Supports HTTP, HTTPS, and SOCKS5 proxies.
Useful for scanning from different geographic locations or through corporate proxies.
Examples:
cxg scan --scope example.com --proxy http://proxy.corp.com:8080
cxg scan --scope example.com --proxy socks5://127.0.0.1:1080
--user-agent <STRING>
Custom User-Agent header. Useful for mimicking specific browsers or tools.
Default: cert-x-gen/<version>
Example:
cxg scan --scope example.com --user-agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
--header <KEY:VALUE>
Add custom HTTP headers. Can be specified multiple times for multiple headers.
Useful for authentication, API keys, or custom application headers.
Examples:
cxg scan --scope api.example.com --header 'Authorization: Bearer token123'
cxg scan --scope example.com --header 'X-API-Key: abc' --header 'X-Custom: value'
--cookie <KEY=VALUE>
Add cookies to requests. Can be specified multiple times. Useful for authenticated scans.
Example:
cxg scan --scope example.com --cookie 'session=abc123' --cookie 'user=admin'
--follow-redirects
Follow HTTP redirects automatically. Useful for discovering redirect chains.
Default: Disabled (redirects are not followed unless this flag is passed)
Example:
cxg scan --scope example.com --follow-redirects --max-redirects 10
--max-redirects <N>
Maximum number of redirects to follow. Prevents infinite redirect loops.
Default: 5
Example:
cxg scan --scope example.com --max-redirects 3
CONFIGURATION FILES:
Use configuration files for complex setups.
--config <FILE>
Load settings from a configuration file (YAML, TOML, or JSON).
CLI arguments override config file settings.
Example:
cxg scan --config production-scan.yaml --scope example.com
COMMON SCANNING SCENARIOS:
1. Quick Vulnerability Assessment (Fast, High-Severity Only):
cxg scan --scope example.com --severity critical,high
2. Comprehensive Security Audit (All Templates, All Severities):
cxg scan --scope example.com --output-format json,html,sarif
3. Stealth Penetration Test (Low Detection Risk):
cxg scan --scope example.com --stealth --rate-limit 5 --timeout 60s
4. Production System Scan (Safe, Non-Disruptive):
cxg scan --scope production.example.com --safe --parallel-templates 3 --rate-limit 10
5. Database Security Scan (Specific Vulnerability Class):
cxg scan --scope db.example.com --tags database,injection --severity high,critical
6. Authenticated Web Application Scan:
cxg scan --scope app.example.com --cookie 'session=xyz' --header 'Authorization: Bearer token'
7. Large-Scale Network Scan (Multiple Targets):
cxg scan --scope @targets.txt --parallel-targets 100 --output-format csv,json
8. API Security Testing:
cxg scan --scope api.example.com --template-language python --tags api,authentication
9. Compliance Scan (OWASP Top 10):
cxg scan --scope example.com --templates @owasp-top10.txt --output-format sarif
10. Internal Network Reconnaissance:
cxg scan --scope 10.0.0.0/24 --passive --top-ports 100 --quiet
Supplied JS probe contracts run automatically through the pentest engine with zero model calls.
Scanner templates keep their language runners; mixed packs produce one JSON report with
template-reported and engine-adjudicated verdict sources. Missing probe inputs are refused.
--scope supplies the target; --codebase defaults to the current directory. Use --auth,
--auth-dir, --auth-inputs, --scope-file and --session-dir for probe execution inputs.
All non-authoring pentest inputs are accepted for the probe engine, including CI,
containment, protocol, chaining, capture and timeout controls. They do not change
scanner contracts; scanner-only runs do not use these probe-engine controls.
Profile/scope inputs require a selected probe. Plain scan always disables authoring.
JS probes only; any-language probes are not yet supported. --pentest exposes authoring too.
For more information, visit: https://cert-x-gen.io/docs"
)]
pub struct ScanArgs {
/// Parsed from the same engine definitions; no parallel list of option types/defaults.
#[arg(skip)]
pub probe_run: Option<Box<PentestRunArgs>>,
#[command(flatten)]
pub probe_inputs: ProbeInputs,
/// Enable all `pentest run` options, including authoring and desktop targets.
/// Plain scan already runs supplied JS probe contracts with zero model calls. JS probes only;
/// any-language probes are not supported. Use --no-author --template-dir DIR
/// for zero model calls. Engine-confirmed verdicts remain pentest verdicts;
/// ordinary scan findings remain template-reported.
#[arg(long, help_heading = "Engine")]
pub pentest: bool,
// ===== Target Selection =====
#[arg(
long = "scope",
short = 's',
short_alias = 't',
aliases = SCAN_SCOPE_ALIASES,
value_name = "SCOPE",
// No `value_delimiter` here on purpose. Comma splitting for scope
// values is done by `expand_scope_entry`, which exempts `cli:` paths
// (a binary path may legitimately contain a comma). Letting clap split
// first would cut such a path in half before the exemption is reached.
help_heading = "Target Selection",
display_order = 1,
help = "Targets: hosts, CIDRs, URLs, @files, or local binaries cli://<binary>",
long_help = "Smart target selector. Accepts single host, comma lists, files (@file.txt), \
CIDR blocks (192.168.1.0/24), domains, URLs, or local CLI binaries \
(cli:///absolute/path/to/my-tool). CLI scopes select a local process, not a network host; \
ports have no meaning for CLI targets. Binary paths preserve commas. Legacy flags \
(--target, --targets, --target-file, --domain, --domains, --domain-file, \
--cidr) remain as aliases."
)]
pub scope: Vec<String>,
#[arg(
long = "ports",
short = 'p',
aliases = ["port", "port-file", "add-ports"],
value_name = "PORT",
value_delimiter = ',',
help_heading = "Target Selection",
display_order = 2,
help = "Extra ports to add: single, ranges, comma lists, @files",
long_help = "Smart port selector. Accepts single ports, ranges (80-90), comma lists, \
files (@ports.txt), or mixed entries. These are ADDED to each template's \
default ports; use --override-ports to replace them instead."
)]
pub ports: Vec<String>,
#[arg(
long,
help_heading = "Target Selection",
display_order = 3,
help = "Scan the top N most common ports",
long_help = "Add the top N most common ports (based on curated frequency data). \
Example: --top-ports 1000"
)]
pub top_ports: Option<u16>,
#[arg(
long,
help_heading = "Target Selection",
display_order = 4,
help = "Replace template default ports entirely",
long_help = "Replace template default ports entirely with your own list (same formats \
as --ports). Use for complete control over port selection."
)]
pub override_ports: Option<String>,
// ===== Template Selection =====
#[arg(
long = "templates",
value_name = "TEMPLATE",
value_delimiter = ',',
aliases = ["template", "template-file"],
help_heading = "Template Selection",
display_order = 11,
help = "Templates: IDs, file names/paths, or @files",
long_help = "Smart template selector. Accepts template IDs, file names/paths, or @file \
references (one per line). Supports mixed entries. Legacy flags (--template, \
--template-file) remain as aliases."
)]
pub templates: Vec<String>,
#[arg(
long,
value_enum,
value_name = "LANG",
help_heading = "Template Selection",
display_order = 12,
help = "Filter templates by language (e.g. python,rust,c)",
long_help = "Filter templates by programming language. Available: yaml, python, rust, \
shell, javascript, c, cpp, java, go, ruby, perl, php."
)]
pub template_language: Option<Vec<LanguageArg>>,
#[arg(
long,
value_enum,
help_heading = "Template Selection",
display_order = 13,
help = "Filter by severity (critical,high,medium,low,info)",
long_help = "Filter templates by severity level. Example: --severity critical,high for \
a quick, high-signal assessment."
)]
pub severity: Option<Vec<SeverityArg>>,
#[arg(
long,
help_heading = "Template Selection",
display_order = 14,
help = "Filter by tags (database,injection,xss,rce,…)",
long_help = "Filter templates by tags (comma-separated). Common tags: database, \
injection, xss, rce, lfi, ssrf, auth."
)]
pub tags: Option<String>,
#[arg(
long,
help_heading = "Template Selection",
display_order = 15,
help = "Exclude templates matching a pattern (wildcards)",
long_help = "Exclude templates matching a pattern. Supports wildcards. \
Example: --exclude-templates test-*,experimental-*"
)]
pub exclude_templates: Option<String>,
#[arg(
long,
help_heading = "Template Selection",
display_order = 16,
help = "Use templates from a custom directory",
long_help = "Use templates from a custom directory instead of the default discovery \
locations."
)]
pub template_dir: Option<PathBuf>,
#[arg(
long,
value_name = "JSON",
help_heading = "Template Selection",
display_order = 17,
help = "JSON context passed to templates (CERT_X_GEN_CONTEXT)",
long_help = "JSON context passed to templates via the CERT_X_GEN_CONTEXT environment \
variable. Templates read this to receive parameterized input (target URLs, \
parameter names, HTTP methods, baselines, etc.) without hardcoding values. \
Example: '{\"param_name\":\"username\",\"method\":\"POST\"}'"
)]
pub context: Option<String>,
// ===== Probe Input =====
#[arg(
long = "arg",
value_name = "ARG",
allow_hyphen_values = true,
help_heading = "Probe Input",
display_order = 51,
help = "Argument to feed the target under test (repeatable)",
long_help = "Argument passed through to the target the template drives, not to the \
template itself. Repeat for an argument vector; hyphen-leading values are \
accepted, so the target's own flags can be passed. Delivered to the \
template as CERT_X_GEN_ARGV (a JSON array). Example: \
--arg --label --arg AAAAAAAAAAAAAAAAAAAA"
)]
pub arg: Vec<String>,
#[arg(
long,
value_name = "PATH",
help_heading = "Probe Input",
display_order = 52,
help = "File whose bytes are fed to the target's stdin",
long_help = "Path to a file whose bytes the template should feed to the target's stdin. \
Delivered as CERT_X_GEN_STDIN_FILE, canonicalised, so the template does not \
depend on its working directory."
)]
pub stdin_file: Option<PathBuf>,
#[arg(
long = "input",
value_name = "DIR",
help_heading = "Probe Input",
display_order = 53,
help = "Directory of seed inputs (corpus) for the probe",
long_help = "Directory of seed inputs the template may iterate over. Delivered as \
CERT_X_GEN_INPUT_DIR. cxg does not mutate or minimise the corpus -- corpus \
search is discovery, and cxg verifies -- it only hands over the directory."
)]
pub input: Option<PathBuf>,
#[arg(
long,
value_name = "K=V",
help_heading = "Probe Input",
display_order = 54,
help = "Environment variable to set on the target (repeatable)",
long_help = "Environment variable the template should set on the target process, not on \
itself. Delivered as CERT_X_GEN_TARGET_ENV (a JSON object). Repeatable; a \
repeated key takes its last value. Typical use is sanitizer runtime \
control, e.g. --target-env ASAN_OPTIONS=abort_on_error=1"
)]
pub target_env: Vec<String>,
#[arg(
long,
help_heading = "Probe Input",
display_order = 55,
help = "Skip the templates an uninstrumented cli:// build could not have shown",
long_help = "Instrumentation preflight. For each cli:// target, inspect the binary for \
sanitizer, coverage and debug-info markers before running anything against \
it. If none are present, record as SKIPPED with the reason \
no-instrumentation-detected every (template, target) execution whose \
oracles needed that instrumentation, instead of running the probe and \
reporting a 'no findings' result that looks like a refutation but is not \
evidence. A template declaring only oracles that work on any build (exit, \
signal, timeout, exception, property) still runs and reaches a real verdict. The \
build cxg wants is the language's instrumented one, e.g. \
clang -fsanitize=address -g; cxg inspects and refuses, it does not build \
the target -- see `cxg build --instrument` for the verb that does."
)]
pub require_instrumentation: bool,
#[arg(
long,
value_name = "PATH",
help_heading = "Probe Input",
display_order = 56,
help = "Trust this cxg build --instrument manifest over re-inspecting the binary",
long_help = "Manifest written by `cxg build --instrument`, naming a binary and the \
instrumentation cxg verified in it at build time. Provenance beats \
inspection: cxg passed the flags and read the produced artefact back before \
it was willing to call the build instrumented, and that record survives \
stripping and a copy away from the build tree. The record applies only to \
the binary the manifest names; every other target is inspected exactly as \
before. Repeatable. Omit it and the scan behaves identically to one run \
before this flag existed."
)]
pub instrumented_manifest: Vec<PathBuf>,
#[arg(
long,
value_name = "GROUP",
help_heading = "Template Selection",
display_order = 18,
help = "Run only templates in this batch group",
long_help = "Run only templates belonging to this batch group. Batch groups let you \
execute a cohort of templates that share the same context shape in a single \
invocation. Common groups: auth-context, endpoint-params, service-ports, \
full-surface."
)]
pub batch_group: Option<String>,
// ===== Execution =====
#[arg(
long,
default_value_t = 50,
help_heading = "Execution",
display_order = 21,
help = "Concurrent targets scanned at once",
long_help = "How many targets to scan simultaneously. Lower for production systems \
(10-25), higher for internal scans (50-100)."
)]
pub parallel_targets: usize,
#[arg(
long,
default_value_t = 10,
help_heading = "Execution",
display_order = 22,
help = "Concurrent templates per target",
long_help = "How many templates to run concurrently per target. Balances speed against \
load on the target. Lower for fragile targets, higher for robust ones."
)]
pub parallel_templates: usize,
#[arg(
long,
default_value = "30s",
help_heading = "Execution",
display_order = 23,
help = "Response timeout (e.g. 30s, 2m, 1h)",
long_help = "Maximum time to wait for a response. Supports s (seconds), m (minutes), \
h (hours). Increase for slow networks or complex checks."
)]
pub timeout: String,
#[arg(
long,
default_value_t = 1,
help_heading = "Execution",
display_order = 24,
help = "Retry attempts for transient failures",
long_help = "Number of retry attempts for failed requests. Higher for unreliable \
networks, lower for fast scans."
)]
pub retry: u32,
#[arg(
long,
help_heading = "Execution",
display_order = 25,
help = "Max requests per second (prevents WAF/IPS triggers)",
long_help = "Maximum requests per second. Use 10-50 for production, 100+ for internal \
testing. Prevents overwhelming targets and triggering WAF/IPS."
)]
pub rate_limit: Option<u32>,
#[arg(
long,
help_heading = "Execution",
display_order = 26,
help = "Aggressive mode: intrusive checks, higher concurrency",
long_help = "Aggressive scanning with intrusive checks and higher concurrency. \
WARNING: may trigger security alerts or cause disruption. Use only with \
explicit permission on systems you control."
)]
pub aggressive: bool,
#[arg(
long,
help_heading = "Execution",
display_order = 27,
help = "Stealth mode: randomized timing, reduced footprint",
long_help = "Stealth mode: randomized timing and reduced footprint to evade IDS/IPS/WAF \
detection. Slower, but less likely to be flagged."
)]
pub stealth: bool,
#[arg(
long,
help_heading = "Execution",
display_order = 28,
help = "Passive mode: analyze responses only, no active probes",
long_help = "Passive scanning: analyze responses from normal requests only, with no \
active probing. Safest option, but limited detection capability."
)]
pub passive: bool,
#[arg(
long,
help_heading = "Execution",
display_order = 29,
help = "Safe mode: skip DoS / resource-exhaustion checks",
long_help = "Safe mode: excludes potentially harmful checks (DoS, resource exhaustion). \
Recommended for production systems where availability is critical."
)]
pub safe: bool,
// ===== Network =====
#[arg(
long,
help_heading = "Network",
display_order = 31,
help = "Route traffic through a proxy (http/https/socks5)",
long_help = "Route all traffic through a proxy. Supports HTTP, HTTPS, and SOCKS5. \
Examples: http://proxy:8080, socks5://127.0.0.1:1080"
)]
pub proxy: Option<String>,
#[arg(
long,
help_heading = "Network",
display_order = 32,
help = "Custom User-Agent header",
long_help = "Custom User-Agent header, for mimicking specific browsers or tools. \
Default: cert-x-gen/<version>. Example: \"Mozilla/5.0 ...\""
)]
pub user_agent: Option<String>,
#[arg(
long,
help_heading = "Network",
display_order = 33,
help = "Add a custom header (repeatable)",
long_help = "Add a custom HTTP header. Repeatable for multiple headers. Useful for \
authentication, API keys, or custom application headers. \
Example: --header \"Authorization: Bearer token\""
)]
pub header: Option<Vec<String>>,
#[arg(
long,
help_heading = "Network",
display_order = 34,
help = "Add a cookie (repeatable)",
long_help = "Add a cookie to requests. Repeatable. Useful for authenticated scans. \
Example: --cookie \"session=abc123\""
)]
pub cookie: Option<Vec<String>>,
#[arg(
long,
help_heading = "Network",
display_order = 35,
help = "Follow HTTP redirects (Default: Disabled)",
long_help = "Follow HTTP redirects automatically, for discovering redirect chains and \
final destinations. Default: Disabled — redirects are not followed unless \
this flag is passed."
)]
pub follow_redirects: bool,
#[arg(
long,
default_value_t = 5,
help_heading = "Network",
display_order = 36,
help = "Max redirect hops to follow",
long_help = "Maximum number of redirects to follow (when --follow-redirects is set). \
Prevents infinite redirect loops."
)]
pub max_redirects: usize,
// ===== Output =====
#[arg(
short,
long,
default_value = "scan-results",
help_heading = "Output",
display_order = 41,
help = "Output basename (extension set by --output-format)",
long_help = "Output file basename. The trailing extension (if any) is REPLACED by the \
chosen format's extension — e.g. `--output report.txt --output-format json` \
writes report.json."
)]
pub output: String,
#[arg(
long,
default_value = "json",
help_heading = "Output",
display_order = 42,
help = "Output formats: json,csv,sarif,html,markdown",
long_help = "Output formats (comma-separated); several can be generated at once. \
Available: json (automation), csv (spreadsheet), sarif (CI/CD), \
html (visual report), markdown (docs)."
)]
pub output_format: String,
#[arg(
long,
value_enum,
value_delimiter = ',',
help_heading = "Output",
help = "Exit 2 after writing reports if any execution has a matching status",
long_help = "Fail CI on matching execution statuses (comma-separated or repeated). \
Example: --fail-on confirmed,errored,timed-out. Reports are written before \
exit 2. Without this flag, findings do not change the exit code."
)]
pub fail_on: Vec<FailOnArg>,
#[arg(
short,
long,
help_heading = "Output",
display_order = 43,
help = "Suppress the ASCII startup banner",
long_help = "Suppress the ASCII startup banner. Scan output itself is unchanged."
)]
pub quiet: bool,
// ===== Not Implemented (accepted and ignored) =====
#[arg(
long,
help_heading = "Not Implemented",
display_order = 91,
help = "Protocol to use [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Specify protocol: http, https, tcp, udp, etc. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub protocol: Option<String>,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 92,
help = "Multiple protocols [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Test multiple protocols (comma-separated). Example: http,https \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub protocols: Option<String>,
#[arg(
long,
default_value_t = num_cpus::get(),
help_heading = "Not Implemented",
display_order = 93,
help = "Worker threads [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Worker threads for parallel execution. Concurrency is actually controlled \
by --parallel-targets and --parallel-templates. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub threads: usize,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 94,
help = "Stream results in real-time [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Stream results in real-time as they are found. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub stream: bool,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 95,
help = "Resume an interrupted scan [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Resume a scan from where it stopped. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub resume: Option<String>,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 96,
help = "Distributed mode [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Distributed mode: coordinate with other scanners for massive scans. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub distributed: bool,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 97,
help = "Coordinator URL [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Coordinator URL for distributed mode. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub coordinator: Option<String>,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 98,
help = "Worker identifier [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Worker identifier in distributed mode. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub worker_id: Option<String>,
#[arg(
long,
help_heading = "Not Implemented",
display_order = 99,
help = "Named config profile [NOT IMPLEMENTED — accepted and ignored]",
long_help = "Use a named profile from the config file. \
[NOT IMPLEMENTED — accepted and ignored]"
)]
pub profile: Option<String>,
}
#[derive(Parser, Debug)]
#[command(
about = "Manage security scanning templates",
long_about = "List, validate, update, create, and manage security scanning templates. \
Templates define vulnerability detection logic in 12 supported languages.",
after_help = "TEMPLATE LANGUAGES:
Interpreted: Python, JavaScript, Ruby, Perl, PHP, Shell
Compiled: Rust, C, C++, Java, Go
Declarative: YAML
EXAMPLES:
# CLI Security Baseline from the detection-template repository (not skeletons)
cxg template update
cxg template list --tags cli
cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation
# List all templates
cxg template list
# Filter templates
cxg template list --language python
cxg template list --language c --severity critical
cxg template list --tags database,unauthenticated
# Search templates
cxg template search redis
cxg template search \"sql injection\" --language python
cxg template search unauthenticated --detailed
# Get template information
cxg template info redis-unauthenticated
cxg template info sql-injection-detection
# Show template directories
cxg template pwd
# View skeleton template for a language
cxg template skeleton python
cxg template skeleton c
# Add a local template to cxg
cxg template add ./my-redis-check.py
cxg template add ./custom-check.c custom/network
# Validate templates
cxg template validate ~/.cert-x-gen/templates/
cxg template validate ./my-templates/ --recursive
cxg template validate ./redis-check.c
# Update templates from repository
cxg template update
cxg template update --force
# Create new template from skeleton
cxg template create --id my-check --language python --name \"My Check\"
cxg template create --id redis-test --language c --output ./my-templates/
# Test a template
cxg template test --template ./my-template.c --target 192.168.1.100
cxg template test --template redis-unauthenticated --target localhost --debug"
)]
pub struct TemplateCommand {
#[command(subcommand)]
pub action: TemplateAction,
}
#[derive(Subcommand, Debug)]
pub enum TemplateAction {
/// List available templates
///
/// CLI Security Baseline: run `cxg template update`, then `cxg template list --tags cli`.
/// The pack comes from cert-x-gen-templates/templates/cli-baseline, not this
/// repository's skeletons. Inspect a result with `cxg template info <template-id>`.
List {
/// Filter by programming language
#[arg(long, value_enum, value_name = "LANG")]
language: Option<LanguageArg>,
/// Filter by severity level
#[arg(long, value_enum, value_name = "LEVEL")]
severity: Option<SeverityArg>,
/// Filter by tags (comma-separated); use cli for local CLI templates
#[arg(long, value_name = "TAG,TAG,...")]
tags: Option<String>,
/// Filter by batch group (e.g. auth-context, endpoint-params)
#[arg(long, value_name = "GROUP")]
batch_group: Option<String>,
},
/// Validate template files
Validate {
/// Template file or directory to validate
path: PathBuf,
/// Recursively validate all templates in subdirectories
#[arg(short, long)]
recursive: bool,
/// Output validation results as JSON
#[arg(long)]
json: bool,
},
/// Update templates from remote repository
///
/// The default repository is https://github.com/Bugb-Technologies/cert-x-gen-templates.
/// It supplies the CLI Security Baseline under templates/cli-baseline, installed at
/// ~/.cert-x-gen/templates/official/templates/cli-baseline with default configuration.
/// Example: cxg template update
Update {
/// Force update (overwrite local changes)
#[arg(short, long)]
force: bool,
},
/// Show detailed information about a template
Info {
/// Template ID to show information for
template_id: String,
},
/// Create a new template from skeleton/scaffold
Create {
/// Unique template ID
#[arg(long, value_name = "ID")]
id: String,
/// Programming language for the template
#[arg(long, value_enum, value_name = "LANG")]
language: LanguageArg,
/// Human-readable template name
#[arg(long, value_name = "NAME")]
name: String,
/// Output directory for the new template
#[arg(short, long, default_value = ".", value_name = "DIR")]
output: PathBuf,
},
/// Test a template against a target
Test {
/// Path to template file or template ID
template: PathBuf,
/// Target to test against
#[arg(long, value_name = "HOST")]
target: String,
/// Enable debug output
#[arg(long)]
debug: bool,
},
/// Search templates (shortcut for `cxg search`)
///
/// Discover CLI Security Baseline templates after `cxg template update`:
/// cxg template search baseline --tags cli
Search {
/// Search query
query: String,
/// Filter by programming language
#[arg(long, value_enum, value_name = "LANG")]
language: Option<LanguageArg>,
/// Filter by severity level
#[arg(long, value_enum, value_name = "LEVEL")]
severity: Option<SeverityArg>,
/// Filter by tags (comma-separated); use cli for local CLI templates
#[arg(long, value_name = "TAG,TAG,...")]
tags: Option<String>,
/// Search in template content/code
#[arg(long)]
content: bool,
/// Show detailed results
#[arg(long)]
detailed: bool,
/// Maximum number of results
#[arg(long, default_value_t = 50, value_name = "N")]
limit: usize,
},
/// Show the template directories used by cxg
Pwd,
/// Display the skeleton/scaffold template for a language.
///
/// This is a starting scaffold, not a ready-to-run template. The emitted YAML skeleton
/// in particular does not pass the engine loader as-is and must be edited before use.
Skeleton {
/// Programming language for the skeleton
#[arg(value_enum, value_name = "LANG")]
language: LanguageArg,
},
/// Add a local template file into the cxg template directory
Add {
/// Path to the template file to add
#[arg(value_name = "FILE")]
file: PathBuf,
/// Destination subdirectory within the user template folder (e.g. "custom/redis")
#[arg(value_name = "DEST")]
dest: Option<String>,
},
}
#[derive(Parser, Debug)]
#[command(
about = "Search and discover security scanning templates",
long_about = "Search through available templates using text queries, filters, and advanced options. \
Supports full-text search, regex patterns, content search, and multiple output formats.",
after_help = "SEARCH CAPABILITIES:
• Full-text search in names, descriptions, and tags
• Regex pattern matching
• Content search (searches inside template code)
• Multiple filters (language, severity, tags, author, CWE)
• Multiple output formats (table, json, yaml, csv, list, detailed)
• Sorting and pagination
EXAMPLES:
# Discover installed CLI Security Baseline templates
cxg template update
cxg search --tags cli
# Basic text search
cxg search --query \"redis\"
cxg search --query \"sql injection\"
cxg search --query \"unauthenticated access\"
# Language-specific search
cxg search --language python
cxg search --language c --query \"buffer overflow\"
cxg search --language rust --severity critical
# Severity filtering
cxg search --severity critical
cxg search --severity high --language python
cxg search --severity critical,high
# Tag-based search
cxg search --tags database
cxg search --tags \"database,unauthenticated\"
cxg search --tags injection --language c
# Author and CWE filtering
cxg search --author \"CERT-X-GEN\"
cxg search --cwe \"CWE-89\"
cxg search --cwe \"CWE-306\" --severity critical
# Advanced search with regex
cxg search --query \"redis|mysql|postgres\" --regex
cxg search --query \"SQL.*injection\" --regex --case-sensitive
# Content search (slower but comprehensive)
cxg search --query \"curl\" --content
cxg search --query \"SELECT.*FROM\" --content --regex
# Output formats
cxg search --query \"redis\" --format table # Default
cxg search --query \"redis\" --format json
cxg search --query \"redis\" --format csv
cxg search --query \"redis\" --format yaml
cxg search --query \"redis\" --format detailed
# Sorting and limiting
cxg search --query \"injection\" --sort name
cxg search --query \"injection\" --sort severity --reverse
cxg search --query \"injection\" --limit 10
# Get only template IDs (useful for piping to scan)
cxg search --query \"redis\" --ids-only
TEMPLATES=$(cxg search --query \"redis\" --ids-only | tr '\\n' ',')
cxg scan --target example.com --templates \"$TEMPLATES\"
# Show statistics
cxg search --query \"redis\" --stats
cxg search --language python --stats
# Save results to file
cxg search --query \"redis\" --output results.json --format json
cxg search --language c --output c-templates.csv --format csv
# Complex queries
cxg search --language python --severity high --tags database --format json
cxg search --query \"authentication\" --content --case-sensitive --regex
cxg search --author \"CERT-X-GEN\" --severity critical --sort date --reverse"
)]
pub struct SearchArgs {
/// Search query (searches in name, description, tags, and optionally content)
#[arg(short, long, value_name = "TEXT")]
pub query: Option<String>,
/// Filter by programming language
#[arg(long, value_enum, value_name = "LANG")]
pub language: Option<LanguageArg>,
/// Filter by severity level
#[arg(long, value_enum, value_name = "LEVEL")]
pub severity: Option<SeverityArg>,
/// Filter by tags (comma-separated); use cli for local CLI templates
#[arg(long, value_name = "TAG,TAG,...")]
pub tags: Option<String>,
/// Filter by template author
#[arg(long, value_name = "NAME")]
pub author: Option<String>,
/// Filter by CWE ID (e.g., CWE-89)
#[arg(long, value_name = "CWE-ID")]
pub cwe: Option<String>,
/// Search in template content/code (slower but more comprehensive)
#[arg(long)]
pub content: bool,
/// Use case-sensitive search
#[arg(long)]
pub case_sensitive: bool,
/// Treat query as regex pattern
#[arg(long)]
pub regex: bool,
/// Maximum number of results to return
#[arg(long, default_value_t = 50, value_name = "N")]
pub limit: usize,
/// Output format for search results
#[arg(long, default_value = "table", value_enum, value_name = "FORMAT")]
pub format: SearchFormat,
/// Output file for results (default: print to stdout)
#[arg(short, long, value_name = "FILE")]
pub output: Option<PathBuf>,
/// Show detailed information for each result
#[arg(long)]
pub detailed: bool,
/// Sort results by field
#[arg(long, default_value = "relevance", value_enum, value_name = "FIELD")]
pub sort: SearchSort,
/// Reverse sort order
#[arg(long)]
pub reverse: bool,
/// Show only template IDs (useful for piping to other commands)
#[arg(long)]
pub ids_only: bool,
/// Show search statistics and summary
#[arg(long)]
pub stats: bool,
}
#[derive(Parser, Debug)]
#[command(
about = "Run as API server [NOT IMPLEMENTED — returns an error]",
long_about = "Intended to start CERT-X-GEN as a REST API server for remote scanning.\n\n\
NOT IMPLEMENTED: this command currently exits with \
`Error: Not implemented: API server not yet implemented`. The flags below \
(including --tls*) are accepted but the server does not start.",
after_help = "NOTE: `cxg server` is not implemented and exits with an error. The options \
below are placeholders and have no effect."
)]
pub struct ServerArgs {
/// Server port
#[arg(short, long, default_value_t = 8080, value_name = "PORT")]
pub port: u16,
/// Bind address (use 0.0.0.0 to listen on all interfaces)
#[arg(short, long, default_value = "127.0.0.1", value_name = "ADDRESS")]
pub bind: String,
/// Authentication token for API requests
#[arg(long, value_name = "TOKEN")]
pub auth_token: Option<String>,
/// Enable TLS/HTTPS
#[arg(long)]
pub tls: bool,
/// TLS certificate file path
#[arg(long, value_name = "FILE", requires = "tls")]
pub tls_cert: Option<PathBuf>,
/// TLS private key file path
#[arg(long, value_name = "FILE", requires = "tls")]
pub tls_key: Option<PathBuf>,
}
#[derive(Parser, Debug)]
#[command(
about = "Generate and manage configuration files",
long_about = "Create, validate, and manage CERT-X-GEN configuration files for reusable \
scan configurations and automation.",
after_help = "EXAMPLES:
# Generate default configuration
cxg config generate
cxg config generate --output config.yaml
cxg config generate --format toml --output config.toml
# Validate configuration
cxg config validate config.yaml
cxg config validate production.toml
# Show current/default configuration
cxg config show"
)]
pub struct ConfigCommand {
#[command(subcommand)]
pub action: ConfigAction,
}
#[derive(Subcommand, Debug)]
pub enum ConfigAction {
/// Generate a default configuration file
Generate {
/// Output file path
#[arg(short, long, default_value = "cert-x-gen.yaml", value_name = "FILE")]
output: PathBuf,
/// Configuration format
#[arg(short, long, value_enum, default_value = "yaml", value_name = "FORMAT")]
format: ConfigFormat,
},
/// Validate a configuration file
Validate {
/// Configuration file to validate
config: PathBuf,
},
/// Show current/default configuration
Show,
}
/// Sandbox management commands
#[derive(Parser, Debug)]
#[command(
about = "Manage per-language dependency environments",
long_about = "Initialize, manage, and configure per-language dependency environments for all \
supported programming languages: Python, JavaScript, Ruby, Perl, PHP, Rust, Go, \
and Java. This gives each runtime its own package directory, keeping template \
dependencies off the system package managers.\n\n\
This does NOT confine template execution. Templates execute as ordinary child \
processes with the invoking user's privileges and full network and filesystem \
access. Review templates before running them. For isolation, run cxg itself \
inside a container or VM, as a non-privileged user.",
after_help = "EXAMPLES:
# Initialize sandbox with all languages
cxg sandbox init
# Initialize specific languages only
cxg sandbox init --languages python,javascript,ruby
# Check sandbox status
cxg sandbox status
# Install additional packages
cxg sandbox install python requests beautifulsoup4
cxg sandbox install javascript axios cheerio
# Clean sandbox environment
cxg sandbox clean
# Access sandbox shell
cxg sandbox shell
# Show sandbox location
cxg sandbox path"
)]
pub struct SandboxCommand {
#[command(subcommand)]
pub action: SandboxAction,
}
/// Dependency environment management
///
/// Neither kind of environment below confines template execution. Templates execute as
/// ordinary child processes with the invoking user's privileges and full network and
/// filesystem access. Review templates before running them.
///
/// CERT-X-GEN supports two kinds of dependency environment:
///
/// 1. Docker environment:
/// - A container holding fresh Python, Ruby, Node, Go, Java, etc.
/// - Named environments (dev, test, prod)
/// - An interactive shell inside the container via 'enter' — work done in that
/// shell is contained by Docker in the ordinary way
/// - Scans launched from your host still run on your host, not in the container
/// - Commands: create, enter, delete, set-default, info
///
/// 2. Package environment:
/// - Python venv, npm node_modules, gem directories
/// - Uses host system's language runtimes
/// - Commands: init, status, install, clean
///
/// Use 'cxg sandbox info' to check Docker availability.
/// Use 'cxg sandbox create <name>' to create a Docker environment.
#[derive(Debug, Clone, Subcommand)]
pub enum SandboxAction {
/// Initialize package-level dependency environment
///
/// Creates separate package directories for Python (venv), JavaScript (node_modules),
/// Ruby (gems), etc. This mode uses your host system's language runtimes.
///
/// Note: this separates packages, not privileges. Templates still execute as ordinary
/// child processes with your privileges and full network and filesystem access.
///
/// The init command is smart:
/// - First run: Sets up all language environments and installs packages
/// - Subsequent runs: Only adds new languages or packages (skips existing)
/// - Use --force to rebuild everything from scratch
Init {
/// Force re-initialization (rebuild everything from scratch)
#[arg(short, long)]
force: bool,
/// Specific languages to initialize (comma-separated: python,node,ruby,go,etc.)
#[arg(short, long)]
languages: Option<String>,
/// Custom sandbox directory (default: OS-specific data directory)
#[arg(short, long)]
directory: Option<PathBuf>,
},
/// Check sandbox status
Status,
/// Install packages in sandbox
Install {
/// Language runtime
language: String,
/// Packages to install
packages: Vec<String>,
},
/// Clean sandbox environment
Clean {
/// Clean specific language only
#[arg(short, long)]
language: Option<String>,
/// Force clean without confirmation
#[arg(short, long)]
force: bool,
},
/// Open sandbox shell
Shell {
/// Language environment to use
#[arg(short, long, default_value = "bash")]
language: String,
},
/// Show sandbox path
Path,
/// Update sandbox packages
Update {
/// Update specific language only
#[arg(short, long)]
language: Option<String>,
},
/// Export sandbox configuration
Export {
/// Output file
#[arg(short, long, default_value = "sandbox-export.yaml")]
output: PathBuf,
/// Description
#[arg(short, long)]
description: Option<String>,
/// Author
#[arg(short, long)]
author: Option<String>,
},
/// Import sandbox configuration
Import {
/// Import file
file: PathBuf,
/// Force overwrite existing sandbox
#[arg(short, long)]
force: bool,
},
/// List available sandbox templates
Templates,
/// Use a pre-configured sandbox template
UseTemplate {
/// Template name (web-security, network-security, api-testing)
template: String,
},
/// List installed packages
List {
/// Language to list packages for
language: String,
},
/// Create a new Docker-based sandbox
Create {
/// Sandbox name
name: String,
/// Languages to install
#[arg(short, long, value_delimiter = ',')]
languages: Option<Vec<String>>,
/// Persist container between runs
#[arg(short, long, default_value = "true")]
persist: bool,
/// Auto-start on CLI launch
#[arg(short, long, default_value = "true")]
auto_start: bool,
},
/// Delete a sandbox
Delete {
/// Sandbox name
name: String,
/// Force deletion without confirmation
#[arg(short, long)]
force: bool,
},
/// Enter sandbox shell
Enter {
/// Sandbox name (uses default if not specified)
name: Option<String>,
},
/// Set default sandbox
SetDefault {
/// Sandbox name (clear default if not specified)
name: Option<String>,
},
/// Show Docker sandbox information
Info,
/// Build Docker image
Build {
/// Dockerfile path
#[arg(short, long)]
dockerfile: Option<PathBuf>,
},
}
// ─── MCP Command ─────────────────────────────────────────────────────
#[derive(Debug, Clone, Parser)]
#[command(about = "MCP (Model Context Protocol) server for AI agent integration")]
pub struct McpCommand {
#[command(subcommand)]
pub action: Option<McpAction>,
}
#[derive(Debug, Clone, Subcommand)]
pub enum McpAction {
/// Configure MCP server for AI coding agents (Claude Desktop, Claude Code, Cursor, etc.)
Install {
/// Specific clients to configure (comma-separated: claude-desktop,claude-code,cursor,windsurf,vscode,zed)
#[arg(long)]
client: Option<String>,
},
/// Remove MCP server configuration from AI coding agents
Uninstall {
/// Specific clients to unconfigure
#[arg(long)]
client: Option<String>,
},
/// Show current MCP configuration status across all detected clients
Status,
}
#[derive(Clone, Copy, Debug, clap::ValueEnum)]
pub enum SeverityArg {
/// Critical severity (highest priority)
Critical,
/// High severity
High,
/// Medium severity
Medium,
/// Low severity
Low,
/// Informational (lowest priority)
Info,
}
impl From<SeverityArg> for cert_x_gen::types::Severity {
fn from(arg: SeverityArg) -> Self {
match arg {
SeverityArg::Critical => cert_x_gen::types::Severity::Critical,
SeverityArg::High => cert_x_gen::types::Severity::High,
SeverityArg::Medium => cert_x_gen::types::Severity::Medium,
SeverityArg::Low => cert_x_gen::types::Severity::Low,
SeverityArg::Info => cert_x_gen::types::Severity::Info,
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum LanguageArg {
/// YAML declarative templates
Yaml,
/// Python interpreted templates
Python,
/// Rust compiled templates
Rust,
/// Shell/Bash script templates
Shell,
/// JavaScript/Node.js templates
JavaScript,
/// C compiled templates
C,
/// C++ compiled templates
Cpp,
/// Java compiled templates
Java,
/// Go compiled templates
Go,
/// Ruby interpreted templates
Ruby,
/// Perl interpreted templates
Perl,
/// PHP interpreted templates
Php,
}
impl From<LanguageArg> for cert_x_gen::types::TemplateLanguage {
fn from(arg: LanguageArg) -> Self {
match arg {
LanguageArg::Yaml => cert_x_gen::types::TemplateLanguage::Yaml,
LanguageArg::Python => cert_x_gen::types::TemplateLanguage::Python,
LanguageArg::Rust => cert_x_gen::types::TemplateLanguage::Rust,
LanguageArg::Shell => cert_x_gen::types::TemplateLanguage::Shell,
LanguageArg::JavaScript => cert_x_gen::types::TemplateLanguage::JavaScript,
LanguageArg::C => cert_x_gen::types::TemplateLanguage::C,
LanguageArg::Cpp => cert_x_gen::types::TemplateLanguage::Cpp,
LanguageArg::Java => cert_x_gen::types::TemplateLanguage::Java,
LanguageArg::Go => cert_x_gen::types::TemplateLanguage::Go,
LanguageArg::Ruby => cert_x_gen::types::TemplateLanguage::Ruby,
LanguageArg::Perl => cert_x_gen::types::TemplateLanguage::Perl,
LanguageArg::Php => cert_x_gen::types::TemplateLanguage::Php,
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConfigFormat {
/// YAML format
Yaml,
/// TOML format
Toml,
/// JSON format
Json,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SearchFormat {
/// Table format (human-readable, default)
Table,
/// JSON format (machine-readable)
Json,
/// YAML format
Yaml,
/// CSV format (spreadsheet-compatible)
Csv,
/// Simple list format (template IDs only)
List,
/// Detailed format (all information)
Detailed,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SearchSort {
/// Sort by relevance score (default)
Relevance,
/// Sort by template name
Name,
/// Sort by programming language
Language,
/// Sort by severity level
Severity,
/// Sort by author name
Author,
/// Sort by creation/update date
Date,
/// Sort by popularity/usage
Popularity,
}
// ============================================================================
// AI COMMAND
// ============================================================================
#[derive(Parser, Debug)]
#[command(
about = "AI-powered security template generation",
long_about = "Generate security scanning templates using AI/LLM providers. Supports local models \
(Ollama) and cloud providers (OpenAI, Anthropic, DeepSeek). No API key required \
for local generation with Ollama.",
after_help = "FEATURES:
• Generate templates from natural language descriptions
• Support for all 12 programming languages (YAML, Python, JavaScript, Rust, C, C++, Java, Go, Ruby, Perl, PHP, Shell)
• Multiple LLM providers (Ollama, OpenAI, Anthropic, DeepSeek)
• Local-first with Ollama (no API key needed, works offline)
• Automatic validation before saving
• Unlimited generations (you control your own LLM)
EXAMPLES:
# Generate with default provider (Ollama, local)
cxg ai generate \"detect Redis without authentication\"
cxg ai generate \"find SQL injection in login forms\"
cxg ai generate \"check for exposed Memcached\"
# Specify programming language
cxg ai generate \"detect Redis unauth\" --language python
cxg ai generate \"find XSS vulnerabilities\" --language javascript
cxg ai generate \"check SSL certificates\" --language rust
# Use specific provider
cxg ai generate \"detect RCE\" --provider openai --model gpt-4
cxg ai generate \"find SSRF\" --provider anthropic --model claude-3-5-sonnet-20241022
cxg ai generate \"check headers\" --provider ollama --model codellama:13b
# Save to specific location
cxg ai generate \"Redis check\" --language yaml --output templates/redis-test.yaml
cxg ai generate \"MySQL scan\" --output mysql-check.py
# List available providers
cxg ai providers list
cxg ai providers list --detailed
# Test provider connection
cxg ai providers test ollama
cxg ai providers test openai
# Show provider status
cxg ai providers status
GETTING STARTED WITH OLLAMA (FREE, LOCAL):
1. Install Ollama: curl -fsSL https://ollama.com/install.sh | sh
2. Download model: ollama pull codellama:13b
3. Start Ollama: ollama serve
4. Generate: cxg ai generate \"your security check description\"
PROVIDER CONFIGURATION:
Configure providers in ~/.cert-x-gen/ai-config.yaml or use environment variables:
- OPENAI_API_KEY for OpenAI
- ANTHROPIC_API_KEY for Anthropic
- DEEPSEEK_API_KEY for DeepSeek
For more information: https://github.com/Bugb-Technologies/cert-x-gen/docs/ai-features"
)]
pub struct AiCommand {
#[command(subcommand)]
pub action: AiAction,
}
#[derive(Subcommand, Debug)]
pub enum AiAction {
/// Generate a new template from natural language
Generate {
/// Natural language description of what to detect
///
/// Examples:
/// "detect Redis without authentication"
/// "find SQL injection vulnerabilities"
/// "check for exposed Memcached instances"
/// "scan for XSS in forms"
prompt: String,
/// Programming language for the template
#[arg(
short = 'l',
long,
value_enum,
default_value = "yaml",
value_name = "LANG",
help = "Template language (yaml, python, javascript, rust, etc.)"
)]
language: LanguageArg,
/// LLM provider to use
#[arg(
short = 'p',
long,
value_name = "PROVIDER",
help = "LLM provider (ollama, openai, anthropic, deepseek)"
)]
provider: Option<String>,
/// Model name to use
#[arg(
short = 'm',
long,
value_name = "MODEL",
help = "Model name (e.g., codellama:13b, gpt-4, claude-3-5-sonnet-20241022)"
)]
model: Option<String>,
/// Output file path (auto-generated if not specified)
#[arg(
short = 'o',
long,
value_name = "FILE",
help = "Output file path (default: ~/.cert-x-gen/templates/ai-generated/<name>.<ext>)"
)]
output: Option<PathBuf>,
/// Test the generated template immediately
#[arg(long, help = "Test the generated template after creation")]
test: bool,
/// Target to test against (requires --test)
#[arg(
long,
requires = "test",
value_name = "HOST",
help = "Target host for testing (e.g., localhost, 192.168.1.1)"
)]
test_target: Option<String>,
/// Force overwrite if file exists
#[arg(short = 'f', long, help = "Overwrite output file if it already exists")]
force: bool,
/// Show generation cost estimate (for cloud providers)
#[arg(
long,
help = "Estimate and show cost before generating (cloud providers only)"
)]
estimate_cost: bool,
/// API key for the LLM provider (session-only, not persisted to config).
/// Overrides environment variables and stored config for this invocation.
/// Use with --provider to specify which provider the key belongs to.
#[arg(
long,
value_name = "KEY",
help = "API key for the LLM provider (not saved). E.g. --provider anthropic --api-key sk-ant-..."
)]
api_key: Option<String>,
},
/// Manage LLM providers
#[command(after_help = "EXAMPLES:
# List all configured providers
cxg ai providers list
cxg ai providers list --detailed
# Test specific provider (comprehensive health check)
cxg ai providers test ollama
cxg ai providers test openai
cxg ai providers test anthropic
cxg ai providers test deepseek
# Check status of all enabled providers
cxg ai providers status
HEALTH CHECK DETAILS:
The 'test' command performs comprehensive diagnostics:
• Connection testing (can we reach the endpoint?)
• Authentication verification (is the API key valid?)
• Response time measurement (how fast is the provider?)
• Model availability check (what models can we use?)
• Helpful hints for common issues
The 'status' command tests all enabled providers at once,
giving you a quick overview of your AI setup.
TROUBLESHOOTING:
If a provider test fails, the output will include:
• Clear error messages explaining what went wrong
• Helpful hints for fixing the issue
• Setup instructions for unconfigured providers
Common issues:
• Ollama: Make sure it's running (ollama serve)
• Cloud providers: Check your API key environment variable
• Network: Verify your internet connection for cloud providers")]
Providers {
#[command(subcommand)]
action: ProviderAction,
},
}
#[derive(Subcommand, Debug)]
pub enum ProviderAction {
/// List all available providers
///
/// Shows which providers are configured and available.
/// Use --detailed to see more information about each provider.
List {
/// Show detailed information about each provider
#[arg(short = 'd', long, help = "Show detailed provider information")]
detailed: bool,
},
/// Test connection to a specific provider
///
/// Performs comprehensive health checks including:
/// - Connection testing
/// - Authentication verification
/// - Response time measurement
/// - Model availability check
///
/// Provides helpful diagnostic information if issues are found.
Test {
/// Provider name to test (ollama, openai, anthropic, deepseek)
provider: String,
},
/// Show status of all configured providers
///
/// Tests all enabled providers and displays their health status.
/// Quick way to see which providers are ready to use.
Status,
}
// @comment -- "unit tests for the desktop-target CLI flags (--target-type/--app-cmd/--app-binary), verifying clap's default, validation, and conflicts_with/required_if_eq resolution before wiring them into the orchestrator forwarding"
#[cfg(test)]
mod desktop_flag_tests {
use super::*;
fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
Cli::try_parse_from(args)
}
#[test]
fn target_type_defaults_to_web() {
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
])
.expect("should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs { target_type, .. }) = p.action {
assert_eq!(target_type, "web");
return;
}
}
panic!("expected pentest run");
}
#[test]
fn electron_requires_a_launch_mechanism() {
let err = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"electron",
]);
assert!(
err.is_err(),
"electron without --app-cmd/--app-binary must fail"
);
}
#[test]
fn app_cmd_and_app_binary_conflict() {
let err = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"electron",
"--app-cmd",
"npm start",
"--app-binary",
"/tmp/a",
]);
assert!(
err.is_err(),
"--app-cmd and --app-binary are mutually exclusive"
);
}
#[test]
fn electron_with_app_cmd_parses() {
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"electron",
"--app-cmd",
"npm run electron:dev",
])
.expect("should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs { app_cmd, .. }) = p.action {
assert_eq!(app_cmd.as_deref(), Some("npm run electron:dev"));
return;
}
}
panic!("expected pentest run");
}
// The two dispatch bounds and the recovery opt-out existed in the Python
// orchestrator only, so they were unreachable from the `cxg` binary: an operator
// could not raise the per-template ceiling, could not disable the stall watchdog,
// and could not decline having their application relaunched mid-engagement. This
// pins that all three now parse and that leaving them off yields None/false, so
// main.rs forwards nothing and the orchestrator's own defaults stay in force.
#[test]
fn timeout_and_restart_flags_parse_and_default_to_unset() {
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"electron",
"--app-cmd",
"npm start",
"--template-timeout",
"1200",
"--stall-timeout",
"45",
"--no-restart",
])
.expect("should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs {
template_timeout,
stall_timeout,
no_restart,
..
}) = p.action
{
assert_eq!(template_timeout, Some(1200.0));
assert_eq!(stall_timeout, Some(45.0));
assert!(no_restart);
} else {
panic!("expected pentest run");
}
} else {
panic!("expected pentest run");
}
let bare = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
])
.expect("should parse");
if let Some(Commands::Pentest(p)) = bare.command {
if let PentestAction::Run(PentestRunArgs {
template_timeout,
stall_timeout,
no_restart,
..
}) = p.action
{
assert_eq!(template_timeout, None);
assert_eq!(stall_timeout, None);
assert!(!no_restart);
return;
}
}
panic!("expected pentest run");
}
#[test]
fn rejects_unknown_target_type() {
// Sentinel is a value that is NOT a known substrate. "tauri" used to serve
// here and is now a valid source-surface target (see tauri_surface_map_parses),
// so this uses "gtk" to keep testing the same thing — clap rejects an unknown
// --target-type — rather than being quietly weakened into asserting a valid one
// is rejected.
assert!(parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"gtk"
])
.is_err());
}
#[test]
fn tauri_prove_flag_parses() {
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target-type",
"tauri",
"--tauri-prove",
"--tauri-prove-timeout",
"600",
])
.expect("tauri --tauri-prove should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs {
target_type,
tauri_prove,
tauri_prove_timeout,
..
}) = p.action
{
assert_eq!(target_type, "tauri");
assert!(tauri_prove);
assert_eq!(tauri_prove_timeout, 600);
return;
}
}
panic!("expected pentest run");
}
#[test]
fn tauri_prove_defaults_off() {
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target-type",
"tauri",
])
.expect("parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs {
tauri_prove,
tauri_prove_timeout,
..
}) = p.action
{
assert!(!tauri_prove);
assert_eq!(tauri_prove_timeout, 1200);
return;
}
}
panic!("expected pentest run");
}
#[test]
fn tauri_surface_map_parses_without_a_target() {
// A tauri source-surface map navigates nowhere, so --target is optional for it;
// --target becoming Option<String> is what makes this parse. The Python preflight
// still refuses a web/electron run with no --target.
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target-type",
"tauri",
])
.expect("tauri run should parse without --target");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs {
target_type,
target,
app_cmd,
..
}) = p.action
{
assert_eq!(target_type, "tauri");
assert!(target.is_none(), "no --target was given");
assert!(app_cmd.is_none(), "tauri needs no launch command");
return;
}
}
panic!("expected pentest run");
}
#[test]
fn electron_with_app_binary_alone_parses() {
// The task brief asserted clap resolves conflicts_with vs required_if_eq
// correctly for this case. It does not: clap's r_ifs/r_unless validation path
// (which required_if_eq feeds) never consults conflicts_with, so pairing
// `conflicts_with = "app_binary"` with `required_if_eq("target_type", "electron")`
// on app_cmd wrongly demanded --app-cmd even when --app-binary alone was given.
// Fixed by moving the conditional requirement to a `requires_if("electron",
// "app_cmd")` on `target_type`, which clap resolves through the ArgGroup-style
// "is_missing_required_ok" path that DOES check conflicts_with of present args.
let cli = parse(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
"--target-type",
"electron",
"--app-binary",
"/tmp/a",
])
.expect("--app-binary alone with --target-type electron should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Run(PentestRunArgs {
app_binary,
app_cmd,
..
}) = p.action
{
assert_eq!(app_binary.as_deref(), Some("/tmp/a"));
assert_eq!(app_cmd, None);
return;
}
}
panic!("expected pentest run");
}
#[test]
fn auth_electron_requires_a_launch_mechanism() {
// Same requires_if wiring was applied to PentestAction::Auth; verify it holds there too.
let err = parse(&[
"cxg",
"pentest",
"auth",
"--target",
"http://x",
"--profile",
"p1",
"--target-type",
"electron",
]);
assert!(
err.is_err(),
"electron without --app-cmd/--app-binary must fail"
);
}
#[test]
fn auth_electron_with_app_binary_alone_parses() {
let cli = parse(&[
"cxg",
"pentest",
"auth",
"--target",
"http://x",
"--profile",
"p1",
"--target-type",
"electron",
"--app-binary",
"/tmp/a",
])
.expect("--app-binary alone with --target-type electron should parse for auth too");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Auth {
app_binary,
app_cmd,
..
} = p.action
{
assert_eq!(app_binary.as_deref(), Some("/tmp/a"));
assert_eq!(app_cmd, None);
return;
}
}
panic!("expected pentest auth");
}
#[test]
fn auth_electron_with_app_cmd_parses() {
let cli = parse(&[
"cxg",
"pentest",
"auth",
"--target",
"http://x",
"--profile",
"p1",
"--target-type",
"electron",
"--app-cmd",
"npm run electron:dev",
])
.expect("should parse");
if let Some(Commands::Pentest(p)) = cli.command {
if let PentestAction::Auth {
app_cmd,
app_binary,
..
} = p.action
{
assert_eq!(app_cmd.as_deref(), Some("npm run electron:dev"));
assert_eq!(app_binary, None);
return;
}
}
panic!("expected pentest auth");
}
#[test]
fn auth_app_cmd_and_app_binary_conflict() {
let err = parse(&[
"cxg",
"pentest",
"auth",
"--target",
"http://x",
"--profile",
"p1",
"--target-type",
"electron",
"--app-cmd",
"npm start",
"--app-binary",
"/tmp/a",
]);
assert!(
err.is_err(),
"--app-cmd and --app-binary are mutually exclusive for auth too"
);
}
}
// @comment -- "unit tests for the two OAST modes: that the pollable one parses in both its bare and explicit forms, that clap rejects the pair (a split canary), and — the one that guards backward compatibility — that a lone --oast still parses to exactly what it always did"
#[cfg(test)]
mod oast_flag_tests {
use super::*;
fn run_action(args: &[&str]) -> PentestAction {
let cli = Cli::try_parse_from(args).expect("should parse");
match cli.command {
Some(Commands::Pentest(p)) => p.action,
_ => panic!("expected pentest"),
}
}
fn base() -> Vec<&'static str> {
vec![
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"http://x",
]
}
// Backward compatibility is the whole point of this one: an engagement script
// that has been passing `--oast <host>` since before the pollable mode existed
// must still parse to Some(host) with the new flag absent, so main.rs forwards
// the identical `--oast <host>` and nothing about that run changes.
#[test]
fn oast_alone_is_unchanged_and_leaves_interactsh_unset() {
let mut argv = base();
argv.extend(["--oast", "c4ca4238a0b92.oastify.com"]);
if let PentestAction::Run(PentestRunArgs {
oast,
oast_interactsh,
..
}) = run_action(&argv)
{
assert_eq!(oast.as_deref(), Some("c4ca4238a0b92.oastify.com"));
assert_eq!(oast_interactsh, None);
return;
}
panic!("expected pentest run");
}
// The bare form must be distinguishable from absence, not merely falsy: it means
// "register against interactsh's default servers", which is a request for a
// canary, whereas None means no canary at all. Some("") vs None is what carries
// that difference across to the orchestrator.
#[test]
fn bare_interactsh_yields_empty_string_not_none() {
let mut argv = base();
argv.push("--oast-interactsh");
if let PentestAction::Run(PentestRunArgs {
oast,
oast_interactsh,
..
}) = run_action(&argv)
{
assert_eq!(oast_interactsh.as_deref(), Some(""));
assert_eq!(oast, None);
return;
}
panic!("expected pentest run");
}
#[test]
fn interactsh_takes_an_explicit_server_url() {
let mut argv = base();
argv.extend(["--oast-interactsh", "https://oast.example.internal"]);
if let PentestAction::Run(PentestRunArgs {
oast_interactsh, ..
}) = run_action(&argv)
{
assert_eq!(
oast_interactsh.as_deref(),
Some("https://oast.example.internal")
);
return;
}
panic!("expected pentest run");
}
// Two canaries would split payloads between a pollable host and an unpollable
// one, so a blind finding could no longer be said to be confirmed or not.
// Enforced by clap's conflicts_with, so it fails during parse rather than after
// AI generation has already spent minutes and API budget.
#[test]
fn oast_and_oast_interactsh_conflict() {
let mut argv = base();
argv.extend([
"--oast",
"c4ca4238a0b92.oastify.com",
"--oast-interactsh",
"https://oast.example.internal",
]);
assert!(
Cli::try_parse_from(&argv).is_err(),
"--oast and --oast-interactsh are mutually exclusive"
);
// Also in the bare form, where the conflict is easiest to write by accident.
let mut bare = base();
bare.extend(["--oast", "c4ca4238a0b92.oastify.com", "--oast-interactsh"]);
assert!(
Cli::try_parse_from(&bare).is_err(),
"bare --oast-interactsh must conflict with --oast too"
);
}
// An optional-value flag placed before another flag must not swallow it.
#[test]
fn bare_interactsh_does_not_consume_a_following_flag() {
let mut argv = base();
argv.extend(["--oast-interactsh", "--headed"]);
if let PentestAction::Run(PentestRunArgs {
oast_interactsh,
headed,
..
}) = run_action(&argv)
{
assert_eq!(oast_interactsh.as_deref(), Some(""));
assert!(headed, "--headed must survive the optional-value flag");
return;
}
panic!("expected pentest run");
}
#[test]
fn neither_flag_leaves_both_unset() {
if let PentestAction::Run(PentestRunArgs {
oast,
oast_interactsh,
oast_listener,
..
}) = run_action(&base())
{
assert_eq!(oast, None);
assert_eq!(oast_interactsh, None);
assert_eq!(oast_listener, None);
return;
}
panic!("expected pentest run");
}
// The bare listener form means "bind the docker bridge", a request for a canary,
// so like bare --oast-interactsh it must be Some("") and distinguishable from the
// None that means no canary — that difference is what main.rs forwards as the flag
// alone rather than with an empty-string value.
#[test]
fn bare_listener_yields_empty_string_not_none() {
let mut argv = base();
argv.push("--oast-listener");
if let PentestAction::Run(PentestRunArgs { oast_listener, .. }) = run_action(&argv) {
assert_eq!(oast_listener.as_deref(), Some(""));
return;
}
panic!("expected pentest run");
}
#[test]
fn listener_takes_an_explicit_bind() {
let mut argv = base();
argv.extend(["--oast-listener", "host-docker-internal"]);
if let PentestAction::Run(PentestRunArgs { oast_listener, .. }) = run_action(&argv) {
assert_eq!(oast_listener.as_deref(), Some("host-docker-internal"));
return;
}
panic!("expected pentest run");
}
// One canary per run: the listener is a third pollable mode, and pairing it with
// either other canary would split payloads between callbacks nobody correlates,
// so clap rejects every pairing during parse.
#[test]
fn listener_conflicts_with_the_other_canaries() {
for other in [
vec!["--oast", "c4ca4238a0b92.oastify.com"],
vec!["--oast-interactsh"],
vec!["--oast-interactsh", "https://oast.example.internal"],
] {
let mut argv = base();
argv.push("--oast-listener");
argv.extend(other.iter().copied());
assert!(
Cli::try_parse_from(&argv).is_err(),
"--oast-listener must conflict with {other:?}"
);
}
}
// The DNS leg is an independent boolean that only means anything alongside the
// listener, but it must parse on its own without consuming the listener's value.
#[test]
fn listener_dns_is_an_independent_boolean() {
let mut argv = base();
argv.extend(["--oast-listener", "127.0.0.1", "--oast-listener-dns"]);
if let PentestAction::Run(PentestRunArgs {
oast_listener,
oast_listener_dns,
..
}) = run_action(&argv)
{
assert_eq!(oast_listener.as_deref(), Some("127.0.0.1"));
assert!(oast_listener_dns);
return;
}
panic!("expected pentest run");
}
#[test]
fn listener_redirect_and_rebinding_options_parse() {
let mut argv = base();
argv.extend([
"--oast-listener",
"127.0.0.1",
"--oast-listener-dns",
"--oast-redirect-location",
"http://169.254.169.254/latest/meta-data/",
"--oast-redirect-status",
"307",
"--oast-dns-rebind-ip",
"169.254.169.254",
]);
if let PentestAction::Run(PentestRunArgs {
oast_redirect_location,
oast_redirect_status,
oast_dns_rebind_ip,
..
}) = run_action(&argv)
{
assert_eq!(
oast_redirect_location.as_deref(),
Some("http://169.254.169.254/latest/meta-data/")
);
assert_eq!(oast_redirect_status.as_deref(), Some("307"));
assert_eq!(oast_dns_rebind_ip.as_deref(), Some("169.254.169.254"));
return;
}
panic!("expected pentest run");
}
#[test]
fn redirect_and_rebinding_options_require_the_listener() {
for options in [
vec!["--oast-redirect-location", "http://internal.example/"],
vec!["--oast-redirect-status", "307"],
vec!["--oast-dns-rebind-ip", "169.254.169.254"],
vec![
"--oast-listener",
"127.0.0.1",
"--oast-dns-rebind-ip",
"169.254.169.254",
],
vec![
"--oast-listener",
"127.0.0.1",
"--oast-redirect-status",
"303",
],
] {
let mut argv = base();
argv.extend(options);
assert!(Cli::try_parse_from(&argv).is_err());
}
}
}
// @comment -- "unit tests for the Track B CI-auth surface (auth import / auth verify subcommands, and run's --ci/--auth-dir). Track B shipped to the Python orchestrator's argparse only; src/cli.rs was never updated, so the cxg binary rejected the whole surface with 'unexpected argument'. These pin that each subcommand and flag now parses, that the auth capture path is unchanged when no subcommand is given, that the import/verify subcommands do NOT demand the capture path's --target/--profile (the reason those two are Option at the parent), and that the mutually-exclusive capture-args-vs-subcommand constraint holds."
#[cfg(test)]
mod track_b_auth_tests {
use super::*;
#[test]
fn auth_capture_and_list_accept_auth_dir() {
for args in [
vec![
"cxg",
"pentest",
"auth",
"--target",
"https://x",
"--profile",
"p",
"--auth-dir",
"./profiles",
],
vec!["cxg", "pentest", "auth-list", "--auth-dir", "./profiles"],
] {
match action(&args) {
PentestAction::Auth { auth_dir, .. } | PentestAction::AuthList { auth_dir } => {
assert_eq!(auth_dir, Some(PathBuf::from("./profiles")));
}
_ => panic!("expected auth action"),
}
}
}
fn action(args: &[&str]) -> PentestAction {
let cli = Cli::try_parse_from(args).expect("should parse");
match cli.command {
Some(Commands::Pentest(p)) => p.action,
_ => panic!("expected pentest"),
}
}
fn err(args: &[&str]) -> bool {
Cli::try_parse_from(args).is_err()
}
// ---- auth import ----
#[test]
fn auth_import_parses_full_surface() {
let a = action(&[
"cxg",
"pentest",
"auth",
"import",
"--profile",
"pentest",
"--target",
"https://staging.app",
"--storage-state",
"./s.json",
"--label",
"admin",
"--tier",
"high",
"--persona",
"billing",
"--cohort",
"team-a",
"--tag",
"k1=v1",
"--tag",
"k2=v2",
"--header",
"x-a:1",
"--header",
"x-b:2",
"--auth-dir",
"./ci-auth",
"--liveness-path",
"/session",
"--liveness-status",
"200",
"--liveness-status",
"204",
"--service",
"community",
"--ci",
]);
match a {
PentestAction::Auth {
auth_sub:
Some(AuthSubcommand::Import {
profile,
target,
storage_state,
label,
tier,
persona,
cohort,
tags,
headers,
auth_dir,
liveness_path,
liveness_status,
service,
ci,
}),
..
} => {
assert_eq!(profile, "pentest");
assert_eq!(target, "https://staging.app");
assert_eq!(storage_state.as_deref(), Some("./s.json"));
assert_eq!(label.as_deref(), Some("admin"));
assert_eq!(tier.as_deref(), Some("high"));
assert_eq!(persona.as_deref(), Some("billing"));
assert_eq!(cohort.as_deref(), Some("team-a"));
assert_eq!(tags, vec!["k1=v1", "k2=v2"]);
assert_eq!(headers, vec!["x-a:1", "x-b:2"]);
assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
assert!(ci);
assert_eq!(liveness_path.as_deref(), Some("/session"));
assert_eq!(liveness_status, vec![200, 204]);
assert_eq!(service.as_deref(), Some("community"));
}
_ => panic!("expected auth import"),
}
}
// The whole point of Option-typed parent --target/--profile: `auth import`
// must NOT inherit the capture path's requirements, only its own.
#[test]
fn auth_import_does_not_require_parent_target_or_profile() {
// import supplies its own --profile/--target and nothing at the parent level.
let a = action(&[
"cxg",
"pentest",
"auth",
"import",
"--profile",
"p",
"--target",
"https://x",
]);
match a {
PentestAction::Auth {
target,
profile,
auth_sub:
Some(AuthSubcommand::Import {
storage_state, ci, ..
}),
..
} => {
// parent capture fields stay unset
assert_eq!(target, None);
assert_eq!(profile, None);
// omitting --storage-state is valid (env-var fallback on the Python side)
assert_eq!(storage_state, None);
assert!(!ci);
}
_ => panic!("expected auth import"),
}
}
#[test]
fn auth_import_stdin_marker_is_a_value() {
let a = action(&[
"cxg",
"pentest",
"auth",
"import",
"--profile",
"p",
"--target",
"https://x",
"--storage-state",
"-",
]);
match a {
PentestAction::Auth {
auth_sub: Some(AuthSubcommand::Import { storage_state, .. }),
..
} => assert_eq!(storage_state.as_deref(), Some("-")),
_ => panic!("expected auth import"),
}
}
#[test]
fn auth_import_requires_profile_and_target() {
assert!(
err(&["cxg", "pentest", "auth", "import", "--target", "https://x"]),
"import without --profile must fail"
);
assert!(
err(&["cxg", "pentest", "auth", "import", "--profile", "p"]),
"import without --target must fail"
);
}
// ---- auth verify ----
#[test]
fn auth_verify_parses_with_defaults() {
let a = action(&["cxg", "pentest", "auth", "verify", "--profile", "pentest"]);
match a {
PentestAction::Auth {
auth_sub:
Some(AuthSubcommand::Verify {
profile,
target,
me_path,
auth_dir,
}),
..
} => {
assert_eq!(profile, "pentest");
assert_eq!(target, None);
assert_eq!(me_path, "/api/me"); // mirrors auth.py's default
assert_eq!(auth_dir, None);
}
_ => panic!("expected auth verify"),
}
}
#[test]
fn auth_verify_accepts_overrides() {
let a = action(&[
"cxg",
"pentest",
"auth",
"verify",
"--profile",
"p",
"--target",
"https://y",
"--me-path",
"/whoami",
"--auth-dir",
"./ci-auth",
]);
match a {
PentestAction::Auth {
auth_sub:
Some(AuthSubcommand::Verify {
target,
me_path,
auth_dir,
..
}),
..
} => {
assert_eq!(target.as_deref(), Some("https://y"));
assert_eq!(me_path, "/whoami");
assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
}
_ => panic!("expected auth verify"),
}
}
#[test]
fn auth_verify_requires_profile() {
assert!(
err(&["cxg", "pentest", "auth", "verify"]),
"verify without --profile must fail"
);
}
// ---- interactive capture path is unchanged (no subcommand) ----
#[test]
fn bare_auth_capture_still_parses_and_leaves_sub_none() {
let a = action(&[
"cxg",
"pentest",
"auth",
"--target",
"https://x",
"--profile",
"p",
]);
match a {
PentestAction::Auth {
target,
profile,
auth_sub,
..
} => {
assert_eq!(target.as_deref(), Some("https://x"));
assert_eq!(profile.as_deref(), Some("p"));
assert!(auth_sub.is_none(), "no subcommand => interactive capture");
}
_ => panic!("expected auth capture"),
}
}
// Capture args and a subcommand are mutually exclusive on one invocation
// (args_conflicts_with_subcommands): you either capture, or import/verify.
#[test]
fn capture_args_conflict_with_subcommand() {
assert!(
err(&[
"cxg",
"pentest",
"auth",
"--target",
"https://x",
"import",
"--profile",
"p",
"--target",
"https://x",
]),
"parent capture args must conflict with a subcommand"
);
}
// ---- run --ci / --auth-dir ----
#[test]
fn run_ci_and_auth_dir_parse() {
let a = action(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"https://x",
"--ci",
"--auth-dir",
"./ci-auth",
]);
match a {
PentestAction::Run(PentestRunArgs {
ci,
probe_inputs: ProbeInputs { auth_dir, .. },
..
}) => {
assert!(ci);
assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
}
_ => panic!("expected pentest run"),
}
}
#[test]
fn run_defaults_leave_ci_false_and_auth_dir_none() {
let a = action(&[
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"https://x",
]);
match a {
PentestAction::Run(PentestRunArgs {
ci,
probe_inputs: ProbeInputs { auth_dir, .. },
..
}) => {
assert!(!ci, "--ci defaults off, so main.rs forwards nothing");
assert_eq!(auth_dir, None);
}
_ => panic!("expected pentest run"),
}
}
}
#[cfg(test)]
mod pentest_transport_tests {
use super::*;
#[test]
fn web_transport_flags_parse_and_require_a_certificate_pair() {
let base = [
"cxg",
"pentest",
"run",
"--codebase",
".",
"--target",
"https://example.test",
];
let mut argv = base.to_vec();
argv.extend([
"--insecure-tls",
"--proxy",
"http://127.0.0.1:8080",
"--client-cert",
"client.pem",
"--client-key",
"client.key",
]);
let cli = Cli::try_parse_from(argv).unwrap();
match cli.command {
Some(Commands::Pentest(PentestCommand {
action:
PentestAction::Run(PentestRunArgs {
insecure_tls,
proxy,
client_cert,
client_key,
..
}),
})) => {
assert!(insecure_tls);
assert_eq!(proxy.as_deref(), Some("http://127.0.0.1:8080"));
assert_eq!(client_cert, Some(PathBuf::from("client.pem")));
assert_eq!(client_key, Some(PathBuf::from("client.key")));
}
_ => panic!("expected pentest run"),
}
for flag in ["--client-cert", "--client-key"] {
let mut argv = base.to_vec();
argv.extend([flag, "file.pem"]);
assert!(Cli::try_parse_from(argv).is_err());
}
}
}
#[cfg(test)]
mod scan_front_door_tests {
use super::*;
#[test]
fn a_probe_argument_cannot_switch_engines_or_change_scan_validation() {
let cli = Cli::try_parse_from([
"cxg",
"scan",
"--scope",
"cli:///bin/tool",
"--arg",
"--pentest",
"--templates",
"baseline",
"--template-dir",
"./pack",
])
.unwrap();
match cli.command {
Some(Commands::Scan(scan)) => {
assert_eq!(scan.arg, ["--pentest"]);
assert_eq!(scan.templates, ["baseline"]);
assert_eq!(scan.template_dir, Some(PathBuf::from("./pack")));
assert!(!scan.pentest);
}
_ => panic!("probe argument switched engines"),
}
let error =
Cli::try_parse_from(["cxg", "scan", "--arg", "--pentest", "--help"]).unwrap_err();
assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
assert!(error.to_string().contains("--parallel-targets"));
}
#[test]
fn globals_and_switch_position_are_parsed_by_clap() {
let cli = Cli::try_parse_from([
"cxg",
"--config",
"scan",
"scan",
"--codebase",
".",
"--target-type",
"tauri",
"--pentest",
])
.unwrap();
assert_eq!(cli.config, Some(PathBuf::from("scan")));
assert!(
matches!(cli.command, Some(Commands::Pentest(PentestCommand {
action: PentestAction::Run(PentestRunArgs { target_type, target: None, .. })
})) if target_type == "tauri")
);
}
#[test]
fn replay_inputs_preserve_bare_optional_values_and_repeated_options() {
let parsed = Cli::try_parse_from([
"cxg",
"scan",
"--scope",
"http://localhost",
"--oast-listener",
"--only-route",
"GET /a",
"--only-route",
"POST /b",
])
.unwrap();
let Some(Commands::Scan(scan)) = parsed.command else {
panic!("expected scan")
};
let run = scan.probe_run.unwrap();
assert_eq!(run.oast_listener.as_deref(), Some(""));
assert_eq!(run.only_route, ["GET /a", "POST /b"]);
}
#[test]
fn plain_scan_reuses_non_authoring_engine_values_and_constraints() {
let parsed = Cli::try_parse_from([
"cxg",
"scan",
"--scope",
"http://localhost",
"--no-author",
"--no-code-graph",
"--attestation",
"local fixture",
"--mitigation-mode",
"mitigated",
"--me-path",
"/identity",
"--ci",
"--enable-chaining",
"--template-timeout",
"1.25",
"--stall-timeout",
"9.5",
"--destructive-ok",
"--allow-grpc",
"--grpc-descriptor-set",
"descriptors.pb",
"--tauri-prove",
"--host-scan-path",
"/fixture/install",
])
.unwrap();
let Some(Commands::Scan(scan)) = parsed.command else {
panic!("expected scan")
};
let run = scan.probe_run.unwrap();
assert!(run.probe_inputs.no_author && run.no_code_graph && run.ci && run.enable_chaining);
assert_eq!(run.attestation.as_deref(), Some("local fixture"));
assert_eq!(run.mitigation_mode, "mitigated");
assert_eq!(run.me_path, "/identity");
assert_eq!(run.template_timeout, Some(1.25));
assert_eq!(run.stall_timeout, Some(9.5));
assert!(run.destructive_ok && run.allow_grpc && run.tauri_prove);
assert_eq!(run.grpc_descriptor_set.as_deref(), Some("descriptors.pb"));
assert_eq!(run.host_scan_path.as_deref(), Some("/fixture/install"));
assert!(Cli::try_parse_from(["cxg", "scan", "--client-cert", "cert.pem"]).is_err());
assert!(Cli::try_parse_from(["cxg", "scan", "--ai"]).is_err());
assert!(Cli::try_parse_from(["cxg", "scan", "--mutation-retries", "1"]).is_err());
}
#[test]
fn ordinary_scan_accepts_shared_probe_inputs_and_defaults_codebase() {
let parsed = Cli::try_parse_from([
"cxg",
"scan",
"--scope",
"https://example.test",
"--auth",
"attacker,victim",
"--auth-dir",
"profiles",
"--auth-inputs",
"inputs.json",
"--scope-file",
"scope.yaml",
"--session-dir",
"session",
])
.unwrap();
let Some(Commands::Scan(args)) = parsed.command else {
panic!("expected scan")
};
assert_eq!(args.probe_inputs.codebase, PathBuf::from("."));
assert_eq!(args.probe_inputs.auth, "attacker,victim");
assert_eq!(args.probe_inputs.auth_dir, Some(PathBuf::from("profiles")));
assert_eq!(
args.probe_inputs.auth_inputs,
Some(PathBuf::from("inputs.json"))
);
assert_eq!(
args.probe_inputs.scope_file,
Some(PathBuf::from("scope.yaml"))
);
assert_eq!(
args.probe_inputs.session_dir,
Some(PathBuf::from("session"))
);
assert!(
Cli::try_parse_from(["cxg", "pentest", "run", "--target", "https://example.test"])
.is_err()
);
}
#[test]
fn pentest_scan_requires_a_codebase_and_rejects_duplicate_targets() {
let error = Cli::try_parse_from(["cxg", "scan", "--pentest"]).unwrap_err();
assert_eq!(
error.kind(),
clap::error::ErrorKind::MissingRequiredArgument
);
assert!(error.to_string().contains("--codebase"));
assert!(Cli::try_parse_from([
"cxg",
"scan",
"--pentest",
"--codebase",
".",
"--scope",
"https://a.test",
"--target",
"https://b.test",
])
.unwrap_err()
.to_string()
.contains("one target"));
}
}