use super::*;
use crate::review::diff::Status;
pub fn run(cx: &Cx, out: &mut Vec<Finding>) {
debug_leftovers(cx, out);
secrets(cx, out);
conflict_markers(cx, out);
env_files(cx, out);
lockfiles(cx, out);
tests_missing(cx, out);
tests_changed(cx, out);
}
fn dir_of(path: &str) -> &str {
path.rsplit_once('/').map_or("", |(d, _)| d)
}
fn debug_needles(ext: &str) -> &'static [(&'static str, bool, &'static str)] {
match ext {
"php" => &[
("dd(", false, "dumps and stops the request"),
("ddd(", false, "dumps and stops the request"),
("dump(", false, "prints into the response"),
("ray(", false, "sends data to the Ray debugger"),
("var_dump(", false, "prints into the response"),
("print_r(", false, "prints into the response"),
],
"js" | "jsx" | "ts" | "tsx" | "vue" | "svelte" | "mjs" => &[
("console.log(", false, "logs to the browser console"),
("console.debug(", false, "logs to the browser console"),
("console.trace(", false, "logs to the browser console"),
("debugger", true, "pauses execution when DevTools is open"),
],
"rs" => &[
("dbg!(", false, "prints to stderr and returns its argument"),
("todo!(", false, "panics when reached"),
("unimplemented!(", false, "panics when reached"),
],
_ => &[],
}
}
fn debug_leftovers(cx: &Cx, out: &mut Vec<Finding>) {
for f in &cx.diff.files {
if f.status == Status::Deleted {
continue;
}
let ext = ext(&f.path);
let needles = debug_needles(&ext);
if needles.is_empty() {
continue;
}
let mut shown = 0;
let mut extra = 0;
for l in f.added() {
if is_comment(&l.text) {
continue;
}
let hit = needles.iter().find_map(|&(n, word, why)| {
let at = if word { find_word(&l.text, n) } else { find_call(&l.text, n) };
at.map(|i| (i, n, why))
});
let Some((i, n, why)) = hit else { continue };
if shown >= 3 {
extra += 1;
continue;
}
shown += 1;
let name = n.trim_end_matches('(');
out.push(
Finding::new("GEN001", Level::Warn, format!("`{name}` left in the code"))
.at_range(&f.path, l, i, i + n.len(), &format!("{why}; is this still wanted?"))
.help("remove it before merging, or keep a proper logger call if the output is meant to stay"),
);
}
if extra > 0
&& let Some(last) = out.last_mut()
{
last.note.push(format!("{extra} more debugging call(s) in this file"));
}
}
}
fn token_kind(t: &str) -> Option<&'static str> {
let upper_digit = |s: &str| s.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
if (t.starts_with("AKIA") || t.starts_with("ASIA")) && t.len() == 20 && upper_digit(t) {
return Some("AWS access key id");
}
if ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"].iter().any(|p| t.starts_with(p)) && t.len() >= 36 {
return Some("GitHub token");
}
if t.starts_with("github_pat_") && t.len() >= 40 {
return Some("GitHub token");
}
if t.starts_with("xox") && t.len() >= 20 && t.as_bytes().get(3).is_some_and(|b| b"baprs".contains(b)) && t.as_bytes().get(4) == Some(&b'-') {
return Some("Slack token");
}
if (t.starts_with("sk_live_") || t.starts_with("rk_live_")) && t.len() >= 20 {
return Some("Stripe live key");
}
if t.starts_with("AIza") && t.len() == 39 {
return Some("Google API key");
}
None
}
const SECRET_KEYS: &[&str] = &["password", "passwd", "secret", "api_key", "apikey", "api-key", "token", "private_key", "access_key"];
const PLACEHOLDERS: &[&str] = &["xxx", "changeme", "change_me", "example", "your", "placeholder", "dummy", "<", ">", "${", "{{", "...", "****", "env(", "getenv", "process."];
fn assigned_secret(text: &str) -> Option<(usize, usize)> {
let lower = text.to_lowercase();
for key in SECRET_KEYS {
for (at, _) in lower.match_indices(key) {
let mut i = at + key.len();
let rest = &text[i..];
let skipped = rest.len() - rest.trim_start_matches(['"', '\'', ']', ')', ' ']).len();
i += skipped;
let rest = &text[i..];
let Some(after) = rest.strip_prefix("=>").or_else(|| rest.strip_prefix('=')).or_else(|| rest.strip_prefix(':')) else { continue };
let from = text.len() - after.len();
let Some((s, e, _)) = string_at(text, from) else { continue };
if !text[from..s].trim().is_empty() {
continue; }
let inner = &text[s + 1..e - 1];
let lower_inner = inner.to_lowercase();
if inner.len() >= 8
&& !inner.contains(char::is_whitespace)
&& inner.chars().any(|c| c.is_ascii_digit())
&& inner.chars().any(|c| c.is_ascii_alphabetic())
&& !inner.starts_with('$')
&& !PLACEHOLDERS.iter().any(|p| lower_inner.contains(p))
{
return Some((s, e));
}
}
}
None
}
fn secret_in(text: &str, check_assignments: bool) -> Option<(usize, usize, &'static str)> {
if let Some(s) = text.find("-----BEGIN ")
&& text.contains("PRIVATE KEY-----")
{
return Some((s, text.len(), "private key"));
}
let mut start = None;
for (i, c) in text.char_indices().chain(std::iter::once((text.len(), ' '))) {
let tok = c.is_ascii_alphanumeric() || c == '_' || c == '-';
match (tok, start) {
(true, None) => start = Some(i),
(false, Some(s)) => {
if let Some(k) = token_kind(&text[s..i]) {
return Some((s, i, k));
}
start = None;
}
_ => {}
}
}
if check_assignments {
return assigned_secret(text).map(|(s, e)| (s, e, "hard-coded credential"));
}
None
}
fn secrets(cx: &Cx, out: &mut Vec<Finding>) {
for f in &cx.diff.files {
let name = file_name(&f.path);
let skip = f.status == Status::Deleted
|| name.ends_with(".lock")
|| name.ends_with("-lock.json")
|| name.ends_with(".md")
|| name.starts_with(".env.example")
|| name.starts_with(".env.sample");
if skip {
continue;
}
let assignments = !is_test_path(&f.path) && !f.path.contains("/factories/") && !f.path.contains("/seeders/");
for l in f.added() {
if let Some((s, e, kind)) = secret_in(&l.text, assignments) {
out.push(
Finding::new("GEN002", Level::Risk, format!("possible {kind} in the code"))
.at_range(&f.path, l, s, e, "looks like a secret")
.note("anything pushed is in git history for good, even if a later commit removes it")
.help("revoke or rotate it first, then read it from the environment or a secret store instead"),
);
break; }
}
}
}
fn conflict_markers(cx: &Cx, out: &mut Vec<Finding>) {
for f in &cx.diff.files {
if let Some(l) = f.added().find(|l| {
["<<<<<<<", ">>>>>>>"].iter().any(|m| l.text.strip_prefix(m).is_some_and(|r| r.is_empty() || r.starts_with(' ')))
}) {
out.push(
Finding::new("GEN003", Level::Risk, "unresolved merge conflict marker")
.at(&f.path, l, &l.text.clone(), "left over from a merge")
.help("resolve the conflict and delete the `<<<<<<<`, `=======` and `>>>>>>>` lines"),
);
}
}
}
fn env_files(cx: &Cx, out: &mut Vec<Finding>) {
for f in &cx.diff.files {
let name = file_name(&f.path);
let templates = [".env.example", ".env.sample", ".env.dist", ".env.template", ".env.testing", ".env.ci"];
if f.status == Status::Deleted || !(name == ".env" || name.starts_with(".env.")) || templates.contains(&name) {
continue;
}
out.push(
Finding::new("GEN006", Level::Risk, format!("`{name}` is part of this change"))
.note("env files hold real credentials and per-machine settings; they should be ignored by git")
.help(format!("remove it from the commit (`git rm --cached {}`), add it to .gitignore, and rotate anything that was in it", f.path)),
);
}
}
const LOCKS: &[(&str, &[&str])] = &[
("composer.json", &["composer.lock"]),
("package.json", &["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb", "npm-shrinkwrap.json"]),
("Cargo.toml", &["Cargo.lock"]),
];
fn affects_lock(manifest: &str, text: &str) -> bool {
let t = text.trim();
match manifest {
"composer.json" | "package.json" => {
let Some((key, value)) = t.split_once("\":") else { return false };
let key = key.trim_start_matches('"');
let value = value.trim().trim_start_matches('"');
let versionish = value.chars().next().is_some_and(|c| c.is_ascii_digit() || "^~<>*=".contains(c))
|| ["latest", "workspace:", "npm:", "github:", "dev-"].iter().any(|p| value.starts_with(p));
if manifest == "composer.json" {
(key.contains('/') || key == "php" || key.starts_with("ext-")) && versionish
} else {
versionish && !["node", "npm", "pnpm", "yarn"].contains(&key)
}
}
_ => {
let Some((key, value)) = t.split_once('=') else { return false };
let key = key.trim();
let value = value.trim();
if ["edition", "rust-version", "description", "license", "name", "authors", "keywords", "categories", "readme", "exclude"].contains(&key) {
return false;
}
key == "version"
|| value.contains("version")
|| value.starts_with('"') && value[1..].chars().next().is_some_and(|c| c.is_ascii_digit() || "^~=<>*".contains(c))
}
}
}
fn lockfiles(cx: &Cx, out: &mut Vec<Finding>) {
for f in &cx.diff.files {
let name = file_name(&f.path);
let Some((_, locks)) = LOCKS.iter().find(|(m, _)| *m == name) else { continue };
if f.status == Status::Deleted {
continue;
}
let dir = dir_of(&f.path);
let lock_changed = cx.diff.files.iter().any(|o| {
locks.contains(&file_name(&o.path)) && {
let od = dir_of(&o.path);
od.is_empty() || dir == od || dir.starts_with(&format!("{od}/"))
}
});
if lock_changed {
continue;
}
let hit = f.added().chain(f.removed()).find(|l| affects_lock(name, &l.text));
let Some(l) = hit else { continue };
let (cmd, fix) = match name {
"composer.json" => ("composer validate".to_string(), "composer update <package>` (or `composer update --lock`) and commit composer.lock".to_string()),
"Cargo.toml" => ("cargo build --locked".to_string(), "cargo update -p <crate>` (or just `cargo build`) and commit Cargo.lock".to_string()),
_ => match cx.node().map(|n| n.pm) {
Some(crate::review::project::Pm::Pnpm) => ("pnpm install --frozen-lockfile".into(), "pnpm install` and commit pnpm-lock.yaml".into()),
Some(crate::review::project::Pm::Yarn) => ("yarn install --immutable".into(), "yarn install` and commit yarn.lock".into()),
Some(crate::review::project::Pm::Bun) => ("bun install --frozen-lockfile".into(), "bun install` and commit the lock file".into()),
_ => ("npm ci".into(), "npm install` and commit package-lock.json".into()),
},
};
out.push(
Finding::new("GEN005", Level::Warn, format!("`{name}` changed but its lock file did not"))
.at(&f.path, l, "", "this changes the dependencies")
.note("installs from the lock file will not pick this up, so CI and production can run different versions than you did")
.test(format!("`{cmd}` must succeed: it fails when the manifest and the lock file disagree"))
.help(format!("run `{fix} (unless this repository deliberately does not commit it)")),
);
}
}
fn is_source(path: &str) -> bool {
if is_test_path(path) || path.ends_with(".d.ts") || path.contains("node_modules/") || path.contains("database/migrations/") {
return false;
}
let code = matches!(ext(path).as_str(), "php" | "rs" | "js" | "jsx" | "ts" | "tsx" | "vue" | "svelte");
code && (path.starts_with("app/") || path.contains("src/") || path.starts_with("resources/js/") || path.starts_with("routes/") || path.starts_with("lib/"))
}
fn has_inline_rust_tests(f: &FileDiff) -> bool {
ext(&f.path) == "rs" && f.added().any(|l| l.text.contains("#[test]") || l.text.contains("#[cfg(test)]") || l.text.contains("::test]"))
}
fn suite_commands(cx: &Cx) -> Vec<String> {
let mut cmds = Vec::new();
if let Some(l) = cx.laravel() {
cmds.push(l.test_cmd(None));
}
if let Some(t) = cx.tauri() {
cmds.push(format!("cargo test --manifest-path {}", t.path("Cargo.toml")));
} else if cx.project.rust {
cmds.push("cargo test".to_string());
}
if let Some(c) = cx.node().and_then(|n| n.test_cmd(None)) {
cmds.push(c);
}
cmds
}
fn tests_missing(cx: &Cx, out: &mut Vec<Finding>) {
let live = || cx.diff.files.iter().filter(|f| f.status != Status::Deleted);
if live().any(|f| is_test_path(&f.path) || has_inline_rust_tests(f)) {
return;
}
let sources: Vec<_> = live().filter(|f| is_source(&f.path)).collect();
let added: usize = sources.iter().map(|f| f.added_count()).sum();
if added < 20 {
return;
}
let mut f = Finding::new("GEN004", Level::Note, format!("{} source file(s) changed (+{added} lines) and no tests did", sources.len()))
.note("nothing in this change pins the new behaviour down, so a later change can break it unnoticed")
.check("which behaviour is new or fixed here? a bug fix should come with a test that fails without it");
for c in suite_commands(cx) {
f = f.test(format!("run the existing suite to see nothing broke: `{c}`"));
}
out.push(f);
}
fn tests_changed(cx: &Cx, out: &mut Vec<Finding>) {
let mut php = Vec::new();
let mut js = Vec::new();
let mut rust = false;
for f in cx.diff.files.iter().filter(|f| f.status != Status::Deleted) {
let by_ext = ext(&f.path);
if has_inline_rust_tests(f) || (by_ext == "rs" && is_test_path(&f.path)) {
rust = true;
} else if is_test_path(&f.path) {
match by_ext.as_str() {
"php" => php.push(f.path.as_str()),
"js" | "jsx" | "ts" | "tsx" | "mjs" => js.push(f.path.as_str()),
_ => {}
}
}
}
let total = php.len() + js.len() + usize::from(rust);
if total == 0 {
return;
}
let mut f = Finding::new("GEN007", Level::Note, "tests were added or changed: run them")
.check("a new test should fail without the change it covers (stash the fix and run it once)");
if !php.is_empty() {
let paths = php.iter().take(6).copied().collect::<Vec<_>>().join(" ");
let cmd = match cx.laravel() {
Some(l) => l.test_cmd(Some(&paths)),
None => format!("./vendor/bin/phpunit {paths}"),
};
f = f.test(format!("`{cmd}`"));
}
if !js.is_empty()
&& let Some(n) = cx.node()
&& let Some(cmd) = n.test_cmd(Some(&js.iter().take(6).copied().collect::<Vec<_>>().join(" ")))
{
f = f.test(format!("`{cmd}`"));
}
if rust {
f = f.test(match cx.tauri() {
Some(t) => format!("`cargo test --manifest-path {}`", t.path("Cargo.toml")),
None => "`cargo test`".to_string(),
});
}
out.push(f);
}
#[cfg(test)]
mod tests {
use super::super::testing::*;
#[test]
fn flags_debug_calls_but_not_lookalikes() {
let f = review(&[add("app/A.php", &["<?php", "$x = add(1);", " dd($x);", "// dd($y);", "$c->dump();"])]);
assert_eq!(f.iter().filter(|f| f.code == "GEN001").count(), 2);
let first = get(&f, "GEN001");
let s = first.span.as_ref().unwrap();
assert_eq!((s.file.as_str(), s.line, s.col, s.len), ("app/A.php", 3, 5, 3));
let js = review(&[add("src/a.ts", &["console.log(x);", "const debuggerTool = 1;"])]);
assert_eq!(js.iter().filter(|f| f.code == "GEN001").count(), 1);
}
#[test]
fn caps_debug_findings_per_file() {
let lines: Vec<String> = (0..6).map(|i| format!("dbg!({i});")).collect();
let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
let f = review(&[add("src/a.rs", &refs)]);
assert_eq!(f.iter().filter(|f| f.code == "GEN001").count(), 3);
assert!(f.iter().any(|f| f.note.iter().any(|n| n.contains("3 more"))));
}
#[test]
fn finds_secrets_and_ignores_placeholders() {
let f = review(&[add(
"src/config.ts",
&["const key = 'AKIAIOSFODNN7EXAMPLE';", "const t = { password: 'hunter2hunter2' };", "const ok = { password: 'changeme123' };"],
)]);
assert_eq!(f.iter().filter(|f| f.code == "GEN002").count(), 1); assert!(get(&f, "GEN002").title.contains("AWS"));
let g = review(&[add("src/c.ts", &["const t = { password: 'hunter2hunter2' };"])]);
assert!(get(&g, "GEN002").title.contains("credential"));
let none = review(&[add("src/c.ts", &["const t = { password: process.env.X };", "const u = { password: 'changeme123' };"])]);
assert!(!has(&none, "GEN002"));
let tests = review(&[add("tests/a.php", &["'password' => 'password123',"])]);
assert!(!has(&tests, "GEN002"));
assert!(has(&review(&[add("k.pem", &["-----BEGIN RSA PRIVATE KEY-----"])]), "GEN002"));
}
#[test]
fn flags_conflict_markers_and_env_files() {
let f = review(&[add("a.txt", &["<<<<<<< HEAD", "x", ">>>>>>> main"]), add(".env", &["APP_KEY=base64:abc"]), add(".env.example", &["APP_KEY="])]);
assert!(has(&f, "GEN003"));
let env: Vec<_> = f.iter().filter(|f| f.code == "GEN006").collect();
assert_eq!(env.len(), 1);
assert!(env[0].title.contains("`.env`"));
}
#[test]
fn manifest_without_lock_is_flagged_and_with_lock_is_not() {
let manifest = edit("composer.json", &["\"require\": {", "-\"laravel/framework\": \"^10.0\",", "+\"laravel/framework\": \"^11.0\","]);
let f = review(std::slice::from_ref(&manifest));
assert!(has(&f, "GEN005"));
assert!(get(&f, "GEN005").test[0].contains("composer validate"));
let with_lock = review(&[manifest, edit("composer.lock", &["-x", "+y"])]);
assert!(!has(&with_lock, "GEN005"));
assert!(!has(&review(&[edit("package.json", &["-\"name\": \"a\",", "+\"name\": \"b\","])]), "GEN005"));
assert!(has(&review(&[edit("src-tauri/Cargo.toml", &["-tauri = \"2.0\"", "+tauri = \"2.1\""])]), "GEN005"));
}
#[test]
fn missing_and_changed_tests() {
let big: Vec<String> = (0..25).map(|i| format!("$a{i} = {i};")).collect();
let refs: Vec<&str> = big.iter().map(String::as_str).collect();
let f = review(&[add("app/Services/Billing.php", &refs)]);
assert!(has(&f, "GEN004"));
let g = review(&[add("app/Services/Billing.php", &refs), add("tests/Feature/BillingTest.php", &["<?php"])]);
assert!(!has(&g, "GEN004"));
assert!(get(&g, "GEN007").test[0].contains("tests/Feature/BillingTest.php"));
let rs = review(&[add("src/a.rs", &["#[cfg(test)]", "mod tests {}"])]);
assert!(has(&rs, "GEN007"));
}
}