rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Rules that apply to any repository.

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)
}

// --- GEN001: debugging calls left in -------------------------------------------------------

/// Calls that print or stop, by language: (text, whether it is a bare word, what it does).
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"));
        }
    }
}

// --- GEN002: secrets -----------------------------------------------------------------------

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."];

/// A string literal assigned to something named like a secret.
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..];
            // Skip the end of a quoted key or an index like `['password']`.
            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; // something other than space before the quote: not a plain literal
            }
            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;
        }
        // Dummy passwords in tests and factories are everywhere; real token formats still count.
        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; // one per file is enough to act on
            }
        }
    }
}

// --- GEN003: conflict markers --------------------------------------------------------------

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"),
            );
        }
    }
}

// --- GEN006: .env files --------------------------------------------------------------------

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)),
        );
    }
}

// --- GEN005: manifest and lock file out of step --------------------------------------------

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"]),
];

/// Whether a changed line of a manifest is one that changes what the lock file records.
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)")),
        );
    }
}

// --- GEN004 / GEN007: tests ----------------------------------------------------------------

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]"))
}

/// The commands that run each kind of test in this project.
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); // one per file
        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"));
    }
}