diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b1248a7..d63857b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,10 +17,17 @@ jobs: - name: Setup Rust uses: dtolnay/rust-toolchain@stable + with: + components: llvm-tools-preview + + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@cargo-llvm-cov + + - name: Install cargo-audit + uses: taiki-e/install-action@cargo-audit - name: Cache cargo uses: Swatinem/rust-cache@v2 - - - name: Run unit tests - run: cargo test + - name: CI gate + run: ./harness ci diff --git a/.gitignore b/.gitignore index 4afdf4d..593cff5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ *.zip node_modules/ /packages/*/vendor/ + +.claude/ +CLAUDE.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a98210f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,18 @@ +# AGENTS.md + +This subproject is the Corgea developer CLI (Rust → npm + pip via maturin). + +## Commands + +- After edits: `./harness check` — clippy fix, format, tests, suppression report +- Pre-commit: `./harness pre-commit` — staged Rust files only (auto via git hook) +- CI: `./harness ci` — strict clippy (`-D warnings`), format check, dep audit, tests + coverage gate (min 13%) +- Audit: `./harness audit` — `cargo audit` for known dep vulnerabilities +- Coverage: `./harness coverage [--min=N]` — cargo-llvm-cov; HTML report under `target/llvm-cov/`; fails if line coverage < N (default 13) +- Lint: `./harness lint` — clippy + format check, no fixes +- Test: `./harness test` — `cargo test` +- Fix: `./harness fix` — clippy fix + format +- Setup: `./harness setup-hooks` — install `.git/hooks/pre-commit` +- Auto-format: `./harness post-edit` — runs `cargo fmt` on changed Rust files (wire into your editor/agent's post-edit hook) + +Add `--verbose` to stream raw command output instead of the quiet summary. diff --git a/harness b/harness new file mode 100755 index 0000000..61cc0b1 --- /dev/null +++ b/harness @@ -0,0 +1,293 @@ +#!/usr/bin/env bash +# Project development tasks. Bash + cargo + git only. +# Usage: ./harness [--verbose] [--min=N] +# +# Commands: check, fix, lint, test, audit, coverage, pre-commit, ci, +# post-edit, setup-hooks, suppressions + +set -u + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$ROOT" + +VERBOSE=0 +COVERAGE_MIN=13 +for arg in "$@"; do + case "$arg" in + --verbose) VERBOSE=1 ;; + --min=*) COVERAGE_MIN="${arg#--min=}" ;; + esac +done + +if [ -t 1 ]; then + GREEN=$'\033[32m'; RED=$'\033[31m'; BLUE=$'\033[34m'; DIM=$'\033[2m'; RESET=$'\033[0m' +else + GREEN=""; RED=""; BLUE=""; DIM=""; RESET="" +fi + +# ── Runner ────────────────────────────────────────────────────────── +# run -- +# Quiet by default: captures stdout+stderr, prints only on failure. +# --verbose streams raw output. +# no_exit=1 lets the caller aggregate failures (e.g. cmd_check). + +LAST_RC=0 +LAST_OUTPUT="" + +run() { + local desc="$1"; shift + local no_exit="$1"; shift + [ "$1" = "--" ] && shift + + if [ "$VERBOSE" -eq 1 ]; then + printf " %s→ %s%s\n" "$DIM" "$*" "$RESET" + "$@" + LAST_RC=$? + LAST_OUTPUT="" + if [ "$LAST_RC" -eq 0 ]; then + printf " %s✓%s %s\n" "$GREEN" "$RESET" "$desc" + return 0 + fi + printf " %s✗%s %s\n" "$RED" "$RESET" "$desc" + [ "$no_exit" = "0" ] && exit "$LAST_RC" + return "$LAST_RC" + fi + + local tmp; tmp="$(mktemp)" + "$@" >"$tmp" 2>&1 + LAST_RC=$? + LAST_OUTPUT="$(cat "$tmp")" + rm -f "$tmp" + if [ "$LAST_RC" -eq 0 ]; then + printf " %s✓%s %s\n" "$GREEN" "$RESET" "$desc" + return 0 + fi + printf " %s✗%s %s\n" "$RED" "$RESET" "$desc" + [ -n "$LAST_OUTPUT" ] && printf "%s\n" "$LAST_OUTPUT" + [ "$no_exit" = "0" ] && exit "$LAST_RC" + return "$LAST_RC" +} + +run_with_summary() { + local desc="$1"; shift + local no_exit="$1"; shift + [ "$1" = "--" ] && shift + + run "$desc" "$no_exit" -- "$@" + local rc=$? + [ $rc -ne 0 ] && return $rc + + # Reprint last line with test summary suffix (cargo test). + local passed total_passed=0 duration=0 + while IFS= read -r line; do + passed="$(printf "%s" "$line" | sed -nE 's/.*ok\. ([0-9]+) passed.*/\1/p')" + [ -n "$passed" ] && total_passed=$(( total_passed + passed )) + local d + d="$(printf "%s" "$line" | sed -nE 's/.*finished in ([0-9.]+)s.*/\1/p')" + if [ -n "$d" ]; then + awk_cmp=$(awk -v a="$d" -v b="$duration" 'BEGIN{print (a>b)?1:0}') + [ "$awk_cmp" = "1" ] && duration="$d" + fi + done <<<"$LAST_OUTPUT" + if [ "$total_passed" -gt 0 ]; then + # Overwrite previous OK line with summary detail. + printf "\033[1A\033[2K %s✓%s %s %s(%s passed, %ss)%s\n" \ + "$GREEN" "$RESET" "$desc" "$DIM" "$total_passed" "$duration" "$RESET" + fi + return 0 +} + +# ── Git helpers ───────────────────────────────────────────────────── + +staged_rs_files() { + git diff --cached --name-only --diff-filter=d --relative 2>/dev/null \ + | grep -E '\.rs$' || true +} + +changed_rs_files() { + git status --porcelain 2>/dev/null \ + | sed -E 's/^...//' \ + | grep -E '\.rs$' || true +} + +# ── Suppressions (report-only) ────────────────────────────────────── + +cmd_suppressions() { + printf "\n=== Suppressions ===\n\n" + local total=0 line_total=0 crate_total=0 + local file + local tmp; tmp="$(mktemp)" + while IFS= read -r -d '' file; do + grep -oE '#!?\[allow\([^)]*\)\]' "$file" 2>/dev/null >>"$tmp" || true + done < <(find src -type f -name '*.rs' -print0 2>/dev/null) + [ -d tests ] && while IFS= read -r -d '' file; do + grep -oE '#!?\[allow\([^)]*\)\]' "$file" 2>/dev/null >>"$tmp" || true + done < <(find tests -type f -name '*.rs' -print0 2>/dev/null) + + line_total=$(awk '/^#\[allow/ {n++} END{print n+0}' "$tmp") + crate_total=$(awk '/^#!\[allow/ {n++} END{print n+0}' "$tmp") + total=$(( line_total + crate_total )) + + printf "Suppressions: %d total\n" "$total" + [ "$total" -eq 0 ] && { rm -f "$tmp"; return 0; } + [ "$line_total" -gt 0 ] && printf " allow: %d\n" "$line_total" + [ "$crate_total" -gt 0 ] && printf " allow_crate: %d\n" "$crate_total" + + # Top 10 rules across both kinds. + sed -E 's/#!?\[allow\(([^)]*)\)\]/\1/' "$tmp" \ + | tr ',' '\n' \ + | sed -E 's/^[[:space:]]+|[[:space:]]+$//g' \ + | grep -v '^$' \ + | sort | uniq -c | sort -rn | head -10 \ + | awk '{ rule=$2; for (i=3;i<=NF;i++) rule=rule" "$i; printf " %s: %d\n", rule, $1 }' + rm -f "$tmp" + return 0 +} + +# ── Commands ──────────────────────────────────────────────────────── + +cmd_fix() { + run "Clippy fix" 0 -- cargo clippy --fix --allow-dirty --allow-staged + run "Format" 0 -- cargo fmt +} + +cmd_lint() { + run "Clippy" 0 -- cargo clippy + run "Format check" 0 -- cargo fmt --check +} + +cmd_test() { + run_with_summary "Tests" 0 -- cargo test +} + +cmd_audit() { + _cmd_audit_inner 0 +} + +_cmd_audit_inner() { + local strict="$1" + if cargo audit --version >/dev/null 2>&1; then + run "Dep audit" 0 -- cargo audit + return + fi + if [ "$strict" = "1" ]; then + printf " %s✗%s Dep audit (cargo-audit not installed)\n" "$RED" "$RESET" + exit 1 + fi + printf " %s⊘ Dep audit skipped (install: cargo install cargo-audit)%s\n" "$DIM" "$RESET" +} + +cmd_coverage() { + printf "\n%s[coverage]%s min=%s%%\n\n" "$BLUE" "$RESET" "$COVERAGE_MIN" + if ! cargo llvm-cov --version >/dev/null 2>&1; then + printf " %s✗%s Coverage (cargo-llvm-cov not installed)\n" "$RED" "$RESET" + printf " %sInstall:%s cargo install cargo-llvm-cov\n" "$DIM" "$RESET" + exit 1 + fi + run "Coverage (min ${COVERAGE_MIN}%)" 0 -- \ + cargo llvm-cov --summary-only --fail-under-lines "$COVERAGE_MIN" + run "HTML report" 0 -- cargo llvm-cov report --html + printf " %sHTML:%s %s/target/llvm-cov/html/index.html\n" \ + "$DIM" "$RESET" "$ROOT" +} + +cmd_post_edit() { + local changed; changed="$(changed_rs_files)" + [ -z "$changed" ] && return 0 + # Never fail the Stop hook. + run "Format" 1 -- cargo fmt || true + return 0 +} + +cmd_pre_commit() { + local staged; staged="$(staged_rs_files)" + if [ -z "$staged" ]; then + printf "No staged Rust files — skipping checks\n" + return 0 + fi + printf "\n%s[pre-commit]%s\n\n" "$BLUE" "$RESET" + # Check-only: never rewrite the working tree behind the commit. + # Mirrors the CI gate so anything that passes here passes there. + run "Clippy (strict)" 0 -- cargo clippy -- -D warnings + run "Format check" 0 -- cargo fmt --check + cmd_test +} + +cmd_check() { + local start; start=$(date +%s) + printf "\n%s[check]%s Running pre-flight checks...\n\n" "$BLUE" "$RESET" + + local passed=0 failed=0 + run "Clippy fix" 1 -- cargo clippy --fix --allow-dirty --allow-staged + [ $? -eq 0 ] && passed=$(( passed + 1 )) || failed=$(( failed + 1 )) + run "Format" 1 -- cargo fmt + [ $? -eq 0 ] && passed=$(( passed + 1 )) || failed=$(( failed + 1 )) + run "Clippy (strict)" 1 -- cargo clippy -- -D warnings + [ $? -eq 0 ] && passed=$(( passed + 1 )) || failed=$(( failed + 1 )) + run_with_summary "Tests" 1 -- cargo test + [ $? -eq 0 ] && passed=$(( passed + 1 )) || failed=$(( failed + 1 )) + + cmd_suppressions + + local elapsed=$(( $(date +%s) - start )) + printf "\n" + if [ "$failed" -gt 0 ]; then + printf "%sFAIL%s %d passed, %d failed %s(%ds)%s\n" \ + "$RED" "$RESET" "$passed" "$failed" "$DIM" "$elapsed" "$RESET" + exit 1 + fi + printf "%sOK%s %d passed %s(%ds)%s\n" \ + "$GREEN" "$RESET" "$passed" "$DIM" "$elapsed" "$RESET" +} + +cmd_ci() { + printf "\n%s[ci]%s\n\n" "$BLUE" "$RESET" + run "Clippy (strict)" 0 -- cargo clippy -- -D warnings + run "Format check" 0 -- cargo fmt --check + _cmd_audit_inner 1 + if ! cargo llvm-cov --version >/dev/null 2>&1; then + printf " %s✗%s Coverage (cargo-llvm-cov not installed)\n" "$RED" "$RESET" + printf " %sInstall:%s cargo install cargo-llvm-cov\n" "$DIM" "$RESET" + exit 1 + fi + run_with_summary "Tests + coverage (min ${COVERAGE_MIN}%)" 0 -- \ + cargo llvm-cov --summary-only --fail-under-lines "$COVERAGE_MIN" +} + +cmd_setup_hooks() { + local hook_dir="$ROOT/.git/hooks" + local hook="$hook_dir/pre-commit" + mkdir -p "$hook_dir" + cat >"$hook" <<'EOF' +#!/bin/sh +exec "$(git rev-parse --show-toplevel)/harness" pre-commit +EOF + chmod +x "$hook" + printf "Installed pre-commit hook at %s\n" "$hook" +} + +# ── Dispatch ──────────────────────────────────────────────────────── + +cmd="${1:-check}" +case "$cmd" in + check) cmd_check ;; + fix) cmd_fix ;; + lint) cmd_lint ;; + test) cmd_test ;; + audit) cmd_audit ;; + coverage) cmd_coverage ;; + pre-commit) cmd_pre_commit ;; + ci) cmd_ci ;; + post-edit) cmd_post_edit ;; + setup-hooks) cmd_setup_hooks ;; + suppressions) cmd_suppressions ;; + -h|--help|help) + printf "Usage: ./harness [--verbose] [--min=N]\n\n" + printf "Commands: check, fix, lint, test, audit, coverage, pre-commit,\n" + printf " ci, post-edit, setup-hooks, suppressions\n" + ;; + *) + printf "Unknown command: %s\n" "$cmd" >&2 + exit 1 + ;; +esac diff --git a/src/authorize.rs b/src/authorize.rs index 39b5df3..686c042 100644 --- a/src/authorize.rs +++ b/src/authorize.rs @@ -1,17 +1,19 @@ -use crate::{config::Config, utils::{terminal, api}}; +use crate::{ + config::Config, + utils::{api, terminal}, +}; +use http_body_util::Full; +use hyper::body::Bytes; use hyper::body::Incoming; use hyper::service::service_fn; use hyper::{Request, Response, StatusCode}; use hyper_util::rt::TokioIo; -use http_body_util::Full; -use hyper::body::Bytes; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use tokio::net::TcpListener; - const DEFAULT_PORT: u16 = 9876; pub fn run(scope: Option, url: Option) -> Result<(), Box> { @@ -24,60 +26,62 @@ pub fn run(scope: Option, url: Option) -> Result<(), Box "https://www.corgea.app".to_string(), }; - + // Find available port starting from default let port = find_available_port(DEFAULT_PORT)?; let callback_url = format!("http://localhost:{}", port); - let auth_url = format!("{}/authorize?callback={}", base_domain, - urlencoding::encode(&callback_url)); - + let auth_url = format!( + "{}/authorize?callback={}", + base_domain, + urlencoding::encode(&callback_url) + ); + println!("Opening browser to authorize Corgea CLI..."); println!("Authorization URL: {}", auth_url); - + // Open browser if let Err(e) = open::that(&auth_url) { eprintln!("Failed to open browser automatically: {}", e); println!("Please manually open the following URL in your browser:"); println!("{}", auth_url); } - + // Set up shared state for the authorization code let auth_code = Arc::new(Mutex::new(None::)); let auth_code_clone = auth_code.clone(); - + // Set up loading message let stop_signal = Arc::new(Mutex::new(false)); let stop_signal_clone = stop_signal.clone(); - + // Start loading spinner in a separate thread let loading_handle = thread::spawn(move || { terminal::show_loading_message("Waiting for authorization...", stop_signal_clone); }); - + // Start the HTTP server to listen for the callback let rt = tokio::runtime::Runtime::new()?; - let result = rt.block_on(async { - start_callback_server(port, auth_code_clone).await - }); - + let result = rt.block_on(async { start_callback_server(port, auth_code_clone).await }); + // Stop the loading spinner *stop_signal.lock().unwrap() = true; loading_handle.join().unwrap(); - + match result { Ok(code) => { - // Exchange the code for a user token let user_token = api::exchange_code_for_token(&base_domain, &code)?; - + // Save the user token to config let mut config = Config::load().expect("Failed to load config"); - config.set_token(user_token).expect("Failed to save user token"); + config + .set_token(user_token) + .expect("Failed to save user token"); config.set_url(base_domain).expect("Failed to save URL"); - + println!("\r🎉 Successfully authenticated to Corgea!"); println!("You can now use other Corgea CLI commands."); - + Ok(()) } Err(e) => { @@ -95,7 +99,7 @@ fn find_available_port(start_port: u16) -> Result Result Result> { let addr = format!("127.0.0.1:{}", port); let listener = match TcpListener::bind(&addr).await { - Ok(listener) => { - listener - } + Ok(listener) => listener, Err(e) => { return Err(format!("Failed to bind to {}: {}", addr, e).into()); } }; - + loop { tokio::select! { accept_result = listener.accept() => { @@ -175,17 +177,17 @@ async fn handle_callback( auth_code: Arc>>, ) -> Result>, hyper::Error> { let uri = req.uri(); - + // Parse query parameters if let Some(query) = uri.query() { let params = parse_query_params(query); - + if let Some(code) = params.get("code") { // Store the authorization code if let Ok(mut code_guard) = auth_code.lock() { *code_guard = Some(code.clone()); } - + // Return success page let success_html = r#" @@ -357,20 +359,20 @@ async fn handle_callback( "#; - + return Ok(Response::builder() .status(StatusCode::OK) .header("Content-Type", "text/html") .body(Full::new(Bytes::from(success_html))) .unwrap()); } - + if let Some(error) = params.get("error") { let default_error = "Unknown error occurred".to_string(); - let error_description = params.get("error_description") - .unwrap_or(&default_error); - - let error_html = format!(r#" + let error_description = params.get("error_description").unwrap_or(&default_error); + + let error_html = format!( + r#" @@ -432,8 +434,10 @@ async fn handle_callback( - "#, error, error_description); - + "#, + error, error_description + ); + return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) .header("Content-Type", "text/html") @@ -441,7 +445,7 @@ async fn handle_callback( .unwrap()); } } - + // Default response for other requests let response_html = r#" @@ -500,7 +504,7 @@ async fn handle_callback( "#; - + Ok(Response::builder() .status(StatusCode::OK) .header("Content-Type", "text/html") @@ -514,20 +518,16 @@ fn parse_query_params(query: &str) -> HashMap { .filter_map(|param| { let mut parts = param.splitn(2, '='); match (parts.next(), parts.next()) { - (Some(key), Some(value)) => { - Some(( - urlencoding::decode(key).ok()?.into_owned(), - urlencoding::decode(value).ok()?.into_owned(), - )) - } + (Some(key), Some(value)) => Some(( + urlencoding::decode(key).ok()?.into_owned(), + urlencoding::decode(value).ok()?.into_owned(), + )), _ => None, } }) .collect() } - - #[cfg(test)] mod tests { use super::*; @@ -541,7 +541,10 @@ mod tests { fn reserve_ephemeral_port() -> u16 { let listener = StdTcpListener::bind("127.0.0.1:0").expect("failed to bind ephemeral port"); - listener.local_addr().expect("failed to get local addr").port() + listener + .local_addr() + .expect("failed to get local addr") + .port() } fn spawn_callback_server( @@ -604,7 +607,10 @@ mod tests { let params = parse_query_params("code=a%20b&error_description=needs%2Blogin"); assert_eq!(params.get("code"), Some(&"a b".to_string())); - assert_eq!(params.get("error_description"), Some(&"needs+login".to_string())); + assert_eq!( + params.get("error_description"), + Some(&"needs+login".to_string()) + ); } #[test] diff --git a/src/cicd.rs b/src/cicd.rs index 7743784..40e075e 100644 --- a/src/cicd.rs +++ b/src/cicd.rs @@ -1,20 +1,19 @@ - pub fn running_in_ci() -> bool { // this will need to be updated to include other CI systems std::env::var("CI").is_ok() && std::env::var("GITHUB_ACTIONS").is_ok() } pub fn which_ci() -> String { - return if std::env::var("GITHUB_ACTIONS").is_ok() { + if std::env::var("GITHUB_ACTIONS").is_ok() { "github".to_string() } else { "unknown".to_string() } } - pub fn get_github_env_vars() -> std::collections::HashMap { - let mut github_env_vars: std::collections::HashMap = std::collections::HashMap::new(); + let mut github_env_vars: std::collections::HashMap = + std::collections::HashMap::new(); for (key, value) in std::env::vars() { if key.starts_with("GITHUB_") { diff --git a/src/config.rs b/src/config.rs index 8976c61..257a483 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,6 @@ -use dirs; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::{env, fs, io}; -use toml; #[derive(Serialize, Deserialize, Clone)] pub struct Config { @@ -13,10 +11,8 @@ pub struct Config { impl Config { fn config_path() -> io::Result { - let mut dir_path = dirs::home_dir().ok_or(io::Error::new( - io::ErrorKind::Other, - "Unable to get home directory", - ))?; + let mut dir_path = + dirs::home_dir().ok_or(io::Error::other("Unable to get home directory"))?; dir_path.push(".corgea"); @@ -95,13 +91,13 @@ impl Config { return corgea_token; } - return self.token.clone(); + self.token.clone() } pub fn get_debug(&self) -> i8 { if let Ok(corgea_debug) = env::var("CORGEA_DEBUG") { return corgea_debug.parse::().unwrap_or(0); } - return self.debug; + self.debug } } diff --git a/src/inspect.rs b/src/inspect.rs index 0933d0c..89fe21e 100644 --- a/src/inspect.rs +++ b/src/inspect.rs @@ -1,16 +1,15 @@ -use crate::utils; use crate::config::Config; -use std::time::SystemTime; use crate::scanners; +use crate::utils; +use std::time::SystemTime; pub fn run( - config: &Config, - issues: &bool, - json: &bool, - summary: &bool, - fix_explanation: &bool, - fix_diff: &bool, + config: &Config, + issues: &bool, + json: &bool, + summary: &bool, + fix_explanation: &bool, + fix_diff: &bool, id: &String, - ) { fn print_section(title: &str, value: impl ToString) { println!("{:<15}: {}", title, value.to_string()); @@ -22,7 +21,10 @@ pub fn run( let issue_details = match utils::api::get_issue(&config.get_url(), id) { Ok(issue) => issue, Err(e) => { - eprintln!("Failed to fetch issue details for issue ID {} with error:\n{}", id, e); + eprintln!( + "Failed to fetch issue details for issue ID {} with error:\n{}", + id, e + ); if e.to_string().contains("404") { println!("If you're trying to inspect a scan make sure to remove the --issue argument"); } @@ -38,33 +40,45 @@ pub fn run( print_section("Urgency", &issue_details.issue.urgency); print_section("Category", &issue_details.issue.classification.name); print_section("File Path", &issue_details.issue.location.file.path); - print_section("Line Num", issue_details.issue.location.line_number.to_string()); - print_section("Status", utils::generic::get_status(&issue_details.issue.status)); + print_section( + "Line Num", + issue_details.issue.location.line_number.to_string(), + ); + print_section( + "Status", + utils::generic::get_status(&issue_details.issue.status), + ); } if let Some(ref details) = issue_details.issue.details { if let Some(ref explanation) = details.explanation { if *summary || show_everything { - println!("Explanation:\n\n{}\n-------------------------", utils::terminal::format_code(explanation)) + println!( + "Explanation:\n\n{}\n-------------------------", + utils::terminal::format_code(explanation) + ) } } - } + } if let Some(auto_fix_suggestion) = issue_details.issue.auto_fix_suggestion { if *fix_explanation || show_everything { if show_everything { - utils::terminal::prompt_to_continue_or_exit(Some("\nTo continue to viewing the fix explanation please press enter, otherwise Ctrl+C to exit.\n".into())); + utils::terminal::prompt_to_continue_or_exit(Some("\nTo continue to viewing the fix explanation please press enter, otherwise Ctrl+C to exit.\n")); } if let Some(ref patch) = &auto_fix_suggestion.patch { utils::terminal::print_with_pagination(&format!( - "Fix Explanation:\n\n{}\n-------------------------", utils::terminal::format_code(&patch.explanation) + "Fix Explanation:\n\n{}\n-------------------------", + utils::terminal::format_code(&patch.explanation) )); } } - if *fix_diff || show_everything { + if *fix_diff || show_everything { if show_everything { - utils::terminal::prompt_to_continue_or_exit(Some("\nTo continue to viewing the diff of the fix please press enter, otherwise Ctrl+C to exit.\n".into())); + utils::terminal::prompt_to_continue_or_exit(Some("\nTo continue to viewing the diff of the fix please press enter, otherwise Ctrl+C to exit.\n")); } if let Some(ref patch) = &auto_fix_suggestion.patch { - utils::terminal::print_with_pagination(&utils::terminal::format_diff(&patch.diff)); + utils::terminal::print_with_pagination(&utils::terminal::format_diff( + &patch.diff, + )); } } } @@ -74,7 +88,9 @@ pub fn run( Err(e) => { eprintln!("Failed to fetch scan details for scan ID {}: {}", id, e); if e.to_string().contains("404") { - println!("If you're trying to inspect an issues make sure to pass --issue argument"); + println!( + "If you're trying to inspect an issues make sure to pass --issue argument" + ); } std::process::exit(1); } @@ -90,21 +106,21 @@ pub fn run( print_section("Status", scan_details.status); print_section("Project", &scan_details.project); print_section("Engine", &scan_details.engine); - let created_at = chrono::DateTime::::from(SystemTime::now()).format("%Y-%m-%d %H:%M:%S").to_string(); + let created_at = chrono::DateTime::::from(SystemTime::now()) + .format("%Y-%m-%d %H:%M:%S") + .to_string(); print_section("Created At", &created_at); - match scanners::blast::fetch_and_group_scan_issues(&config.get_url(), &scan_details.project) { - Ok(counts) => { - let total_issues = counts.values().sum::(); - let order = vec!["CR", "HI", "ME", "LO"]; - for urgency in order { - if let Some(count) = counts.get(urgency) { - print_section(&format!("{} Issues", urgency), &count.to_string()); - } + if let Ok(counts) = + scanners::blast::fetch_and_group_scan_issues(&config.get_url(), &scan_details.project) + { + let total_issues = counts.values().sum::(); + let order = vec!["CR", "HI", "ME", "LO"]; + for urgency in order { + if let Some(count) = counts.get(urgency) { + print_section(&format!("{} Issues", urgency), count.to_string()); } - print_section("Total Issues", &total_issues); - }, - Err(_) => { } + } + print_section("Total Issues", total_issues); }; - } } diff --git a/src/list.rs b/src/list.rs index afacc31..571559b 100644 --- a/src/list.rs +++ b/src/list.rs @@ -1,17 +1,31 @@ -use crate::utils; use crate::config::Config; -use std::path::Path; -use serde_json::json; use crate::log::debug; +use crate::utils; +use serde_json::json; +use std::path::Path; -pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: &Option, page_size: &Option, scan_id: &Option) { - let project_name = utils::generic::get_current_working_directory().unwrap_or("unknown".to_string()); - println!(""); +pub fn run( + config: &Config, + issues: &bool, + sca_issues: &bool, + json: &bool, + page: &Option, + page_size: &Option, + scan_id: &Option, +) { + let project_name = + utils::generic::get_current_working_directory().unwrap_or("unknown".to_string()); + println!(); if *sca_issues { - let sca_issues_response = match utils::api::get_sca_issues(&config.get_url(), Some((*page).unwrap_or(1)), *page_size, scan_id.clone()) { + let sca_issues_response = match utils::api::get_sca_issues( + &config.get_url(), + Some((*page).unwrap_or(1)), + *page_size, + scan_id.clone(), + ) { Ok(response) => response, Err(e) => { - debug(&format!("Error Sending Request: {}", e.to_string())); + debug(&format!("Error Sending Request: {}", e)); if e.to_string().contains("404") { if scan_id.is_some() { eprintln!("Scan with ID '{}' doesn't exist or has no SCA issues. Please run 'corgea scan' to create a new scan for this project.", scan_id.as_ref().unwrap()); @@ -42,18 +56,16 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: return; } - let mut table = vec![ - vec![ - "Issue ID".to_string(), - "Package".to_string(), - "Version".to_string(), - "Fix Version".to_string(), - "Severity".to_string(), - "CVE".to_string(), - "Ecosystem".to_string(), - "File Path".to_string(), - ], - ]; + let mut table = vec![vec![ + "Issue ID".to_string(), + "Package".to_string(), + "Version".to_string(), + "Fix Version".to_string(), + "Severity".to_string(), + "CVE".to_string(), + "Ecosystem".to_string(), + "File Path".to_string(), + ]]; for issue in &sca_issues_response.issues { let path = Path::new(&issue.location.path); @@ -77,7 +89,11 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: issue.id.clone(), issue.package.name.clone(), issue.package.version.clone(), - issue.package.fix_version.clone().unwrap_or("N/A".to_string()), + issue + .package + .fix_version + .clone() + .unwrap_or("N/A".to_string()), issue.severity.clone().unwrap_or("N/A".to_string()), issue.cve.clone().unwrap_or("N/A".to_string()), issue.package.ecosystem.clone(), @@ -85,12 +101,22 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: ]); } - utils::terminal::print_table(table, Some(sca_issues_response.page), Some(sca_issues_response.total_pages)); + utils::terminal::print_table( + table, + Some(sca_issues_response.page), + Some(sca_issues_response.total_pages), + ); } else if *issues { - let issues_response = match utils::api::get_scan_issues(&config.get_url(), &project_name, Some((*page).unwrap_or(1)), *page_size, scan_id.clone()) { + let issues_response = match utils::api::get_scan_issues( + &config.get_url(), + &project_name, + Some((*page).unwrap_or(1)), + *page_size, + scan_id.clone(), + ) { Ok(response) => response, Err(e) => { - debug(&format!("Error Sending Request: {}", e.to_string())); + debug(&format!("Error Sending Request: {}", e)); if e.to_string().contains("404") { if scan_id.is_some() { eprintln!("Scan with ID '{}' doesn't exist. Please run 'corgea scan' to create a new scan for this project.", scan_id.as_ref().unwrap()); @@ -110,12 +136,17 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: } }; let mut render_blocking_rules = false; - let mut blocking_rules: std::collections::HashMap = std::collections::HashMap::new(); + let mut blocking_rules: std::collections::HashMap = + std::collections::HashMap::new(); if scan_id.is_some() { let mut page: u32 = 1; loop { - match utils::api::check_blocking_rules(&config.get_url(), scan_id.as_ref().unwrap(), Some(page)) { + match utils::api::check_blocking_rules( + &config.get_url(), + scan_id.as_ref().unwrap(), + Some(page), + ) { Ok(rules) => { if rules.block { render_blocking_rules = true; @@ -138,7 +169,6 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: } } - if *json { let mut json = serde_json::json!({ "page": issues_response.page, @@ -146,30 +176,31 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: "results": &issues_response.issues }); if render_blocking_rules { - json["results"] = serde_json::json!( - issues_response.issues.unwrap_or_default().iter().map(|issue| { - serde_json::json!( - utils::api::IssueWithBlockingRules { - id: issue.id.clone(), - scan_id: issue.scan_id.clone(), - status: issue.status.clone(), - urgency: issue.urgency.clone(), - created_at: issue.created_at.clone(), - classification: issue.classification.clone(), - location: issue.location.clone(), - details: issue.details.clone(), - auto_triage: issue.auto_triage.clone(), - auto_fix_suggestion: issue.auto_fix_suggestion.clone(), - blocked: blocking_rules.contains_key(&issue.id), - blocking_rules: if blocking_rules.contains_key(&issue.id) { - Some(vec![blocking_rules.get(&issue.id).unwrap().clone()]) - } else { - None - } + json["results"] = serde_json::json!(issues_response + .issues + .unwrap_or_default() + .iter() + .map(|issue| { + serde_json::json!(utils::api::IssueWithBlockingRules { + id: issue.id.clone(), + scan_id: issue.scan_id.clone(), + status: issue.status.clone(), + urgency: issue.urgency.clone(), + created_at: issue.created_at.clone(), + classification: issue.classification.clone(), + location: issue.location.clone(), + details: issue.details.clone(), + auto_triage: issue.auto_triage.clone(), + auto_fix_suggestion: issue.auto_fix_suggestion.clone(), + blocked: blocking_rules.contains_key(&issue.id), + blocking_rules: if blocking_rules.contains_key(&issue.id) { + Some(vec![blocking_rules.get(&issue.id).unwrap().clone()]) + } else { + None } - ) - }).collect::>() - ); + }) + }) + .collect::>()); } let output = json!(json); println!("{}", serde_json::to_string_pretty(&output).unwrap()); @@ -186,9 +217,7 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: table_header.push("Blocking".to_string()); table_header.push("Rule ID".to_string()); } - let mut table = vec![ - table_header - ]; + let mut table = vec![table_header]; for issue in &issues_response.issues.unwrap_or_default() { let classification_display = issue.classification.id.clone(); @@ -216,23 +245,36 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: issue.location.line_number.to_string(), ]; if render_blocking_rules { - row.push(blocking_rules.get(&issue.id).is_some().to_string()); - row.push(blocking_rules.get(&issue.id).unwrap_or(&"".to_string()).to_string()); + row.push(blocking_rules.contains_key(&issue.id).to_string()); + row.push( + blocking_rules + .get(&issue.id) + .unwrap_or(&"".to_string()) + .to_string(), + ); } table.push(row); } utils::terminal::print_table(table, issues_response.page, issues_response.total_pages); } else { - let (scans, page, total_pages) = match utils::api::query_scan_list(&config.get_url(), Some(&project_name), *page, *page_size) { + let (scans, page, total_pages) = match utils::api::query_scan_list( + &config.get_url(), + Some(&project_name), + *page, + *page_size, + ) { Ok(scans) => { let page = scans.page; let total_pages = scans.total_pages; - let filtered_scans: Vec = scans.scans.unwrap_or_default().into_iter() + let filtered_scans: Vec = scans + .scans + .unwrap_or_default() + .into_iter() .filter(|scan| scan.project == project_name) .collect(); (filtered_scans, page, total_pages) - }, + } Err(e) => { if e.to_string().contains("404") { eprintln!("Project with name '{}' doesn't exist. Please run 'corgea scan' to create a new scan for this project.", project_name); @@ -256,20 +298,18 @@ pub fn run(config: &Config, issues: &bool, sca_issues: &bool, json: &bool, page: println!("{}", serde_json::to_string_pretty(&output).unwrap()); return; } - let mut table = vec![ - vec![ - "Scan ID".to_string(), - "Project".to_string(), - "Status".to_string(), - "Repo".to_string(), - "Branch".to_string(), - ], - ]; + let mut table = vec![vec![ + "Scan ID".to_string(), + "Project".to_string(), + "Status".to_string(), + "Repo".to_string(), + "Branch".to_string(), + ]]; for scan in &scans { let formatted_repo = scan.repo.clone().unwrap_or("N/A".to_string()); let formatted_repo = if formatted_repo != "N/A" { - if let Some(repo_name) = formatted_repo.split('/').last() { + if let Some(repo_name) = formatted_repo.split('/').next_back() { let owner = formatted_repo.split('/').nth(3).unwrap_or("unknown"); let repo_name = repo_name.strip_suffix(".git").unwrap_or(repo_name); format!("{}/{}", owner, repo_name) diff --git a/src/log.rs b/src/log.rs index daf745a..7f193fe 100644 --- a/src/log.rs +++ b/src/log.rs @@ -1,8 +1,8 @@ -use crate::config::Config; +use crate::config::Config; pub fn debug(input: &str) { let config = Config::load().expect("Failed to load config"); if config.get_debug() == 1 { println!("DEBUG: {}\n", input); } -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index 5da00f9..0802e1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,28 +1,28 @@ +mod authorize; +mod cicd; mod config; -mod scan; -mod wait; -mod list; mod inspect; -mod cicd; +mod list; mod log; +mod scan; mod setup_hooks; -mod authorize; +mod wait; mod scanners { - pub mod fortify; pub mod blast; + pub mod fortify; pub mod parsers; } mod utils { - pub mod terminal; - pub mod generic; pub mod api; + pub mod generic; + pub mod terminal; } mod targets; -use std::str::FromStr; -use clap::{Parser, Subcommand, CommandFactory}; +use clap::{CommandFactory, Parser, Subcommand}; use config::Config; use scanners::fortify::parse as fortify_parse; +use std::str::FromStr; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -32,20 +32,26 @@ struct Cli { command: Option, #[arg(required = false)] - args: Vec, + args: Vec, } #[derive(Subcommand, Debug)] enum Commands { /// Authenticate to Corgea - Login { + Login { #[arg(help = "API token (if not provided, will use OAuth flow)")] token: Option, - #[arg(long, help = "The url of the corgea instance to use. defaults to https://www.corgea.app")] + #[arg( + long, + help = "The url of the corgea instance to use. defaults to https://www.corgea.app" + )] url: Option, - #[arg(long, help = "Scope to use for custom domain (e.g., 'ikea' for ikea.corgea.app). Only used with OAuth flow")] + #[arg( + long, + help = "Scope to use for custom domain (e.g., 'ikea' for ikea.corgea.app). Only used with OAuth flow" + )] scope: Option, }, /// Upload a scan report to Corgea via STDIN or a file @@ -65,13 +71,20 @@ enum Commands { #[arg(default_value = "blast")] scanner: Scanner, - #[arg(long, help = "Fail on (exits with error code 1) a specific severity level . Valid options are CR, HI, ME, LO.")] + #[arg( + long, + help = "Fail on (exits with error code 1) a specific severity level . Valid options are CR, HI, ME, LO." + )] fail_on: Option, #[arg(long, help = "Only scan uncommitted changes.")] only_uncommitted: bool, - #[arg(short, long, help = "Fail on (exits with error code 1) based on blocking rules defined in the web app.")] + #[arg( + short, + long, + help = "Fail on (exits with error code 1) based on blocking rules defined in the web app." + )] fail: bool, #[arg( @@ -88,10 +101,17 @@ enum Commands { )] scan_type: Option, - #[arg(long, help = "Output the result to a file in a specific format. Valid options are json, html, sarif, markdown.")] + #[arg( + long, + help = "Output the result to a file in a specific format. Valid options are json, html, sarif, markdown." + )] out_format: Option, - #[arg(short, long, help = "Output the result to a file. you can use the out_format option to specify the format of the output file.")] + #[arg( + short, + long, + help = "Output the result to a file. you can use the out_format option to specify the format of the output file." + )] out_file: Option, #[arg( @@ -107,16 +127,18 @@ enum Commands { project_name: Option, }, /// Wait for the latest in progress scan - Wait { - scan_id: Option, - }, + Wait { scan_id: Option }, /// List something, by default it lists the scans #[command(alias = "ls")] List { #[arg(short, long, help = "List issues instead of scans")] issues: bool, - #[arg(long, short = 'c', help = "List SCA (Software Composition Analysis) issues instead of regular issues")] + #[arg( + long, + short = 'c', + help = "List SCA (Software Composition Analysis) issues instead of regular issues" + )] sca_issues: bool, #[arg(short, long, help = "Specify the scan id to list issues for.")] @@ -129,7 +151,7 @@ enum Commands { json: bool, #[arg(long, value_parser = clap::value_parser!(u16), help = "Number of items per page")] - page_size: Option + page_size: Option, }, /// Inspect something, by default it will inspect a scan Inspect { @@ -140,20 +162,36 @@ enum Commands { #[arg(long, help = "Output the result in JSON format.")] json: bool, - #[arg(long, short, help = "Display a summary only of the issue in the output (only if --issue is true).")] + #[arg( + long, + short, + help = "Display a summary only of the issue in the output (only if --issue is true)." + )] summary: bool, - #[arg(long, short, help = "Display the fix explanations only in the output (only if --issue is true).")] + #[arg( + long, + short, + help = "Display the fix explanations only in the output (only if --issue is true)." + )] fix: bool, - #[arg(long, short, help = "Display the diff of the fix only in the output (only if --issue is true).")] + #[arg( + long, + short, + help = "Display the diff of the fix only in the output (only if --issue is true)." + )] diff: bool, id: String, }, /// Setup a git hook, currently only pre-commit is supported SetupHooks { - #[arg(long, short, help = "Include default config (scan types are pii, secrets and fail on levels are CR, HI, ME, LO).")] + #[arg( + long, + short, + help = "Include default config (scan types are pii, secrets and fail on levels are CR, HI, ME, LO)." + )] default_config: bool, }, } @@ -181,20 +219,18 @@ impl FromStr for Scanner { fn main() { let cli = Cli::parse(); let mut corgea_config = Config::load().expect("Failed to load config"); - fn verify_token_and_exit_when_fail (config: &Config) { + fn verify_token_and_exit_when_fail(config: &Config) { if config.get_token().is_empty() { eprintln!("No token set.\nPlease run 'corgea login' to authenticate.\nFor more info checkout our docs at Check out our docs at https://docs.corgea.app/install_cli#login-with-the-cli"); std::process::exit(1); } utils::api::set_auth_token(&config.get_token()); match utils::api::verify_token(config.get_url().as_str()) { - Ok(true) => { - return; - } + Ok(true) => {} Ok(false) => { println!("Invalid token provided.\nPlease run 'corgea login' to authenticate.\nFor more info checkout our docs at Check out our docs at https://docs.corgea.app/install_cli#login-with-the-cli"); std::process::exit(1); - }, + } Err(e) => { eprintln!("Error occurred: {}", e); std::process::exit(1); @@ -203,19 +239,34 @@ fn main() { } match &cli.command { Some(Commands::Login { token, url, scope }) => { - let effective_token = token.clone().or_else(|| utils::generic::get_env_var_if_exists("CORGEA_TOKEN")); - + let effective_token = token + .clone() + .or_else(|| utils::generic::get_env_var_if_exists("CORGEA_TOKEN")); + match effective_token { Some(token_value) => { - let token_source = if token.is_some() { "parameter" } else { "CORGEA_TOKEN environment variable" }; + let token_source = if token.is_some() { + "parameter" + } else { + "CORGEA_TOKEN environment variable" + }; utils::api::set_auth_token(&token_value); - match utils::api::verify_token(url.as_deref().unwrap_or(corgea_config.get_url().as_str())) { + match utils::api::verify_token( + url.as_deref().unwrap_or(corgea_config.get_url().as_str()), + ) { Ok(true) => { - corgea_config.set_token(token_value.clone()).expect("Failed to set token"); + corgea_config + .set_token(token_value.clone()) + .expect("Failed to set token"); if let Some(url) = url { - corgea_config.set_url(url.clone()).expect("Failed to set url"); + corgea_config + .set_url(url.clone()) + .expect("Failed to set url"); } - println!("Successfully authenticated to Corgea using token from {}.", token_source) + println!( + "Successfully authenticated to Corgea using token from {}.", + token_source + ) } Ok(false) => println!("Invalid token provided from {}.", token_source), Err(e) => { @@ -225,7 +276,7 @@ fn main() { } eprintln!("Error occurred: {}", e); std::process::exit(1); - }, + } } } // No token available - use OAuth flow @@ -233,9 +284,9 @@ fn main() { if url.is_some() && scope.is_some() { eprintln!("Warning: --url option is ignored when using OAuth flow with --scope. The scope determines the domain."); } - + match authorize::run(scope.clone(), url.clone()) { - Ok(()) => {}, + Ok(()) => {} Err(e) => { eprintln!("Authorization failed: {}", e); std::process::exit(1); @@ -244,7 +295,10 @@ fn main() { } } } - Some(Commands::Upload { report, project_name }) => { + Some(Commands::Upload { + report, + project_name, + }) => { verify_token_and_exit_when_fail(&corgea_config); match report { Some(report) => { @@ -259,7 +313,18 @@ fn main() { } } } - Some(Commands::Scan { scanner , fail_on, fail, only_uncommitted, scan_type, policy, out_format, out_file, target, project_name }) => { + Some(Commands::Scan { + scanner, + fail_on, + fail, + only_uncommitted, + scan_type, + policy, + out_format, + out_file, + target, + project_name, + }) => { verify_token_and_exit_when_fail(&corgea_config); if let Some(level) = fail_on { if *scanner != Scanner::Blast { @@ -292,7 +357,9 @@ fn main() { std::process::exit(1); } - if out_file.is_some() && !out_format.is_some() || !out_file.is_some() && out_format.is_some() { + if out_file.is_some() && !out_format.is_some() + || !out_file.is_some() && out_format.is_some() + { eprintln!("out_file and out_format must be used together."); std::process::exit(1); } @@ -342,14 +409,32 @@ fn main() { match scanner { Scanner::Snyk => scan::run_snyk(&corgea_config, project_name.clone()), Scanner::Semgrep => scan::run_semgrep(&corgea_config, project_name.clone()), - Scanner::Blast => scanners::blast::run(&corgea_config, fail_on.clone(), fail, only_uncommitted, scan_type.clone(), policy.clone(), out_format.clone(), out_file.clone(), target.clone(), project_name.clone()) + Scanner::Blast => scanners::blast::run( + &corgea_config, + fail_on.clone(), + fail, + only_uncommitted, + scan_type.clone(), + policy.clone(), + out_format.clone(), + out_file.clone(), + target.clone(), + project_name.clone(), + ), } } Some(Commands::Wait { scan_id }) => { verify_token_and_exit_when_fail(&corgea_config); wait::run(&corgea_config, scan_id.clone(), None); } - Some(Commands::List { issues , json, page, page_size, scan_id, sca_issues}) => { + Some(Commands::List { + issues, + json, + page, + page_size, + scan_id, + sca_issues, + }) => { verify_token_and_exit_when_fail(&corgea_config); if *issues && *sca_issues { eprintln!("Cannot use both --issues and --sca-issues at the same time."); @@ -359,9 +444,24 @@ fn main() { println!("scan_id option is only supported for issues list command."); std::process::exit(1); } - list::run(&corgea_config, issues, sca_issues, json, page, page_size, scan_id); + list::run( + &corgea_config, + issues, + sca_issues, + json, + page, + page_size, + scan_id, + ); } - Some(Commands::Inspect { issue, json, id, summary, fix, diff }) => { + Some(Commands::Inspect { + issue, + json, + id, + summary, + fix, + diff, + }) => { verify_token_and_exit_when_fail(&corgea_config); inspect::run(&corgea_config, issue, json, summary, fix, diff, id) } diff --git a/src/scan.rs b/src/scan.rs index 184dbdd..d657bc5 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -1,14 +1,14 @@ +use crate::cicd::*; +use crate::log::debug; +use crate::scanners::parsers::ScanParserFactory; +use crate::{utils, Config}; +use reqwest::header; +use serde_json::Value; use std::collections::HashSet; use std::io::{self, Read}; -use crate::{utils, Config}; -use uuid::Uuid; use std::path::Path; use std::process::Command; -use crate::cicd::{*}; -use crate::log::debug; -use reqwest::header; -use crate::scanners::parsers::ScanParserFactory; -use serde_json::Value; +use uuid::Uuid; pub fn run_command(base_cmd: &String, mut command: Command) -> String { match which::which(base_cmd) { @@ -30,7 +30,7 @@ pub fn run_command(base_cmd: &String, mut command: Command) -> String { std::process::exit(1); } - return stdout; + stdout } else { let stderr = String::from_utf8(output.stderr).expect("Failed to parse stderr"); let stdout = String::from_utf8(output.stdout).expect("Failed to parse stdout"); @@ -55,7 +55,11 @@ pub fn run_semgrep(config: &Config, project_name: Option) { println!("Scanning with semgrep..."); let base_command = "semgrep"; let mut command = std::process::Command::new(base_command); - command.arg("scan").arg("--config").arg("auto").arg("--json"); + command + .arg("scan") + .arg("--config") + .arg("auto") + .arg("--json"); println!("Running \"semgrep scan --config auto --json\""); @@ -100,7 +104,12 @@ pub fn read_file_report(config: &Config, file_path: &str, project_name: Option) -> Option { +pub fn parse_scan( + config: &Config, + input: String, + save_to_file: bool, + project_name: Option, +) -> Option { debug("Parsing the scan report"); // Remove BOM (Byte Order Mark) if present @@ -115,7 +124,14 @@ pub fn parse_scan(config: &Config, input: String, save_to_file: bool, project_na std::process::exit(0); } - return upload_scan(config, parse_result.paths, parse_result.scanner, cleaned_input.to_string(), save_to_file, project_name); + upload_scan( + config, + parse_result.paths, + parse_result.scanner, + cleaned_input.to_string(), + save_to_file, + project_name, + ) } Err(error_message) => { @@ -125,7 +141,14 @@ pub fn parse_scan(config: &Config, input: String, save_to_file: bool, project_na } } -pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: String, save_to_file: bool, project_name: Option) -> Option { +pub fn upload_scan( + config: &Config, + paths: Vec, + scanner: String, + input: String, + save_to_file: bool, + project_name: Option, +) -> Option { let in_ci = running_in_ci(); let ci_platform = which_ci(); let github_env_vars = get_github_env_vars(); @@ -133,30 +156,38 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: let run_id = Uuid::new_v4().to_string(); let base_url = config.get_url(); let api_base = "/api/v1"; - let project; - if in_ci { + let project = if in_ci { debug("Running in CI"); - project = format!("{}-{}", - github_env_vars.get("GITHUB_REPOSITORY").expect("Failed to get GITHUB_REPOSITORY").to_string(), - github_env_vars.get("GITHUB_PR").expect("Failed to get GITHUB_REPOSITORY").to_string()) + format!( + "{}-{}", + github_env_vars + .get("GITHUB_REPOSITORY") + .expect("Failed to get GITHUB_REPOSITORY"), + github_env_vars + .get("GITHUB_PR") + .expect("Failed to get GITHUB_REPOSITORY") + ) } else { - project = utils::generic::determine_project_name(project_name.as_deref()); - } + utils::generic::determine_project_name(project_name.as_deref()) + }; let repo_data = std::env::var("REPO_DATA").unwrap_or_else(|_| "".to_string()); let scan_upload_url = if repo_data.is_empty() { format!( - "{}{}/scan-upload?engine={}&run_id={}&project={}&ci={}&ci_platform={}", base_url, api_base, scanner, run_id, project, in_ci, ci_platform + "{}{}/scan-upload?engine={}&run_id={}&project={}&ci={}&ci_platform={}", + base_url, api_base, scanner, run_id, project, in_ci, ci_platform ) } else { format!( - "{}{}/scan-upload?engine={}&run_id={}&project={}&ci={}&ci_platform={}&repo_data={}", base_url, api_base, scanner, run_id, project, in_ci, ci_platform, repo_data + "{}{}/scan-upload?engine={}&run_id={}&project={}&ci={}&ci_platform={}&repo_data={}", + base_url, api_base, scanner, run_id, project, in_ci, ci_platform, repo_data ) }; let git_config_upload_url = format!( - "{}{}/git-config-upload?run_id={}", base_url, api_base, run_id + "{}{}/git-config-upload?run_id={}", + base_url, api_base, run_id ); let client = utils::api::http_client(); @@ -168,7 +199,10 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: for path in &paths { if !Path::new(&path).exists() { - eprintln!("Required file {} not found which is required for the scan, exiting.", path); + eprintln!( + "Required file {} not found which is required for the scan, exiting.", + path + ); std::process::exit(1); } @@ -177,7 +211,8 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: } let src_upload_url = format!( - "{}{}/code-upload?run_id={}&path={}", base_url, api_base, run_id, path + "{}{}/code-upload?run_id={}&path={}", + base_url, api_base, run_id, path ); debug(&format!("Uploading file: {}", path)); let fp = Path::new(&path); @@ -191,16 +226,19 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: .expect("Failed to read file"); debug(&format!("POST: {}", src_upload_url)); - let res = client.post(&src_upload_url) - .multipart(form) - .send(); + let res = client.post(&src_upload_url).multipart(form).send(); match res { Ok(response) => { if !response.status().is_success() { let status = response.status(); - let body = response.text().unwrap_or_else(|_| "Unable to read response body".to_string()); - debug(&format!("Code upload failed with status: {}. Response body: {}", status, body)); + let body = response + .text() + .unwrap_or_else(|_| "Unable to read response body".to_string()); + debug(&format!( + "Code upload failed with status: {}. Response body: {}", + status, body + )); eprintln!("Failed to upload file {} {}... retrying", status, path); std::thread::sleep(std::time::Duration::from_secs(1)); attempts += 1; @@ -219,7 +257,10 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: if attempts == 3 && !success { upload_error_count += 1; - eprintln!("Failed to upload file: {} after 3 attempts. skipping...", path); + eprintln!( + "Failed to upload file: {} after 3 attempts. skipping...", + path + ); } } @@ -235,30 +276,34 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: let input_size = input_bytes.len(); let max_upload_size = 50 * 1024 * 1024; // 50mb let chunk_size = match std::env::var("DEBUG_CORGEA_OVERRIDE_REPORT_CHUNK_SIZE") { - Ok(val) => { - match val.parse::() { - Ok(mb) if mb > 0 => { - debug(&format!("Overriding report chunk size to {} MB", mb)); - mb * 1024 * 1024 - } - _ => { - eprintln!("Invalid DEBUG_CORGEA_OVERRIDE_REPORT_CHUNK_SIZE value '{}', using default 1 MB", val); - 1024 * 1024 - } + Ok(val) => match val.parse::() { + Ok(mb) if mb > 0 => { + debug(&format!("Overriding report chunk size to {} MB", mb)); + mb * 1024 * 1024 } - } + _ => { + eprintln!("Invalid DEBUG_CORGEA_OVERRIDE_REPORT_CHUNK_SIZE value '{}', using default 1 MB", val); + 1024 * 1024 + } + }, Err(_) => 1024 * 1024, // default 1mb }; let is_chunked = input_size > max_upload_size; let res = if is_chunked { - let total_chunks = (input_size + chunk_size - 1) / chunk_size; + let total_chunks = input_size.div_ceil(chunk_size); debug(&format!("Uploading scan in {} chunks", total_chunks)); let mut offset = 0usize; let mut last_response = None; for (index, chunk) in input_bytes.chunks(chunk_size).enumerate() { - debug(&format!("POST: {} (chunk {}/{})", scan_upload_url, index + 1, total_chunks)); - let response = client.post(&scan_upload_url) + debug(&format!( + "POST: {} (chunk {}/{})", + scan_upload_url, + index + 1, + total_chunks + )); + let response = client + .post(&scan_upload_url) .header(header::CONTENT_TYPE, "application/json") .header("Upload-Offset", offset.to_string()) .header("Upload-Length", input_size.to_string()) @@ -295,7 +340,7 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: false } } - }, + } Err(_) => true, }; last_response = Some(response); @@ -308,7 +353,8 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: last_response.expect("Failed to upload scan.") } else { debug(&format!("POST: {}", scan_upload_url)); - client.post(&scan_upload_url) + client + .post(&scan_upload_url) .header(header::CONTENT_TYPE, "application/json") .body(input.clone()) .send() @@ -365,8 +411,13 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: } else { upload_failed = true; let status = response.status(); - let body = response.text().unwrap_or_else(|_| "Unable to read response body".to_string()); - debug(&format!("Scan upload failed with status: {}. Response body: {}", status, body)); + let body = response + .text() + .unwrap_or_else(|_| "Unable to read response body".to_string()); + debug(&format!( + "Scan upload failed with status: {}. Response body: {}", + status, body + )); eprintln!("Failed to upload scan: {}", status); } } @@ -376,7 +427,6 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: } } - let git_config_path = Path::new(".git/config"); if git_config_path.exists() { @@ -386,9 +436,7 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: .expect("Failed to read file"); debug(&format!("POST: {}", git_config_upload_url)); - let res = client.post(&git_config_upload_url) - .multipart(form) - .send(); + let res = client.post(&git_config_upload_url).multipart(form).send(); match res { Ok(response) => { @@ -404,7 +452,8 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: if in_ci { let ci_data_upload_url = format!( - "{}{}/ci-data-upload?run_id={}&platform={}", base_url, api_base, run_id, ci_platform + "{}{}/ci-data-upload?run_id={}&platform={}", + base_url, api_base, run_id, ci_platform ); let mut github_env_vars_json = serde_json::Map::new(); @@ -421,7 +470,8 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: }; debug(&format!("POST: {}", ci_data_upload_url)); - let _res = client.post(ci_data_upload_url) + let _res = client + .post(ci_data_upload_url) .header(header::CONTENT_TYPE, "application/json") .body(github_env_vars_json_string) .send(); @@ -433,7 +483,7 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: match std::fs::write(&file_path, input.clone()) { Ok(_) => println!("Successfully saved scan to {}", file_path.display()), - Err(e) => eprintln!("Failed to save scan to {}: {}", file_path.display(), e) + Err(e) => eprintln!("Failed to save scan to {}: {}", file_path.display(), e), } } @@ -441,13 +491,22 @@ pub fn upload_scan(config: &Config, paths: Vec, scanner: String, input: std::process::exit(1); } - println!("Successfully scanned using {} and uploaded to Corgea.", scanner); + println!( + "Successfully scanned using {} and uploaded to Corgea.", + scanner + ); if upload_error_count > 0 { - println!("Failed to upload {} files, you may not see all fixes in Corgea.", upload_error_count); + println!( + "Failed to upload {} files, you may not see all fixes in Corgea.", + upload_error_count + ); } println!("Go to {base_url} to see results."); - sast_scan_id.map(|scan_id| ScanUploadResult { scan_id, project_id }) + sast_scan_id.map(|scan_id| ScanUploadResult { + scan_id, + project_id, + }) } diff --git a/src/scanners/blast.rs b/src/scanners/blast.rs index d530ed8..e712ddb 100644 --- a/src/scanners/blast.rs +++ b/src/scanners/blast.rs @@ -1,20 +1,19 @@ -use crate::utils; use crate::config::Config; use crate::targets; +use crate::utils; use std::collections::HashMap; -use std::sync::{Arc, Mutex}; -use std::error::Error; -use std::thread; use std::env; +use std::error::Error; use std::fs; +use std::sync::{Arc, Mutex}; +use std::thread; use uuid::Uuid; - - +#[allow(clippy::too_many_arguments)] pub fn run( - config: &Config, - fail_on: Option, - fail: &bool, + config: &Config, + fail_on: Option, + fail: &bool, only_uncommitted: &bool, scan_type: Option, policy: Option, @@ -34,37 +33,33 @@ pub fn run( Ok(false) => { eprintln!("This is not a git repository. Without a git repository Corgea CLI can't determine which files have been modified or added thus only a full scan is possible."); std::process::exit(1); - }, + } Err(e) => { eprintln!("Error checking git repository information: {}. Without a git repository Corgea CLI can't determine which files have been modified or added thus only a full scan is possible.", e); std::process::exit(1); - }, + } Ok(true) => { // Continue with the git repo logic } } } - println!( - "\nScanning with BLAST 🚀🚀🚀" - ); + println!("\nScanning with BLAST 🚀🚀🚀"); if let Some(scan_type) = &scan_type { println!("Running Scan Type: {}", scan_type); } if let Some(policy) = &policy { - println!("Including only specified policies for policy scan: {}", policy); + println!( + "Including only specified policies for policy scan: {}", + policy + ); } println!("\n\n"); let temp_dir = env::temp_dir().join(format!("corgea/tmp/{}", Uuid::new_v4())); fs::create_dir_all(&temp_dir).expect("Failed to create temp directory"); let project_name = utils::generic::determine_project_name(project_name.as_deref()); let zip_path = format!("{}/{}.zip", temp_dir.display(), project_name); - let repo_info = match utils::generic::get_repo_info("./") { - Ok(info) => info, - Err(_) => { - None - } - }; + let repo_info = utils::generic::get_repo_info("./").unwrap_or_default(); match utils::generic::create_path_if_not_exists(&temp_dir) { Ok(_) => (), Err(e) => { @@ -79,7 +74,10 @@ pub fn run( let stop_signal = Arc::new(Mutex::new(false)); let stop_signal_clone = Arc::clone(&stop_signal); let packaging_thread = thread::spawn(move || { - utils::terminal::show_loading_message("Packaging your project... ([T]s)", stop_signal_clone); + utils::terminal::show_loading_message( + "Packaging your project... ([T]s)", + stop_signal_clone, + ); }); let target_str: Option<&str> = if *only_uncommitted { @@ -94,7 +92,10 @@ pub fn run( if result.files.is_empty() { *stop_signal.lock().unwrap() = true; let _ = packaging_thread.join(); - print!("\r{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset)); + print!( + "\r{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset) + ); eprintln!("\n\nError: target resolved to zero files.\n"); eprintln!("Target value: {}\n", target_value); eprintln!("Segment results:"); @@ -102,7 +103,10 @@ pub fn run( if let Some(ref error) = segment_result.error { eprintln!(" {}: ERROR - {}", segment_result.segment, error); } else { - eprintln!(" {}: {} matches", segment_result.segment, segment_result.matches); + eprintln!( + " {}: {} matches", + segment_result.segment, segment_result.matches + ); } } eprintln!("\nPlease check your target specification and try again.\n"); @@ -113,7 +117,9 @@ pub fn run( if *only_uncommitted { println!("\rFiles to be submitted for partial scan:\n"); for (index, file) in result.files.iter().enumerate() { - if let Ok(relative) = file.strip_prefix(std::env::current_dir().unwrap_or_default()) { + if let Ok(relative) = + file.strip_prefix(std::env::current_dir().unwrap_or_default()) + { println!("{}: {}", index + 1, relative.display()); } else { println!("{}: {}", index + 1, file.display()); @@ -122,10 +128,12 @@ pub fn run( println!(); } else { println!("Scanning {} files (target mode)", file_count); - + let display_count = std::cmp::min(20, file_count); for file in result.files.iter().take(display_count) { - if let Ok(relative) = file.strip_prefix(std::env::current_dir().unwrap_or_default()) { + if let Ok(relative) = + file.strip_prefix(std::env::current_dir().unwrap_or_default()) + { println!(" {}", relative.display()); } else { println!(" {}", file.display()); @@ -140,7 +148,10 @@ pub fn run( Err(e) => { *stop_signal.lock().unwrap() = true; let _ = packaging_thread.join(); - print!("\r{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset)); + print!( + "\r{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset) + ); eprintln!("\n\nError resolving targets: {}\n", e); std::process::exit(1); } @@ -152,23 +163,27 @@ pub fn run( if added_files.is_empty() { *stop_signal.lock().unwrap() = true; let _ = packaging_thread.join(); - print!("\r{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset)); + print!( + "\r{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset) + ); if *only_uncommitted { eprintln!( "\n\nOops! It seems there are no scannable uncommitted changes in your project.\nYou may have uncommitted changes, but none match the types of files we can scan.\n\n" ); } else { - eprintln!( - "\n\nOops! No valid files found to scan after filtering.\n\n" - ); + eprintln!("\n\nOops! No valid files found to scan after filtering.\n\n"); } std::process::exit(1); } - }, + } Err(e) => { *stop_signal.lock().unwrap() = true; let _ = packaging_thread.join(); - print!("\r{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset)); + print!( + "\r{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset) + ); eprintln!( "\n\nUh-oh! We couldn't package your project at '{}'.\nThis might be due to insufficient permissions, invalid file paths, or a file system error.\nPlease check the directory and try again.\nError details:\n{}\n\n", zip_path, e @@ -178,9 +193,19 @@ pub fn run( } *stop_signal.lock().unwrap() = true; let _ = packaging_thread.join(); - print!("\r{}Project packaged successfully.\n", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Green)); + print!( + "\r{}Project packaged successfully.\n", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Green) + ); println!("\n\nSubmitting scan to Corgea:"); - let upload_result = match utils::api::upload_zip(&zip_path, &config.get_url(), &project_name, repo_info, scan_type, policy) { + let upload_result = match utils::api::upload_zip( + &zip_path, + &config.get_url(), + &project_name, + repo_info, + scan_type, + policy, + ) { Ok(result) => result, Err(e) => { eprintln!("\n\nOh no! We encountered an issue while uploading the zip file '{}' to the server.\nPlease ensure that: @@ -197,13 +222,18 @@ pub fn run( e ); std::process::exit(1); - }, + } }; let scan_id = upload_result.scan_id; let scan_url = match &upload_result.project_id { Some(pid) => format!("{}/project/{}/?scan_id={}", config.get_url(), pid, scan_id), - None => format!("{}/project/{}?scan_id={}", config.get_url(), project_name, scan_id), + None => format!( + "{}/project/{}?scan_id={}", + config.get_url(), + project_name, + scan_id + ), }; let _ = utils::generic::delete_directory(&temp_dir); @@ -222,7 +252,10 @@ pub fn run( let stop_signal = Arc::new(Mutex::new(false)); let stop_signal_clone = Arc::clone(&stop_signal); let results_thread = thread::spawn(move || { - utils::terminal::show_loading_message("Collecting scan results... ([T]s)", stop_signal_clone); + utils::terminal::show_loading_message( + "Collecting scan results... ([T]s)", + stop_signal_clone, + ); }); let classifications = match report_scan_status(&config.get_url(), &project_name) { @@ -234,7 +267,7 @@ pub fn run( utils::terminal::set_text_color(&scan_url, utils::terminal::TerminalColor::Green) ); issues_classes - }, + } Err(e) => { *stop_signal.lock().unwrap() = true; let _ = results_thread.join(); @@ -247,7 +280,10 @@ pub fn run( - Error details: {}\n", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset), utils::terminal::set_text_color( - &format!("Failed to report the scan status for project: '{}'.", project_name), + &format!( + "Failed to report the scan status for project: '{}'.", + project_name + ), utils::terminal::TerminalColor::Red ), utils::terminal::set_text_color(&scan_url, utils::terminal::TerminalColor::Blue), @@ -258,13 +294,14 @@ pub fn run( } }; if *fail { - let blocking_rules = match utils::api::check_blocking_rules(&config.get_url(), &scan_id, None) { - Ok(rules) => rules, - Err(e) => { - eprintln!("Failed to check blocking rules: {}", e); - std::process::exit(1); - } - }; + let blocking_rules = + match utils::api::check_blocking_rules(&config.get_url(), &scan_id, None) { + Ok(rules) => rules, + Err(e) => { + eprintln!("Failed to check blocking rules: {}", e); + std::process::exit(1); + } + }; if blocking_rules.block { println!("\nExiting with error code 1 due to some issues violating some blocking rules defined for this project.\nfor more details, please check the scan results at the link: {}\nAlternatively, you can run {} to view the issues list on your local machine.", utils::terminal::set_text_color(&scan_url, utils::terminal::TerminalColor::Green), @@ -282,18 +319,29 @@ pub fn run( let stop_signal = Arc::new(Mutex::new(false)); let stop_signal_clone = Arc::clone(&stop_signal); let results_thread = thread::spawn(move || { - utils::terminal::show_loading_message("Generating scan report... ([T]s)", stop_signal_clone); + utils::terminal::show_loading_message( + "Generating scan report... ([T]s)", + stop_signal_clone, + ); }); if out_format == "json" { - let issues = match utils::api::get_all_issues(&config.get_url(), &project_name, Some(scan_id.clone())) { + let issues = match utils::api::get_all_issues( + &config.get_url(), + &project_name, + Some(scan_id.clone()), + ) { Ok(issues) => issues, Err(e) => { eprintln!("\n\nFailed to fetch issues: {}\n\n", e); std::process::exit(1); } }; - let sca_issues = match utils::api::get_all_sca_issues(&config.get_url(), &project_name, Some(scan_id.clone())) { + let sca_issues = match utils::api::get_all_sca_issues( + &config.get_url(), + &project_name, + Some(scan_id.clone()), + ) { Ok(issues) => issues, Err(e) => { eprintln!("\n\nFailed to fetch SCA issues: {}\n\n", e); @@ -302,15 +350,17 @@ pub fn run( }; let json = serde_json::to_string_pretty(&issues).unwrap(); let sca_json = serde_json::to_string_pretty(&sca_issues).unwrap(); - let report_json= serde_json::to_string_pretty(&classifications).unwrap(); - let results_json = format!("{{\"issues\": {}, \"sca_issues\": {}, \"report\": {}}}", json, sca_json, report_json); + let report_json = serde_json::to_string_pretty(&classifications).unwrap(); + let results_json = format!( + "{{\"issues\": {}, \"sca_issues\": {}, \"report\": {}}}", + json, sca_json, report_json + ); *stop_signal.lock().unwrap() = true; let _ = results_thread.join(); fs::write(out_file.clone(), results_json).expect("Failed to write JSON file, check if the file path is valid and you have the necessary permissions to write to it."); utils::terminal::clear_previous_line(); println!("\n\nScan results written to: {}\n\n", out_file.clone()); - } - else if out_format == "html" { + } else if out_format == "html" { let report = match utils::api::get_scan_report(&config.get_url(), &scan_id, None) { Ok(html) => html, Err(e) => { @@ -323,23 +373,26 @@ pub fn run( fs::write(out_file.clone(), report).expect("\n\nFailed to write HTML file, check if the file path is valid and you have the necessary permissions to write to it."); utils::terminal::clear_previous_line(); println!("\n\nScan report written to: {}\n\n", out_file.clone()); - } - else if out_format == "sarif" { - let report = match utils::api::get_scan_report(&config.get_url(), &scan_id, Some("sarif")) { - Ok(sarif) => sarif, - Err(e) => { - eprintln!("\n\nFailed to fetch SARIF report: {}\n\n", e); - std::process::exit(1); - } - }; + } else if out_format == "sarif" { + let report = + match utils::api::get_scan_report(&config.get_url(), &scan_id, Some("sarif")) { + Ok(sarif) => sarif, + Err(e) => { + eprintln!("\n\nFailed to fetch SARIF report: {}\n\n", e); + std::process::exit(1); + } + }; *stop_signal.lock().unwrap() = true; let _ = results_thread.join(); fs::write(out_file.clone(), report).expect("\n\nFailed to write SARIF file, check if the file path is valid and you have the necessary permissions to write to it."); utils::terminal::clear_previous_line(); println!("\n\nScan report written to: {}\n\n", out_file.clone()); - } - else if out_format == "markdown" { - let report = match utils::api::get_scan_report(&config.get_url(), &scan_id, Some("markdown")) { + } else if out_format == "markdown" { + let report = match utils::api::get_scan_report( + &config.get_url(), + &scan_id, + Some("markdown"), + ) { Ok(markdown) => markdown, Err(e) => { eprintln!("\n\nFailed to fetch Markdown report: {}\n\n", e); @@ -359,100 +412,96 @@ pub fn run( if let Some(fail_on) = fail_on { match fail_on.as_str() { - "LO" => { - if classifications.values().any(|&count| count > 0) { - std::process::exit(1); - } - }, - "ME" => { - if classifications.get("ME").map_or(false, |&count| count > 0) || - classifications.get("HI").map_or(false, |&count| count > 0) { - std::process::exit(1); - } - }, - "HI" => { - if classifications.get("CR").map_or(false, |&count| count > 0) || - classifications.get("HI").map_or(false, |&count| count > 0) { - std::process::exit(1); - } - }, + "LO" if classifications.values().any(|&count| count > 0) => { + std::process::exit(1); + } + "ME" if (classifications.get("ME").is_some_and(|&count| count > 0) + || classifications.get("HI").is_some_and(|&count| count > 0)) => + { + std::process::exit(1); + } + "HI" if (classifications.get("CR").is_some_and(|&count| count > 0) + || classifications.get("HI").is_some_and(|&count| count > 0)) => + { + std::process::exit(1); + } "CR" => { if let Some(cr_count) = classifications.get("CR") { if *cr_count > 0 { std::process::exit(1); } } - }, + } _ => (), } } - - } pub fn wait_for_scan(config: &Config, scan_id: &str) { - // Create loading animation - let stop_signal = Arc::new(Mutex::new(false)); + // Create loading animation + let stop_signal = Arc::new(Mutex::new(false)); - // Spawn a new thread for the spinner animation - let stop_signal_clone = Arc::clone(&stop_signal); - thread::spawn(move || { - utils::terminal::show_loading_message("Scanning... The Hunt Is On! ([T]s)", stop_signal_clone); - }); - - loop { - std::thread::sleep(std::time::Duration::from_secs(1)); - match check_scan_status(&scan_id, &config.get_url()) { - Ok(true) => { - *stop_signal.lock().unwrap() = true; - break; - }, - Ok(false) => { }, - Err(e) => { - eprintln!( - "\n\nUnable to check the scan status for scan ID '{}'.\nPlease verify that: + // Spawn a new thread for the spinner animation + let stop_signal_clone = Arc::clone(&stop_signal); + thread::spawn(move || { + utils::terminal::show_loading_message( + "Scanning... The Hunt Is On! ([T]s)", + stop_signal_clone, + ); + }); + + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + match check_scan_status(scan_id, &config.get_url()) { + Ok(true) => { + *stop_signal.lock().unwrap() = true; + break; + } + Ok(false) => {} + Err(e) => { + eprintln!( + "\n\nUnable to check the scan status for scan ID '{}'.\nPlease verify that: - The server URL '{}' is reachable. - Your authentication token is valid. - The scan ID '{}' exists and is correct. Check out our docs at https://docs.corgea.app/install_cli#login-with-the-cli - Error details:\n{}", - scan_id, - config.get_url(), - scan_id, - e - ); - std::process::exit(1); - } + Error details:\n{}", + scan_id, + config.get_url(), + scan_id, + e + ); + std::process::exit(1); } } - print!("{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset)); - println!( - "\r╭────────────────────────────────────────────╮\n\ + } + print!( + "{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset) + ); + println!( + "\r╭────────────────────────────────────────────╮\n\ │ {: <42} │\n\ │ 🎉🎉 Scan Completed Successfully! 🎉🎉 │\n\ │ {: <42} │\n\ ╰────────────────────────────────────────────╯\n", - " ", - " " - ); - - - - + " ", " " + ); } - pub fn check_scan_status(scan_id: &str, url: &str) -> Result> { match utils::api::get_scan(url, scan_id) { Ok(scan) => Ok(scan.status == "complete"), - Err(e) => Err(e) + Err(e) => Err(e), } } - -pub fn fetch_and_group_scan_issues(url: &str, project: &str) -> Result, Box> { +pub fn fetch_and_group_scan_issues( + url: &str, + project: &str, +) -> Result, Box> { let issues = match utils::api::get_all_issues(url, project, None) { Ok(issues) => issues, Err(err) => { @@ -462,13 +511,18 @@ pub fn fetch_and_group_scan_issues(url: &str, project: &str) -> Result = HashMap::new(); if !issues.is_empty() { for issue in &issues { - *classification_counts.entry(issue.urgency.clone()).or_insert(0) += 1; + *classification_counts + .entry(issue.urgency.clone()) + .or_insert(0) += 1; } } Ok(classification_counts) } -pub fn report_scan_status(url: &str, project: &str) -> Result, Box>{ +pub fn report_scan_status( + url: &str, + project: &str, +) -> Result, Box> { let classification_counts = match fetch_and_group_scan_issues(url, project) { Ok(counts) => counts, Err(e) => { @@ -479,8 +533,8 @@ pub fn report_scan_status(url: &str, project: &str) -> Result(); utils::terminal::clear_previous_line(); println!("\rScan Results:-\n"); - println!("{:<20} | {}", "Classification", "Count"); - println!("{:-<20} | {}", "", ""); + println!("{:<20} | Count", "Classification"); + println!("{:-<20} | ", ""); let order = vec!["CR", "HI", "ME", "LO"]; for classification in order { @@ -491,8 +545,7 @@ pub fn report_scan_status(url: &str, project: &str) -> Result) { let temp_dir = match TempDir::new() { @@ -48,7 +48,14 @@ pub fn parse(config: &Config, file_path: &str, project_name: Option) { } let (scan_data, paths) = extract_file_path(outpath); - let _scan_id = upload_scan(config, paths, "fortify".to_string(), scan_data, false, project_name); + let _scan_id = upload_scan( + config, + paths, + "fortify".to_string(), + scan_data, + false, + project_name, + ); } else { println!("File 'audit.fvdl' not found in the archive"); }; @@ -61,7 +68,9 @@ fn extract_file_path(scan_file: PathBuf) -> (String, Vec) { let mut reader = BufReader::new(file); let mut contents = String::new(); - reader.read_to_string(&mut contents).expect("Unable to read file"); + reader + .read_to_string(&mut contents) + .expect("Unable to read file"); let mut xml_reader = Reader::from_str(&contents); xml_reader.config_mut().trim_text(true); diff --git a/src/scanners/parsers/checkmarx.rs b/src/scanners/parsers/checkmarx.rs index f8da40f..4fda0f2 100644 --- a/src/scanners/parsers/checkmarx.rs +++ b/src/scanners/parsers/checkmarx.rs @@ -1,8 +1,8 @@ -use serde_json::Value; +use super::{ParseResult, ScanParser}; use crate::log::debug; -use super::{ScanParser, ParseResult}; -use quick_xml::Reader; use quick_xml::events::Event; +use quick_xml::Reader; +use serde_json::Value; pub struct CheckmarxCliParser; @@ -79,13 +79,22 @@ impl ScanParser for CheckmarxWebParser { for language in languages { if let Some(queries) = language.get("queries").and_then(|v| v.as_array()) { for query in queries { - if let Some(vulns) = query.get("vulnerabilities").and_then(|v| v.as_array()) { + if let Some(vulns) = + query.get("vulnerabilities").and_then(|v| v.as_array()) + { for vuln in vulns { - if let Some(nodes) = vuln.get("nodes").and_then(|v| v.as_array()) { + if let Some(nodes) = + vuln.get("nodes").and_then(|v| v.as_array()) + { for node in nodes { if let Some(path) = node.get("fileName") { if let Some(truncated_path) = path.as_str() { - paths.push(truncated_path.get(1..).unwrap_or("").to_string()); + paths.push( + truncated_path + .get(1..) + .unwrap_or("") + .to_string(), + ); } } } @@ -124,14 +133,13 @@ impl CheckmarxXmlParser { match reader.read_event_into(&mut buf) { Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) => { if e.name().as_ref() == b"Result" { - for attr in e.attributes() { - if let Ok(attr) = attr { - if attr.key.as_ref() == b"FileName" { - if let Ok(file_name) = std::str::from_utf8(&attr.value) { - let clean_path = file_name.trim_start_matches('/').trim_start_matches('\\'); - if !clean_path.is_empty() { - paths.push(clean_path.to_string()); - } + for attr in e.attributes().flatten() { + if attr.key.as_ref() == b"FileName" { + if let Ok(file_name) = std::str::from_utf8(&attr.value) { + let clean_path = + file_name.trim_start_matches('/').trim_start_matches('\\'); + if !clean_path.is_empty() { + paths.push(clean_path.to_string()); } } } @@ -139,7 +147,8 @@ impl CheckmarxXmlParser { } else if e.name().as_ref() == b"FileName" { if let Ok(Event::Text(text)) = reader.read_event_into(&mut buf) { if let Ok(file_name) = std::str::from_utf8(text.as_ref()) { - let clean_path = file_name.trim_start_matches('/').trim_start_matches('\\'); + let clean_path = + file_name.trim_start_matches('/').trim_start_matches('\\'); if !clean_path.is_empty() { paths.push(clean_path.to_string()); } diff --git a/src/scanners/parsers/coverity.rs b/src/scanners/parsers/coverity.rs index 1d3f5d7..80c7109 100644 --- a/src/scanners/parsers/coverity.rs +++ b/src/scanners/parsers/coverity.rs @@ -23,17 +23,13 @@ impl ScanParser for CoverityParser { let is_merged_defect = e.name().as_ref() == b"cov:mergedDefect" || e.name().as_ref() == b"mergedDefect"; if is_merged_defect { - for attr in e.attributes() { - if let Ok(attr) = attr { - if attr.key.as_ref() == b"file" { - if let Ok(file_path) = std::str::from_utf8(attr.value.as_ref()) - { - let clean_path = file_path - .trim_start_matches('/') - .trim_start_matches('\\'); - if !clean_path.is_empty() { - paths.push(clean_path.to_string()); - } + for attr in e.attributes().flatten() { + if attr.key.as_ref() == b"file" { + if let Ok(file_path) = std::str::from_utf8(attr.value.as_ref()) { + let clean_path = + file_path.trim_start_matches('/').trim_start_matches('\\'); + if !clean_path.is_empty() { + paths.push(clean_path.to_string()); } } } diff --git a/src/scanners/parsers/mod.rs b/src/scanners/parsers/mod.rs index 8311935..cae9ae6 100644 --- a/src/scanners/parsers/mod.rs +++ b/src/scanners/parsers/mod.rs @@ -1,5 +1,3 @@ - - #[derive(Debug)] pub struct ParseResult { pub paths: Vec, @@ -34,8 +32,11 @@ impl ScanParserFactory { } #[allow(dead_code)] - pub fn find_parser(&self, input: &str) -> Option<&Box> { - self.parsers.iter().find(|parser| parser.detect(input)) + pub fn find_parser(&self, input: &str) -> Option<&dyn ScanParser> { + self.parsers + .iter() + .find(|parser| parser.detect(input)) + .map(|b| b.as_ref()) } pub fn parse_scan_data(&self, input: &str) -> Result { @@ -53,7 +54,7 @@ impl ScanParserFactory { } } -pub mod semgrep; -pub mod sarif; pub mod checkmarx; pub mod coverity; +pub mod sarif; +pub mod semgrep; diff --git a/src/scanners/parsers/sarif.rs b/src/scanners/parsers/sarif.rs index d9b1956..4781bda 100644 --- a/src/scanners/parsers/sarif.rs +++ b/src/scanners/parsers/sarif.rs @@ -1,29 +1,38 @@ -use serde_json::Value; +use super::{ParseResult, ScanParser}; use crate::log::debug; -use super::{ScanParser, ParseResult}; +use serde_json::Value; pub struct SarifParser; impl ScanParser for SarifParser { fn detect(&self, input: &str) -> bool { if let Ok(data) = serde_json::from_str::(input) { - let schema = data.get("$schema").and_then(|v| v.as_str()).unwrap_or("unknown"); + let schema = data + .get("$schema") + .and_then(|v| v.as_str()) + .unwrap_or("unknown"); schema.contains("sarif") } else { false } } - + fn parse(&self, input: &str) -> Option { debug("Detected sarif schema"); - + let data: Value = match serde_json::from_str(input) { Ok(data) => data, Err(_) => return None, }; - - let run = data.get("runs").and_then(|v| v.as_array()).and_then(|v| v.get(0)); - let driver = run.and_then(|v| v.get("tool")).and_then(|v| v.get("driver")).and_then(|v| v.get("name")); + + let run = data + .get("runs") + .and_then(|v| v.as_array()) + .and_then(|v| v.first()); + let driver = run + .and_then(|v| v.get("tool")) + .and_then(|v| v.get("driver")) + .and_then(|v| v.get("name")); let tool = driver.and_then(|v| v.as_str()).unwrap_or("unknown"); let scanner = match tool { @@ -46,12 +55,15 @@ impl ScanParser for SarifParser { for run in runs { if let Some(results) = run.get("results").and_then(|v| v.as_array()) { for result in results { - if let Some(locations) = result.get("locations").and_then(|v| v.as_array()) { + if let Some(locations) = result.get("locations").and_then(|v| v.as_array()) + { for location in locations { - if let Some(uri) = location.get("physicalLocation") + if let Some(uri) = location + .get("physicalLocation") .and_then(|v| v.get("artifactLocation")) .and_then(|v| v.get("uri")) - .and_then(|v| v.as_str()) { + .and_then(|v| v.as_str()) + { paths.push(uri.to_string()); } } @@ -60,10 +72,10 @@ impl ScanParser for SarifParser { } } } - + Some(ParseResult { paths, scanner }) } - + fn scanner_name(&self) -> &str { "sarif" } diff --git a/src/scanners/parsers/semgrep.rs b/src/scanners/parsers/semgrep.rs index db70bb6..f00548b 100644 --- a/src/scanners/parsers/semgrep.rs +++ b/src/scanners/parsers/semgrep.rs @@ -1,6 +1,6 @@ -use serde_json::Value; +use super::{ParseResult, ScanParser}; use crate::log::debug; -use super::{ScanParser, ParseResult}; +use serde_json::Value; pub struct SemgrepParser; @@ -8,15 +8,15 @@ impl ScanParser for SemgrepParser { fn detect(&self, input: &str) -> bool { input.contains("semgrep.dev") } - + fn parse(&self, input: &str) -> Option { debug("Detected semgrep schema"); - + let data: Value = match serde_json::from_str(input) { Ok(data) => data, Err(_) => return None, }; - + let mut paths = Vec::new(); if let Some(results) = data.get("results").and_then(|v| v.as_array()) { for result in results { @@ -25,13 +25,13 @@ impl ScanParser for SemgrepParser { } } } - + Some(ParseResult { paths, scanner: "semgrep".to_string(), }) } - + fn scanner_name(&self) -> &str { "semgrep" } diff --git a/src/setup_hooks.rs b/src/setup_hooks.rs index c90a78e..44febd8 100644 --- a/src/setup_hooks.rs +++ b/src/setup_hooks.rs @@ -29,11 +29,14 @@ pub fn setup_pre_commit_hook(include_default_scan_types: bool) { }); // Check if pre-commit hook already exists - if std::path::Path::new(&pre_commit_path).exists() { - if !terminal::ask_yes_no("Pre-commit hook already exists. Do you want to overwrite it?", false) { - println!("Skipping pre-commit hook setup."); - return; - } + if std::path::Path::new(&pre_commit_path).exists() + && !terminal::ask_yes_no( + "Pre-commit hook already exists. Do you want to overwrite it?", + false, + ) + { + println!("Skipping pre-commit hook setup."); + return; } // Determine scan types to include @@ -62,10 +65,13 @@ pub fn setup_pre_commit_hook(include_default_scan_types: bool) { // Determine fail-on severity levels to include // Create pre-commit hook content - let hook_content = format!(r#"#!/bin/sh + let hook_content = format!( + r#"#!/bin/sh # Corgea pre-commit hook corgea scan blast --only-uncommitted --fail-on LO --scan-type {} -"#, scan_types.join(",")); +"#, + scan_types.join(",") + ); // Write pre-commit hook std::fs::write(&pre_commit_path, hook_content).unwrap_or_else(|e| { @@ -74,11 +80,14 @@ corgea scan blast --only-uncommitted --fail-on LO --scan-type {} }); #[cfg(unix)] - std::fs::set_permissions(&pre_commit_path, std::os::unix::fs::PermissionsExt::from_mode(0o755)) - .unwrap_or_else(|e| { - eprintln!("Failed to set pre-commit hook permissions: {}", e); - std::process::exit(1); - }); + std::fs::set_permissions( + &pre_commit_path, + std::os::unix::fs::PermissionsExt::from_mode(0o755), + ) + .unwrap_or_else(|e| { + eprintln!("Failed to set pre-commit hook permissions: {}", e); + std::process::exit(1); + }); println!("Successfully installed pre-commit hook!"); } diff --git a/src/targets.rs b/src/targets.rs index 81f2d47..96efe65 100644 --- a/src/targets.rs +++ b/src/targets.rs @@ -1,9 +1,9 @@ +use git2::{Delta, Repository, StatusOptions}; +use globset::{Glob, GlobSetBuilder}; +use ignore::WalkBuilder; use std::collections::HashSet; use std::io::{self, BufRead, Read}; use std::path::{Path, PathBuf}; -use globset::{Glob, GlobSetBuilder}; -use ignore::WalkBuilder; -use git2::{Repository, StatusOptions, Delta}; #[derive(Debug)] pub struct TargetResolutionResult { @@ -66,7 +66,11 @@ pub fn resolve_targets(target_value: &str) -> Result Result Result, Stri } let path = Path::new(segment); - + let full_path = if path.is_absolute() { path.to_path_buf() } else { @@ -140,10 +141,11 @@ fn read_stdin_files(nul_delimited: bool) -> Result, String> { if nul_delimited { let mut buffer = Vec::new(); - stdin.lock().read_to_end(&mut buffer).map_err(|e| { - format!("Failed to read from stdin: {}", e) - })?; - + stdin + .lock() + .read_to_end(&mut buffer) + .map_err(|e| format!("Failed to read from stdin: {}", e))?; + for part in buffer.split(|&b| b == 0) { if part.is_empty() { continue; @@ -216,26 +218,25 @@ fn resolve_git_selector(selector: &str, repo_root: &Path) -> Result } fn get_git_staged_files(repo_root: &Path) -> Result, String> { - let repo = Repository::open(repo_root) - .map_err(|e| format!("Failed to open git repository: {}", e))?; + let repo = + Repository::open(repo_root).map_err(|e| format!("Failed to open git repository: {}", e))?; - let mut index = repo.index() + let mut index = repo + .index() .map_err(|e| format!("Failed to get index: {}", e))?; - let head_tree = repo.head() - .ok() - .and_then(|head| head.peel_to_tree().ok()); + let head_tree = repo.head().ok().and_then(|head| head.peel_to_tree().ok()); - let index_tree_id = index.write_tree() + let index_tree_id = index + .write_tree() .map_err(|e| format!("Failed to write index tree: {}", e))?; - let index_tree = repo.find_tree(index_tree_id) + let index_tree = repo + .find_tree(index_tree_id) .map_err(|e| format!("Failed to find index tree: {}", e))?; - let diff = repo.diff_tree_to_tree( - head_tree.as_ref(), - Some(&index_tree), - None - ).map_err(|e| format!("Failed to create diff: {}", e))?; + let diff = repo + .diff_tree_to_tree(head_tree.as_ref(), Some(&index_tree), None) + .map_err(|e| format!("Failed to create diff: {}", e))?; let mut files = Vec::new(); diff.foreach( @@ -253,21 +254,23 @@ fn get_git_staged_files(repo_root: &Path) -> Result, String> { None, None, None, - ).map_err(|e| format!("Failed to iterate diff: {}", e))?; + ) + .map_err(|e| format!("Failed to iterate diff: {}", e))?; Ok(files) } fn get_git_untracked_files(repo_root: &Path) -> Result, String> { - let repo = Repository::open(repo_root) - .map_err(|e| format!("Failed to open git repository: {}", e))?; + let repo = + Repository::open(repo_root).map_err(|e| format!("Failed to open git repository: {}", e))?; let mut opts = StatusOptions::new(); opts.include_untracked(true); opts.exclude_submodules(true); opts.include_ignored(false); - let statuses = repo.statuses(Some(&mut opts)) + let statuses = repo + .statuses(Some(&mut opts)) .map_err(|e| format!("Failed to get statuses: {}", e))?; let mut files = Vec::new(); @@ -284,17 +287,14 @@ fn get_git_untracked_files(repo_root: &Path) -> Result, String> { } fn get_git_modified_files(repo_root: &Path) -> Result, String> { - let repo = Repository::open(repo_root) - .map_err(|e| format!("Failed to open git repository: {}", e))?; + let repo = + Repository::open(repo_root).map_err(|e| format!("Failed to open git repository: {}", e))?; - let head_tree = repo.head() - .ok() - .and_then(|head| head.peel_to_tree().ok()); + let head_tree = repo.head().ok().and_then(|head| head.peel_to_tree().ok()); - let diff = repo.diff_tree_to_workdir( - head_tree.as_ref(), - None - ).map_err(|e| format!("Failed to create diff: {}", e))?; + let diff = repo + .diff_tree_to_workdir(head_tree.as_ref(), None) + .map_err(|e| format!("Failed to create diff: {}", e))?; let mut files = Vec::new(); diff.foreach( @@ -312,14 +312,15 @@ fn get_git_modified_files(repo_root: &Path) -> Result, String> { None, None, None, - ).map_err(|e| format!("Failed to iterate diff: {}", e))?; + ) + .map_err(|e| format!("Failed to iterate diff: {}", e))?; Ok(files) } fn get_git_diff_files(repo_root: &Path, range: &str) -> Result, String> { - let repo = Repository::open(repo_root) - .map_err(|e| format!("Failed to open git repository: {}", e))?; + let repo = + Repository::open(repo_root).map_err(|e| format!("Failed to open git repository: {}", e))?; let parts: Vec<&str> = range.split("...").collect(); let (old_ref, new_ref) = if parts.len() == 2 { @@ -329,23 +330,28 @@ fn get_git_diff_files(repo_root: &Path, range: &str) -> Result, Str if parts.len() == 2 { (parts[0].trim(), parts[1].trim()) } else { - return Err(format!("Invalid diff range format: {}. Expected format: 'old..new' or 'old...new'", range)); + return Err(format!( + "Invalid diff range format: {}. Expected format: 'old..new' or 'old...new'", + range + )); } }; let old_commit = if old_ref.is_empty() { None } else { - Some(repo.revparse_single(old_ref) - .map_err(|e| format!("Failed to resolve reference '{}': {}", old_ref, e))? - .id()) + Some( + repo.revparse_single(old_ref) + .map_err(|e| format!("Failed to resolve reference '{}': {}", old_ref, e))? + .id(), + ) }; let new_commit = if new_ref.is_empty() { repo.head() .map_err(|e| format!("Failed to get HEAD: {}", e))? .target() - .ok_or_else(|| format!("HEAD is not a direct reference"))? + .ok_or_else(|| "HEAD is not a direct reference".to_string())? } else { repo.revparse_single(new_ref) .map_err(|e| format!("Failed to resolve reference '{}': {}", new_ref, e))? @@ -353,24 +359,25 @@ fn get_git_diff_files(repo_root: &Path, range: &str) -> Result, Str }; let old_tree = if let Some(old_id) = old_commit { - Some(repo.find_commit(old_id) - .map_err(|e| format!("Failed to find commit: {}", e))? - .tree() - .map_err(|e| format!("Failed to get tree: {}", e))?) + Some( + repo.find_commit(old_id) + .map_err(|e| format!("Failed to find commit: {}", e))? + .tree() + .map_err(|e| format!("Failed to get tree: {}", e))?, + ) } else { None }; - let new_tree = repo.find_commit(new_commit) + let new_tree = repo + .find_commit(new_commit) .map_err(|e| format!("Failed to find commit: {}", e))? .tree() .map_err(|e| format!("Failed to get tree: {}", e))?; - let diff = repo.diff_tree_to_tree( - old_tree.as_ref(), - Some(&new_tree), - None - ).map_err(|e| format!("Failed to create diff: {}", e))?; + let diff = repo + .diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), None) + .map_err(|e| format!("Failed to create diff: {}", e))?; let mut files = Vec::new(); diff.foreach( @@ -388,22 +395,21 @@ fn get_git_diff_files(repo_root: &Path, range: &str) -> Result, Str None, None, None, - ).map_err(|e| format!("Failed to iterate diff: {}", e))?; + ) + .map_err(|e| format!("Failed to iterate diff: {}", e))?; Ok(files) } fn resolve_directory(dir: &Path, _repo_root: &Path) -> Result, String> { let mut files = Vec::new(); - - let walker = WalkBuilder::new(dir) - .standard_filters(true) - .build(); + + let walker = WalkBuilder::new(dir).standard_filters(true).build(); for result in walker { let entry = result.map_err(|e| format!("Error walking directory: {}", e))?; let path = entry.path(); - + if path.is_file() { files.push(path.to_path_buf()); } @@ -413,24 +419,23 @@ fn resolve_directory(dir: &Path, _repo_root: &Path) -> Result, Stri } fn resolve_glob(pattern: &str, repo_root: &Path) -> Result, String> { - let glob = Glob::new(pattern) - .map_err(|e| format!("Invalid glob pattern '{}': {}", pattern, e))?; + let glob = + Glob::new(pattern).map_err(|e| format!("Invalid glob pattern '{}': {}", pattern, e))?; let mut glob_builder = GlobSetBuilder::new(); glob_builder.add(glob); - let glob_set = glob_builder.build() + let glob_set = glob_builder + .build() .map_err(|e| format!("Failed to build glob set: {}", e))?; let mut files = Vec::new(); - - let walker = WalkBuilder::new(repo_root) - .standard_filters(true) - .build(); + + let walker = WalkBuilder::new(repo_root).standard_filters(true).build(); for result in walker { let entry = result.map_err(|e| format!("Error walking directory: {}", e))?; let path = entry.path(); - + if path.is_file() { // Get relative path from repo root if let Ok(relative) = path.strip_prefix(repo_root) { @@ -459,23 +464,19 @@ fn normalize_path(path: &Path, _repo_root: &Path) -> Result { } fn find_repo_root() -> Result { - let current_dir = std::env::current_dir() - .map_err(|e| format!("Failed to get current directory: {}", e))?; + let current_dir = + std::env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?; match Repository::discover(¤t_dir) { - Ok(repo) => { - repo.workdir() - .map(|p| p.to_path_buf()) - .or_else(|| repo.path().parent().map(|p| p.to_path_buf())) - .ok_or_else(|| "Failed to determine repository root".to_string()) - } - Err(_) => { - Ok(current_dir) - } + Ok(repo) => repo + .workdir() + .map(|p| p.to_path_buf()) + .or_else(|| repo.path().parent().map(|p| p.to_path_buf())) + .ok_or_else(|| "Failed to determine repository root".to_string()), + Err(_) => Ok(current_dir), } } fn is_git_repo(dir: &Path) -> bool { Repository::discover(dir).is_ok() } - diff --git a/src/utils/api.rs b/src/utils/api.rs index f0e8a59..6f08083 100644 --- a/src/utils/api.rs +++ b/src/utils/api.rs @@ -1,16 +1,19 @@ +use crate::log::debug; use crate::utils; -use serde_json::json; -use std::collections::HashMap; use reqwest::header::HeaderMap; -use serde::{Deserialize, Serialize}; use reqwest::StatusCode; -use std::fs::File; +use reqwest::{ + blocking::multipart, + blocking::multipart::{Form, Part}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use serde_json::Value; +use std::collections::HashMap; use std::error::Error; +use std::fs::File; use std::io::Read; use std::path::Path; -use reqwest::{blocking::multipart, blocking::multipart::{Form, Part}}; -use serde_json::Value; -use crate::log::debug; const CHUNK_SIZE: usize = 50 * 1024 * 1024; // 50 MB const API_BASE: &str = "/api/v1"; @@ -58,7 +61,7 @@ static SHARED_CLIENT: std::sync::LazyLock = debug(&format!("https_proxy detected: {}", https_proxy)); if std::env::var("CORGEA_ACCEPT_CERT").is_ok() { - debug(&format!("Skipping CA cert validation")); + debug("Skipping CA cert validation"); builder = builder.danger_accept_invalid_certs(true); } } @@ -77,15 +80,24 @@ pub struct DebugRequestBuilder { impl HttpClient { pub fn get(&self, url: U) -> DebugRequestBuilder { - DebugRequestBuilder { client: self.inner.clone(), inner: self.inner.get(url) } + DebugRequestBuilder { + client: self.inner.clone(), + inner: self.inner.get(url), + } } pub fn post(&self, url: U) -> DebugRequestBuilder { - DebugRequestBuilder { client: self.inner.clone(), inner: self.inner.post(url) } + DebugRequestBuilder { + client: self.inner.clone(), + inner: self.inner.post(url), + } } pub fn patch(&self, url: U) -> DebugRequestBuilder { - DebugRequestBuilder { client: self.inner.clone(), inner: self.inner.patch(url) } + DebugRequestBuilder { + client: self.inner.clone(), + inner: self.inner.patch(url), + } } } @@ -97,19 +109,31 @@ impl DebugRequestBuilder { reqwest::header::HeaderValue: TryFrom, >::Error: Into, { - Self { inner: self.inner.header(key, value), client: self.client } + Self { + inner: self.inner.header(key, value), + client: self.client, + } } pub fn query(self, query: &T) -> Self { - Self { inner: self.inner.query(query), client: self.client } + Self { + inner: self.inner.query(query), + client: self.client, + } } pub fn multipart(self, form: reqwest::blocking::multipart::Form) -> Self { - Self { inner: self.inner.multipart(form), client: self.client } + Self { + inner: self.inner.multipart(form), + client: self.client, + } } pub fn body>(self, body: T) -> Self { - Self { inner: self.inner.body(body), client: self.client } + Self { + inner: self.inner.body(body), + client: self.client, + } } pub fn send(self) -> reqwest::Result { @@ -127,7 +151,10 @@ impl DebugRequestBuilder { debug(&format!("→ {} {}", request.method(), request.url())); debug(&format!(" Request headers: {:?}", request.headers())); match COOKIE_JAR.cookies(request.url()) { - Some(cookies) => debug(&format!(" Cookie: {}", cookies.to_str().unwrap_or(""))), + Some(cookies) => debug(&format!( + " Cookie: {}", + cookies.to_str().unwrap_or("") + )), None => debug(" Cookie: (none in jar for this URL)"), } @@ -141,18 +168,27 @@ impl DebugRequestBuilder { } pub fn http_client() -> HttpClient { - HttpClient { inner: SHARED_CLIENT.clone() } + HttpClient { + inner: SHARED_CLIENT.clone(), + } +} + +/// Returns true when the `warning` header carries an RFC 7234 code `299`, +/// which Corgea uses to signal a deprecated CLI version. +fn should_warn_deprecated(headers: &HeaderMap) -> bool { + headers + .get("warning") + .and_then(|v| v.to_str().ok()) + .map(|text| { + text.split(',') + .any(|w| w.trim().split(' ').next() == Some("299")) + }) + .unwrap_or(false) } fn check_for_warnings(headers: &HeaderMap, status: StatusCode) { - if let Some(warning) = headers.get("warning") { - let warnings = warning.to_str().unwrap().split(','); - for warning in warnings { - let code = warning.trim().split(' ').next().unwrap(); - if code == "299" { - eprintln!("This version of the Corgea plugin is deprecated. Please upgrade to the latest version to ensure continued support and better performance."); - } - } + if should_warn_deprecated(headers) { + eprintln!("This version of the Corgea plugin is deprecated. Please upgrade to the latest version to ensure continued support and better performance."); } if status == StatusCode::GONE { eprintln!("Support for this extension version has dropped. Please upgrade Corgea extension immediately to continue using it."); @@ -171,68 +207,81 @@ pub fn upload_zip( project_name: &str, repo_info: Option, scan_type: Option, - policy: Option + policy: Option, ) -> Result> { let client = http_client(); let file_size = std::fs::metadata(file_path)?.len(); - let file_name = Path::new(file_path) - .file_name() - .unwrap() - .to_str() - .unwrap(); + let file_name = Path::new(file_path).file_name().unwrap().to_str().unwrap(); let json_object = json!({ "file_name": file_name, "file_size": file_size }); let form = reqwest::blocking::multipart::Form::new() - .part("files", reqwest::blocking::multipart::Part::bytes(Vec::new()) - .file_name(file_name.to_string())) + .part( + "files", + reqwest::blocking::multipart::Part::bytes(Vec::new()).file_name(file_name.to_string()), + ) .text("json", json_object.to_string()); let response_object = client .post(format!("{}{}/start-scan", url, API_BASE)) - .query(&[ - ("scan_type", "blast"), - ]) + .query(&[("scan_type", "blast")]) .multipart(form) .send(); let response_object = match response_object { Ok(response) => { check_for_warnings(response.headers(), response.status()); response - }, - Err(err) => return Err(format!("Network error: Unable to reach the server. Please try again later. Error: {}", err).into()), + } + Err(err) => { + return Err(format!( + "Network error: Unable to reach the server. Please try again later. Error: {}", + err + ) + .into()) + } }; let response_status = response_object.status(); let response_text = response_object.text()?; - + if response_status != StatusCode::OK { - debug(&format!("Initial scan request failed with status: {}. Response body: {}", response_status, response_text)); - + debug(&format!( + "Initial scan request failed with status: {}. Response body: {}", + response_status, response_text + )); + if response_status == StatusCode::BAD_REQUEST { - if let Ok(error_response) = serde_json::from_str::>(&response_text) { + if let Ok(error_response) = + serde_json::from_str::>(&response_text) + { if let Some(message) = error_response.get("message").and_then(Value::as_str) { return Err(format!("Request failed: {}", message).into()); } } return Err(format!("Request failed (400): {}", response_text).into()); } - + return Err("Error getting server response, Please try again later.".into()); } - + let response: HashMap = match serde_json::from_str(&response_text) { Ok(json) => json, Err(_) => { - debug(&format!("Failed to parse initial scan response as JSON. Response body: {}", response_text)); + debug(&format!( + "Failed to parse initial scan response as JSON. Response body: {}", + response_text + )); return Err("Error getting server response, Please try again later.".into()); - }, + } }; let transfer_id = match response["transfer_id"].as_str() { Some(transfer_id) => transfer_id, - None => return Err("Failed to retrieve transfer ID. Please check the request parameters and try again.".into()), + None => return Err( + "Failed to retrieve transfer ID. Please check the request parameters and try again." + .into(), + ), }; let mut file = File::open(file_path)?; let mut buffer = vec![0; CHUNK_SIZE]; @@ -247,14 +296,17 @@ pub fn upload_zip( let chunk = &buffer[..bytes_read]; let mut form = Form::new() - .part( - "chunk_data", - Part::bytes(chunk.to_vec()) - .file_name(file_name.to_string()) - .mime_str("application/octet-stream")?, - ) - .part("project_name", multipart::Part::text(project_name.to_string())) - .part("file_size", multipart::Part::text(file_size.to_string())); + .part( + "chunk_data", + Part::bytes(chunk.to_vec()) + .file_name(file_name.to_string()) + .mime_str("application/octet-stream")?, + ) + .part( + "project_name", + multipart::Part::text(project_name.to_string()), + ) + .part("file_size", multipart::Part::text(file_size.to_string())); if let Some(ref info) = repo_info { if let Some(branch) = &info.branch { form = form.part("branch", multipart::Part::text(branch.to_string())); @@ -279,58 +331,69 @@ pub fn upload_zip( } let response = match client - .patch(format!("{}{}/start-scan/{}/", url, API_BASE, transfer_id)) - .header("Upload-Offset", offset.to_string()) - .header("Upload-Length", file_size.to_string()) - .header("Upload-Name", file_name) - .query(&[ - ("scan_type", "blast") - ]) - .multipart(form) - .send() { + .patch(format!("{}{}/start-scan/{}/", url, API_BASE, transfer_id)) + .header("Upload-Offset", offset.to_string()) + .header("Upload-Length", file_size.to_string()) + .header("Upload-Name", file_name) + .query(&[("scan_type", "blast")]) + .multipart(form) + .send() + { Ok(response) => { check_for_warnings(response.headers(), response.status()); response - }, + } Err(e) => { return Err(format!("Failed to send request: {}", e).into()); } }; if !response.status().is_success() { let status_code = response.status(); - let response_text = response.text().unwrap_or_else(|_| "Unable to read response body".to_string()); - debug(&format!("Chunk upload failed with status: {}. Response body: {}", status_code, response_text)); - + let response_text = response + .text() + .unwrap_or_else(|_| "Unable to read response body".to_string()); + debug(&format!( + "Chunk upload failed with status: {}. Response body: {}", + status_code, response_text + )); + if status_code.is_client_error() && response_text.contains("Invalid policy ids") { - return Err("Invalid policy ids passed. Please check the policy ids and try again.".into()); + return Err( + "Invalid policy ids passed. Please check the policy ids and try again.".into(), + ); } - + if status_code == StatusCode::BAD_REQUEST { - if let Ok(error_response) = serde_json::from_str::>(&response_text) { + if let Ok(error_response) = + serde_json::from_str::>(&response_text) + { if let Some(message) = error_response.get("message").and_then(Value::as_str) { return Err(format!("Upload failed: {}", message).into()); } } return Err(format!("Upload failed (400): {}", response_text).into()); } - - return Err(format!("Failed to upload file: {}", status_code).into()); + return Err(format!("Failed to upload file: {}", status_code).into()); } utils::terminal::show_progress_bar(offset as f32 / file_size as f32); offset += bytes_read as u64; if bytes_read < CHUNK_SIZE { utils::terminal::show_progress_bar(1.0); - print!("\n"); + println!(); let body: HashMap = response.json()?; if let Some(scan_id_value) = body.get("scan_id") { let scan_id = scan_id_value.as_str().unwrap().to_string(); let project_id = body.get("project_id").and_then(|v| { - v.as_str().map(|s| s.to_string()) + v.as_str() + .map(|s| s.to_string()) .or_else(|| v.as_i64().map(|n| n.to_string())) }); - return Ok(UploadZipResult { scan_id, project_id }); + return Ok(UploadZipResult { + scan_id, + project_id, + }); } else { return Err("Failed to get scan_id from response".into()); } @@ -340,14 +403,24 @@ pub fn upload_zip( Err("Failed to upload file".into()) } -pub fn get_all_issues(url: &str, project: &str, scan_id: Option) -> Result, Box> { +pub fn get_all_issues( + url: &str, + project: &str, + scan_id: Option, +) -> Result, Box> { let mut all_issues = Vec::new(); let mut current_page: u32 = 1; loop { - let response = match get_scan_issues(url, project, Some(current_page as u16), Some(30), scan_id.clone()) { + let response = match get_scan_issues( + url, + project, + Some(current_page as u16), + Some(30), + scan_id.clone(), + ) { Ok(response) => response, - Err(e) => return Err(format!("Failed to get scan issues: {}", e).into()) + Err(e) => return Err(format!("Failed to get scan issues: {}", e).into()), }; if let Some(mut issues) = response.issues { @@ -374,19 +447,14 @@ pub fn get_scan_issues( project: &str, page: Option, page_size: Option, - scan_id: Option -) -> Result> { + scan_id: Option, +) -> Result> { let mut seperator = "?"; let mut url = match scan_id { Some(scan_id) => format!("{}{}/scan/{}/issues", url, API_BASE, scan_id), None => { seperator = "&"; - format!( - "{}{}/issues?project={}", - url, - API_BASE, - project - ) + format!("{}{}/issues?project={}", url, API_BASE, project) } }; if let Some(p) = page { @@ -405,14 +473,18 @@ pub fn get_scan_issues( Ok(res) => { check_for_warnings(res.headers(), res.status()); res - }, + } Err(e) => return Err(format!("Failed to send request: {}", e).into()), }; let response_text = response.text()?; - let project_issues_response: ProjectIssuesResponse = serde_json::from_str(&response_text).map_err(|e| { - debug(&format!("Failed to parse response: {}. Response body: {}", e, response_text)); - format!("Failed to parse response: {}", e) - })?; + let project_issues_response: ProjectIssuesResponse = serde_json::from_str(&response_text) + .map_err(|e| { + debug(&format!( + "Failed to parse response: {}. Response body: {}", + e, response_text + )); + format!("Failed to parse response: {}", e) + })?; if project_issues_response.status == "ok" { Ok(project_issues_response) @@ -423,7 +495,7 @@ pub fn get_scan_issues( } } -pub fn get_scan(url: &str, scan_id: &str) -> Result> { +pub fn get_scan(url: &str, scan_id: &str) -> Result> { let url = format!("{}{}/scan/{}", url, API_BASE, scan_id); let client = http_client(); @@ -438,16 +510,27 @@ pub fn get_scan(url: &str, scan_id: &str) -> Result) -> Result> { +pub fn get_scan_report( + url: &str, + scan_id: &str, + format: Option<&str>, +) -> Result> { let url = if let Some(fmt) = format { format!("{}{}/scan/{}/report?format={}", url, API_BASE, scan_id, fmt) } else { @@ -468,43 +551,43 @@ pub fn get_scan_report(url: &str, scan_id: &str, format: Option<&str>) -> Result if response.status().is_success() { Ok(response.text()?) } else { - Err(format!("Error: Unable to fetch scan report. Status code: {}", response.status()).into()) + Err(format!( + "Error: Unable to fetch scan report. Status code: {}", + response.status() + ) + .into()) } } pub fn get_issue(url: &str, issue: &str) -> Result> { - let url = format!( - "{}{}/issue/{}", - url, - API_BASE, - issue, - ); + let url = format!("{}{}/issue/{}", url, API_BASE, issue,); let client = http_client(); debug(&format!("Sending request to URL: {}", url)); let response = match client.get(&url).send() { Ok(res) => { check_for_warnings(res.headers(), res.status()); res - }, + } Err(e) => return Err(format!("Failed to send request: {}", e).into()), }; let response_text = response.text()?; - return match serde_json::from_str::(&response_text) { + match serde_json::from_str::(&response_text) { Ok(body) => Ok(body), Err(e) => { - debug(&format!("Failed to parse response: {}. Response body: {}", e, response_text)); + debug(&format!( + "Failed to parse response: {}. Response body: {}", + e, response_text + )); Err(format!("Failed to parse response: {}", e).into()) - }, - }; + } + } } - - pub fn query_scan_list( url: &str, project: Option<&str>, page: Option, - page_size: Option + page_size: Option, ) -> Result> { let url = format!("{}{}/scans", url, API_BASE); let page = page.unwrap_or(1); @@ -518,60 +601,57 @@ pub fn query_scan_list( query_params.push(("project", project.to_string())); } - let client = http_client(); debug(&format!("Sending request to URL: {}", url)); - let response = match client - .get(url) - .query(&query_params) - .send() { - Ok(res) => { - check_for_warnings(res.headers(), res.status()); - res - }, - Err(e) => return Err(format!("API request failed: {}", e).into()), - }; - if response.status().is_success() { - let response_text = response.text()?; - let api_response: ScansResponse = serde_json::from_str(&response_text).map_err(|e| { - debug(&format!("Failed to parse response: {}. Response body: {}", e, response_text)); - format!("Failed to parse response: {}", e) - })?; - Ok(api_response) - } else { - Err(format!( - "API request failed with status: {}", - response.status() - ).into()) + let response = match client.get(url).query(&query_params).send() { + Ok(res) => { + check_for_warnings(res.headers(), res.status()); + res } + Err(e) => return Err(format!("API request failed: {}", e).into()), + }; + if response.status().is_success() { + let response_text = response.text()?; + let api_response: ScansResponse = serde_json::from_str(&response_text).map_err(|e| { + debug(&format!( + "Failed to parse response: {}. Response body: {}", + e, response_text + )); + format!("Failed to parse response: {}", e) + })?; + Ok(api_response) + } else { + Err(format!("API request failed with status: {}", response.status()).into()) + } } - pub fn exchange_code_for_token( base_url: &str, code: &str, ) -> Result> { let client = reqwest::blocking::Client::new(); let exchange_url = format!("{}{}/authorize", base_url, API_BASE); - + let response = client .get(&exchange_url) .header("CORGEA-SOURCE", get_source()) .query(&[("code", code)]) .send()?; - + if response.status().is_success() { let response_json: HashMap = response.json()?; - + if let Some(user_token) = response_json.get("user_token") { if let Some(user_token_str) = user_token.as_str() { return Ok(user_token_str.to_string()); } } - + Err("User token not found in response".into()) } else { - let error_text = response.text().unwrap_or_else(|_| "Unknown error".to_string()); + let error_text = response + .text() + .unwrap_or_else(|_| "Unknown error".to_string()); Err(format!("Failed to exchange code for user token: {}", error_text).into()) } } @@ -581,9 +661,7 @@ pub fn verify_token(corgea_url: &str) -> Result> { let client = http_client(); debug(&format!("Sending request to URL: {}", url)); - let response = client - .get(&url) - .send()?; + let response = client.get(&url).send()?; check_for_warnings(response.headers(), response.status()); @@ -592,8 +670,11 @@ pub fn verify_token(corgea_url: &str) -> Result> { let body: HashMap = match serde_json::from_str(&body_text) { Ok(json) => json, Err(e) => { - debug(&format!("Failed to parse response as JSON: {}. Response body: {}", e, body_text)); - return Err(format!("Failed to parse response").into()); + debug(&format!( + "Failed to parse response as JSON: {}. Response body: {}", + e, body_text + )); + return Err("Failed to parse response".to_string().into()); } }; @@ -606,9 +687,12 @@ pub fn verify_token(corgea_url: &str) -> Result> { pub fn check_blocking_rules( url: &str, sast_scan_id: &str, - page: Option + page: Option, ) -> Result> { - let url = format!("{}{}/scan/{}/check_blocking_rules", url, API_BASE, sast_scan_id); + let url = format!( + "{}{}/scan/{}/check_blocking_rules", + url, API_BASE, sast_scan_id + ); let page = page.unwrap_or(1); let query_params = vec![("page", page.to_string())]; @@ -616,43 +700,40 @@ pub fn check_blocking_rules( debug(&format!("Sending request to URL: {}", url)); debug(&format!("Query params: {:?}", query_params)); - let response = match client - .get(url) - .query(&query_params) - .send() { - Ok(res) => { - check_for_warnings(res.headers(), res.status()); - debug(&format!("Response status: {}", res.status())); - debug(&format!("Response headers: {:?}", res.headers())); - res - }, - Err(e) => return Err(format!("API request failed: {}", e).into()), - }; + let response = match client.get(url).query(&query_params).send() { + Ok(res) => { + check_for_warnings(res.headers(), res.status()); + debug(&format!("Response status: {}", res.status())); + debug(&format!("Response headers: {:?}", res.headers())); + res + } + Err(e) => return Err(format!("API request failed: {}", e).into()), + }; if response.status().is_success() { let response_text = response.text()?; - let api_response: BlockingRuleResponse = serde_json::from_str(&response_text).map_err(|e| { - debug(&format!("Failed to parse response: {}. Response body: {}", e, response_text)); - format!("Failed to parse response: {}", e) - })?; + let api_response: BlockingRuleResponse = + serde_json::from_str(&response_text).map_err(|e| { + debug(&format!( + "Failed to parse response: {}. Response body: {}", + e, response_text + )); + format!("Failed to parse response: {}", e) + })?; Ok(api_response) } else { let status = response.status(); let response_text = response.text()?; debug(&format!("Response body: {}", response_text)); - Err(format!( - "API request failed with status: {}", - status - ).into()) + Err(format!("API request failed with status: {}", status).into()) } } - pub fn get_sca_issues( url: &str, page: Option, page_size: Option, - scan_id: Option + scan_id: Option, ) -> Result> { let client = http_client(); let mut query_params = vec![]; @@ -672,10 +753,7 @@ pub fn get_sca_issues( debug(&format!("Sending request to URL: {}", endpoint)); debug(&format!("Query params: {:?}", query_params)); - let response = client - .get(&endpoint) - .query(&query_params) - .send(); + let response = client.get(&endpoint).query(&query_params).send(); let response = match response { Ok(response) => { @@ -683,14 +761,23 @@ pub fn get_sca_issues( debug(&format!("Response status: {}", response.status())); debug(&format!("Response headers: {:?}", response.headers())); response - }, - Err(err) => return Err(format!("Network error: Unable to reach the server. Please try again later. Error: {}", err).into()), + } + Err(err) => { + return Err(format!( + "Network error: Unable to reach the server. Please try again later. Error: {}", + err + ) + .into()) + } }; let status = response.status(); if !status.is_success() { if status == StatusCode::NOT_FOUND { - return Err("SCA issues not found. Please check the scan ID or ensure the scan has SCA issues.".into()); + return Err( + "SCA issues not found. Please check the scan ID or ensure the scan has SCA issues." + .into(), + ); } return Err(format!("Request failed with status: {}", status).into()); } @@ -699,9 +786,12 @@ pub fn get_sca_issues( let response_data: SCAIssuesResponse = match serde_json::from_str(&response_text) { Ok(json) => json, Err(e) => { - debug(&format!("Failed to parse response: {}. Response body: {}", e, response_text)); - return Err("Error parsing server response. Please try again later.".into()) - }, + debug(&format!( + "Failed to parse response: {}. Response body: {}", + e, response_text + )); + return Err("Error parsing server response. Please try again later.".into()); + } }; Ok(response_data) @@ -710,16 +800,17 @@ pub fn get_sca_issues( pub fn get_all_sca_issues( url: &str, _project: &str, - scan_id: Option + scan_id: Option, ) -> Result, Box> { let mut all_issues = Vec::new(); let mut current_page: u32 = 1; loop { - let response = match get_sca_issues(url, Some(current_page as u16), Some(30), scan_id.clone()) { - Ok(response) => response, - Err(e) => return Err(format!("Failed to get SCA issues: {}", e).into()) - }; + let response = + match get_sca_issues(url, Some(current_page as u16), Some(30), scan_id.clone()) { + Ok(response) => response, + Err(e) => return Err(format!("Failed to get SCA issues: {}", e).into()), + }; if response.issues.is_empty() { break; @@ -737,7 +828,7 @@ pub fn get_all_sca_issues( } #[derive(Deserialize, Serialize, Debug)] -pub struct ScanResponse { +pub struct ScanResponse { pub id: String, pub project: String, pub repo: Option, @@ -753,10 +844,9 @@ pub struct ProjectIssuesResponse { pub issues: Option>, pub page: Option, pub total_pages: Option, - pub total_issues: Option + pub total_issues: Option, } - #[derive(Serialize, Deserialize, Debug)] pub struct ScansResponse { pub status: String, @@ -765,7 +855,6 @@ pub struct ScansResponse { pub scans: Option>, } - #[derive(Serialize, Deserialize, Debug)] pub struct FullIssueResponse { pub status: String, @@ -802,7 +891,6 @@ pub struct IssueWithBlockingRules { pub blocking_rules: Option>, } - #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Classification { pub id: String, @@ -877,7 +965,7 @@ pub struct BlockingRuleResponse { #[derive(Deserialize, Debug, Clone)] pub struct BlockingIssue { pub id: String, - pub triggered_by_rules: Vec + pub triggered_by_rules: Vec, } #[derive(Deserialize, Serialize, Debug)] @@ -913,3 +1001,90 @@ pub struct SCAIssuesResponse { pub total_pages: u32, pub total_issues: u32, } + +#[cfg(test)] +mod tests { + use super::*; + use reqwest::header::{HeaderMap, HeaderValue}; + + #[test] + fn is_jwt_accepts_three_dot_separated_non_empty_parts() { + assert!(is_jwt("aaa.bbb.ccc")); + assert!(is_jwt("header.payload.signature")); + } + + #[test] + fn is_jwt_rejects_wrong_part_count() { + assert!(!is_jwt("aaa.bbb")); + assert!(!is_jwt("aaa.bbb.ccc.ddd")); + assert!(!is_jwt("plainstring")); + assert!(!is_jwt("")); + } + + #[test] + fn is_jwt_rejects_when_any_part_is_empty() { + assert!(!is_jwt("aaa..ccc")); + assert!(!is_jwt(".bbb.ccc")); + assert!(!is_jwt("aaa.bbb.")); + } + + #[test] + fn auth_headers_uses_bearer_for_jwt_tokens() { + let headers = auth_headers("aaa.bbb.ccc"); + + assert_eq!( + headers.get("Authorization").map(|v| v.to_str().unwrap()), + Some("Bearer aaa.bbb.ccc") + ); + assert!(headers.get("CORGEA-TOKEN").is_none()); + assert!(headers.get("CORGEA-SOURCE").is_some()); + } + + #[test] + fn auth_headers_uses_corgea_token_header_for_opaque_tokens() { + let headers = auth_headers("opaque-token-xyz"); + + assert_eq!( + headers.get("CORGEA-TOKEN").map(|v| v.to_str().unwrap()), + Some("opaque-token-xyz") + ); + assert!(headers.get("Authorization").is_none()); + assert!(headers.get("CORGEA-SOURCE").is_some()); + } + + #[test] + fn should_warn_deprecated_false_when_no_warning_header() { + let headers = HeaderMap::new(); + assert!(!should_warn_deprecated(&headers)); + } + + #[test] + fn should_warn_deprecated_false_for_non_299_codes() { + let mut headers = HeaderMap::new(); + headers.insert( + "warning", + HeaderValue::from_static("199 - \"misc warning\""), + ); + assert!(!should_warn_deprecated(&headers)); + } + + #[test] + fn should_warn_deprecated_true_for_single_299() { + let mut headers = HeaderMap::new(); + headers.insert( + "warning", + HeaderValue::from_static("299 host \"deprecated\""), + ); + assert!(should_warn_deprecated(&headers)); + } + + #[test] + fn should_warn_deprecated_true_when_299_in_comma_separated_list() { + let mut headers = HeaderMap::new(); + headers.insert( + "warning", + HeaderValue::from_static("199 host \"first\", 299 host \"deprecated\""), + ); + assert!(should_warn_deprecated(&headers)); + } +} diff --git a/src/utils/generic.rs b/src/utils/generic.rs index 627ddda..7cfad56 100644 --- a/src/utils/generic.rs +++ b/src/utils/generic.rs @@ -1,12 +1,12 @@ +use crate::utils::terminal::{set_text_color, TerminalColor}; +use git2::Repository; +use globset::{Glob, GlobSetBuilder}; +use ignore::WalkBuilder; +use std::env; +use std::fs::{self, File}; use std::io; use std::path::{Path, PathBuf}; use zip::{write::FileOptions, ZipWriter}; -use ignore::WalkBuilder; -use globset::{GlobSetBuilder, Glob}; -use std::fs::{self, File}; -use std::env; -use git2::Repository; -use crate::utils::terminal::{set_text_color, TerminalColor}; // Global exclude globs used across multiple functions const DEFAULT_EXCLUDE_GLOBS: &[&str] = &[ @@ -32,7 +32,7 @@ const DEFAULT_EXCLUDE_GLOBS: &[&str] = &[ ]; /// Create a zip file from a target specification or full repository scan. -/// +/// /// - If `target` is `None`, performs a full repository scan (equivalent to scanning all files). /// - If `target` is `Some(target_str)`, resolves the target using the targets module and creates zip from those files. /// The target string can be a comma-separated list of files, directories, globs, or git selectors. @@ -53,8 +53,9 @@ pub fn create_zip_from_target>( let current_dir = env::current_dir()?; let result = crate::targets::resolve_targets(target_str) .map_err(|e| format!("Failed to resolve targets: {}", e))?; - - result.files + + result + .files .iter() .filter_map(|file| { if !file.exists() || !file.is_file() { @@ -62,17 +63,13 @@ pub fn create_zip_from_target>( } match file.strip_prefix(¤t_dir) { Ok(relative) => Some((file.clone(), relative.to_path_buf())), - Err(_) => { - Some((file.clone(), file.clone())) - } + Err(_) => Some((file.clone(), file.clone())), } }) .collect() } else { let directory = Path::new("."); - let walker = WalkBuilder::new(directory) - .standard_filters(true) - .build(); + let walker = WalkBuilder::new(directory).standard_filters(true).build(); let mut files = Vec::new(); for result in walker { @@ -99,7 +96,7 @@ pub fn create_zip_from_target>( for (path, relative_path) in files_to_zip { let is_excluded = glob_set.is_match(&path); - + if (path.is_file() || path.is_dir()) && !is_excluded { if path.is_file() { zip.start_file(relative_path.to_string_lossy(), options)?; @@ -152,13 +149,12 @@ pub fn create_path_if_not_exists>(path: P) -> io::Result<()> { Ok(()) } - pub fn is_git_repo(dir: &str) -> Result { let git_path = Path::new(dir).join(".git"); if git_path.exists() { return Ok(true); } - + // Fall back to the more expensive discover method for cases like: // - We're in a subdirectory of a git repo // - .git is a file (worktrees, submodules) @@ -183,9 +179,10 @@ pub fn delete_directory>(path: P) -> io::Result<()> { } pub fn get_current_working_directory() -> Option { - env::current_dir() - .ok() - .and_then(|path| path.file_name().map(|name| name.to_string_lossy().to_string())) + env::current_dir().ok().and_then(|path| { + path.file_name() + .map(|name| name.to_string_lossy().to_string()) + }) } /// Determine the project name with fallback logic: @@ -227,25 +224,25 @@ fn extract_repo_name_from_url(url: &str) -> Option { // - git@github.com:user/repo.git // - https://github.com/user/repo // - git@github.com:user/repo - + let url = url.trim(); - + let url = url.strip_suffix(".git").unwrap_or(url); - - if let Some(name) = url.split('/').last() { + + if let Some(name) = url.split('/').next_back() { let name = name.trim(); if !name.is_empty() { return Some(name.to_string()); } } - - if let Some(name) = url.split(':').last() { + + if let Some(name) = url.split(':').next_back() { let name = name.trim(); if !name.is_empty() { return Some(name.to_string()); } } - + None } @@ -271,12 +268,23 @@ pub fn get_repo_info(dir: &str) -> Result, git2::Error> { }); // Get the latest commit SHA - let sha = repo.head().ok().and_then(|head| head.peel_to_commit().ok().map(|commit| commit.id().to_string())); + let sha = repo.head().ok().and_then(|head| { + head.peel_to_commit() + .ok() + .map(|commit| commit.id().to_string()) + }); // Get the remote URL (assuming "origin") - let repo_url = repo.find_remote("origin").ok().and_then(|remote| remote.url().map(|url| url.to_string())); + let repo_url = repo + .find_remote("origin") + .ok() + .and_then(|remote| remote.url().map(|url| url.to_string())); - Ok(Some(RepoInfo { branch, repo_url, sha })) + Ok(Some(RepoInfo { + branch, + repo_url, + sha, + })) } pub fn get_status(status: &str) -> &str { @@ -300,4 +308,3 @@ pub struct RepoInfo { pub repo_url: Option, pub sha: Option, } - diff --git a/src/utils/terminal.rs b/src/utils/terminal.rs index 4c726eb..1bb4c4c 100644 --- a/src/utils/terminal.rs +++ b/src/utils/terminal.rs @@ -1,11 +1,11 @@ -use std::io::{self, Write}; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; -use std::{thread, time}; -use std::sync::{Arc, Mutex}; use crate::utils; use regex::Regex; +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; +use std::{thread, time}; +use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; -pub fn show_progress_bar(progress: f32) -> () { +pub fn show_progress_bar(progress: f32) { let total_bar_length = 50; if progress == -1.0 { print!("\r{}", " ".repeat(50)); @@ -27,17 +27,28 @@ pub fn show_progress_bar(progress: f32) -> () { } pub fn show_loading_message(message: &str, stop_signal: Arc>) { - let spinner = vec!["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]; - let spinner_colors = vec![Color::Cyan, Color::Magenta, Color::Yellow, Color::Green]; + let spinner = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]; + let spinner_colors = [Color::Cyan, Color::Magenta, Color::Yellow, Color::Green]; let start_time = time::Instant::now(); let mut i = 0; let mut stdout = StandardStream::stdout(ColorChoice::Always); print!("{} ", message); io::stdout().flush().unwrap(); loop { - stdout.set_color(ColorSpec::new().set_fg(Some(spinner_colors[i % spinner_colors.len()])).set_bg(Some(Color::Black))).unwrap(); + stdout + .set_color( + ColorSpec::new() + .set_fg(Some(spinner_colors[i % spinner_colors.len()])) + .set_bg(Some(Color::Black)), + ) + .unwrap(); let message = message.replace("[T]", &format!("{:.0}", start_time.elapsed().as_secs())); - print!("\r[{}] {}{}", spinner[i % spinner.len()], message, set_text_color("", TerminalColor::Reset)); + print!( + "\r[{}] {}{}", + spinner[i % spinner.len()], + message, + set_text_color("", TerminalColor::Reset) + ); io::stdout().flush().unwrap(); // Sleep for a bit before updating the spinner thread::sleep(time::Duration::from_millis(100)); @@ -53,8 +64,6 @@ pub fn show_loading_message(message: &str, stop_signal: Arc>) { stdout.reset().unwrap(); } - - pub fn set_text_color(txt: &str, color: TerminalColor) -> String { let color_code = match color { TerminalColor::Red => "\x1b[31m", @@ -63,7 +72,7 @@ pub fn set_text_color(txt: &str, color: TerminalColor) -> String { TerminalColor::Yellow => "\x1b[33m", TerminalColor::Reset => "\x1b[0m", }; - return format!("{}{}{}", color_code, txt, "\x1b[0m"); + format!("{}{}{}", color_code, txt, "\x1b[0m") } pub fn show_welcome_message() { @@ -79,7 +88,7 @@ pub fn show_welcome_message() { "#; println!("{}", set_text_color(dog_art, TerminalColor::Green)); -} +} pub fn format_code(code: &str) -> String { let mut formatted_code = String::new(); @@ -89,7 +98,13 @@ pub fn format_code(code: &str) -> String { for capture in regex.captures_iter(code) { if let Some(matched) = capture.get(1) { formatted_code.push_str(&code[last_end..capture.get(0).unwrap().start()]); - formatted_code.push_str(&format!("`{}`", utils::terminal::set_text_color(matched.as_str(), utils::terminal::TerminalColor::Green))); + formatted_code.push_str(&format!( + "`{}`", + utils::terminal::set_text_color( + matched.as_str(), + utils::terminal::TerminalColor::Green + ) + )); last_end = capture.get(0).unwrap().end(); } } @@ -113,9 +128,9 @@ pub fn format_diff(diff: &str) -> String { format!("{}\n", set_text_color(line, TerminalColor::Green)) } else if line.starts_with("@@") { let formatted_text = regex.replace_all(line, |caps: ®ex::Captures| { - set_text_color(&caps[0], TerminalColor::Blue) + set_text_color(&caps[0], TerminalColor::Blue) }); - format!("{}\n", formatted_text) + format!("{}\n", formatted_text) } else if line.starts_with("-") { format!("{}\n", set_text_color(line, TerminalColor::Red)) } else if line.starts_with("+") { @@ -135,7 +150,11 @@ pub fn clear_line(length: usize) { } pub fn clear_previous_line() { - print!("\r{}{}", utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset), " ".repeat(100)); + print!( + "\r{}{}", + utils::terminal::set_text_color("", utils::terminal::TerminalColor::Reset), + " ".repeat(100) + ); } pub fn print_with_pagination(str: &str) { @@ -143,7 +162,7 @@ pub fn print_with_pagination(str: &str) { let mut lines = str.lines(); let mut buffer = String::new(); let stdin = io::stdin(); - let message ="-- More -- (Press Enter to continue, Ctrl+C to exit)"; + let message = "-- More -- (Press Enter to continue, Ctrl+C to exit)"; loop { clear_line(message.len()); @@ -154,7 +173,6 @@ pub fn print_with_pagination(str: &str) { clear_line(message.len()); return; } - } print!("{}", message); @@ -163,7 +181,6 @@ pub fn print_with_pagination(str: &str) { buffer.clear(); stdin.read_line(&mut buffer).unwrap(); - print!("\x1B[2K\x1B[1A"); stdout.flush().unwrap(); } @@ -182,30 +199,44 @@ pub fn ask_yes_no(question: &str, should_default: bool) -> bool { loop { print!("{} (y/n): ", question); io::stdout().flush().unwrap(); - + let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); - + match input.trim().to_lowercase().as_str() { "y" | "yes" => return true, "n" | "no" => return false, - _ => if should_default { - return true; - } else { - println!("Please answer with yes/y or no/n"); + _ => { + if should_default { + return true; + } else { + println!("Please answer with yes/y or no/n"); + } } } } } pub fn print_table(table: Vec>, page: Option, total_pages: Option) { - let columns = table.iter().enumerate().fold(vec![vec![]; table[0].len()], |mut acc, (_i, row)| { - for (j, cell) in row.iter().enumerate() { - acc[j].push(cell.clone()); - } - acc - }); - let column_lengths = columns.iter().map(|col| col.iter().map(|cell| cell.len()).max_by(|a, b| a.cmp(b)).unwrap_or(0)).collect::>(); + let columns = + table + .iter() + .enumerate() + .fold(vec![vec![]; table[0].len()], |mut acc, (_i, row)| { + for (j, cell) in row.iter().enumerate() { + acc[j].push(cell.clone()); + } + acc + }); + let column_lengths = columns + .iter() + .map(|col| { + col.iter() + .map(|cell| cell.len()) + .max_by(|a, b| a.cmp(b)) + .unwrap_or(0) + }) + .collect::>(); for (j, row) in table.iter().enumerate() { for (i, cell) in row.iter().enumerate() { print!("{:>, page: Option, total_pages: Opti } } - pub enum TerminalColor { Reset, Red, Green, Blue, Yellow, -} \ No newline at end of file +} diff --git a/src/wait.rs b/src/wait.rs index c0ce3e7..8a7cccc 100644 --- a/src/wait.rs +++ b/src/wait.rs @@ -1,7 +1,6 @@ -use crate::utils; use crate::config::Config; use crate::scanners::blast; - +use crate::utils; pub fn run(config: &Config, scan_id: Option, project_id: Option) { let project_name = match utils::generic::get_current_working_directory() { @@ -12,7 +11,8 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) } }; - let scans_result = utils::api::query_scan_list(&config.get_url(), Some(&project_name), Some(1), None); + let scans_result = + utils::api::query_scan_list(&config.get_url(), Some(&project_name), Some(1), None); let scans: Vec = match scans_result { Ok(result) => result.scans.unwrap_or_default(), Err(e) => { @@ -23,7 +23,7 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) Check out our docs at https://docs.corgea.app/install_cli#login-with-the-cli - Error details: {}", + Error details: {}", e ); std::process::exit(1); @@ -41,21 +41,24 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) } }; (scan_id.to_string(), processed) - }, - None => { - match scans.get(0) { - Some(scan) => (scan.id.clone(), scan.status == "Complete"), - None => { - eprintln!("Error querying scan list"); - std::process::exit(1); - } - } } + None => match scans.first() { + Some(scan) => (scan.id.clone(), scan.status == "Complete"), + None => { + eprintln!("Error querying scan list"); + std::process::exit(1); + } + }, }; let scan_url = match &project_id { Some(pid) => format!("{}/project/{}/?scan_id={}", config.get_url(), pid, scan_id), - None => format!("{}/project/{}?scan_id={}", config.get_url(), project_name, scan_id), + None => format!( + "{}/project/{}?scan_id={}", + config.get_url(), + project_name, + scan_id + ), }; if !processed { @@ -70,7 +73,7 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) ); blast::wait_for_scan(config, &scan_id); } else { - print!("Scan has been processed successfully!\n"); + println!("Scan has been processed successfully!"); } match blast::report_scan_status(&config.get_url(), &project_name) { @@ -79,7 +82,7 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) "\n\nYou can view the scan results at the following link:\n{}", utils::terminal::set_text_color(&scan_url, utils::terminal::TerminalColor::Green) ); - }, + } Err(e) => { eprintln!( "\n\n{}\n\n\ @@ -89,7 +92,10 @@ pub fn run(config: &Config, scan_id: Option, project_id: Option) - Server URL: {}\n\ - Error details: {}\n", utils::terminal::set_text_color( - &format!("Failed to report the scan status for project: '{}'.", project_name), + &format!( + "Failed to report the scan status for project: '{}'.", + project_name + ), utils::terminal::TerminalColor::Red ), utils::terminal::set_text_color(&scan_url, utils::terminal::TerminalColor::Blue),