rustimal 0.8.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Laravel rules: schema changes, routes and who may call them, mass assignment, raw SQL,
//! Blade output, validation, configuration, queues and views.

use super::*;
use crate::review::diff::{Hunk, Kind, Status};

pub fn run(cx: &Cx, out: &mut Vec<Finding>) {
    let Some(l) = cx.laravel() else { return };
    migrations(cx, &l, out);
    routes(cx, &l, out);
    models(cx, &l, out);
    raw_sql(cx, out);
    blade(cx, out);
    validation(cx, out);
    env_usage(cx, &l, out);
    jobs_and_schedule(cx, &l, out);
    authorization(cx, &l, out);
    composer(cx, &l, out);
    views(cx, out);
}

/// The files that still exist after the change.
fn live<'a>(cx: &'a Cx) -> impl Iterator<Item = &'a FileDiff> {
    cx.diff.files.iter().filter(|f| f.status != Status::Deleted)
}

/// Added lines with the hunk around them: (hunk, index in it, line).
fn added_in(f: &FileDiff) -> impl Iterator<Item = (&Hunk, usize, &Line)> {
    f.hunks
        .iter()
        .flat_map(|h| h.lines.iter().enumerate().filter(|(_, l)| l.kind == Kind::Added).map(move |(i, l)| (h, i, l)))
}

// --- migrations ----------------------------------------------------------------------------

fn is_migration(path: &str) -> bool {
    path.starts_with("database/migrations/") && ext(path) == "php"
}

const DESTRUCTIVE: &[(&str, Level, &str)] = &[
    ("dropColumn(", Level::Risk, "drops a column and everything in it"),
    ("dropIfExists(", Level::Risk, "drops a table and everything in it"),
    ("Schema::drop(", Level::Risk, "drops a table and everything in it"),
    ("truncate(", Level::Risk, "deletes every row"),
    ("dropSoftDeletes(", Level::Risk, "drops `deleted_at`: soft-deleted rows come back to life"),
    ("renameColumn(", Level::Warn, "renames a column: code still using the old name breaks"),
    ("Schema::rename(", Level::Warn, "renames a table: code still using the old name breaks"),
    ("->change()", Level::Warn, "alters a column in place: existing values may be truncated or converted"),
    ("dropForeign(", Level::Warn, "drops a foreign key: nothing enforces the relation afterwards"),
    ("dropUnique(", Level::Warn, "drops a unique index: duplicates become possible"),
    ("dropIndex(", Level::Warn, "drops an index: queries that relied on it get slower"),
    ("DB::statement(", Level::Warn, "runs raw SQL: check it works on every database you use, tests included"),
    ("DB::unprepared(", Level::Warn, "runs raw SQL: check it works on every database you use, tests included"),
];

/// Whether the lines before an added line put it inside `down()` rather than `up()`.
fn in_down(before: &[Line]) -> bool {
    before
        .iter()
        .rev()
        .filter(|l| l.kind != Kind::Removed)
        .find_map(|l| {
            if l.text.contains("function down") { Some(true) } else { l.text.contains("function up").then_some(false) }
        })
        .unwrap_or(false)
}

/// The `function down` line of a `down()` with nothing in it.
fn empty_down<'a>(lines: &[&'a Line]) -> Option<&'a Line> {
    let at = lines.iter().position(|l| l.text.contains("function down"))?;
    let head = lines[at].text.replace(' ', "");
    if head.ends_with("{}") {
        return Some(lines[at]);
    }
    for l in &lines[at + 1..] {
        match l.text.trim() {
            "" | "{" => {}
            "}" => return Some(lines[at]),
            t if is_comment(t) => {}
            _ => return None,
        }
    }
    None
}

fn migrations(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| is_migration(&f.path)) {
        let added_file = f.status == Status::Added;
        let mut shown = 0;
        for (h, i, line) in added_in(f) {
            if is_comment(&line.text) || in_down(&h.lines[..i]) || shown >= 5 {
                continue;
            }
            let hit = DESTRUCTIVE.iter().find(|(needle, ..)| {
                // `dropIfExists` right before `create` is the usual guard of a new migration.
                !(added_file && *needle == "dropIfExists(" && f.added().any(|a| a.text.contains("Schema::create(")))
                    && line.text.contains(needle)
            });
            let Some(&(needle, level, what)) = hit else { continue };
            shown += 1;
            out.push(
                Finding::new("LAR001", level, if level == Level::Risk { "destructive migration" } else { "migration needs care" })
                    .at(&f.path, line, needle, what)
                    .check("is the data copied elsewhere or truly unused? during a deploy, does the old code still read or write it while this runs?")
                    .test(format!("`{}` prints the SQL it will run", l.artisan("migrate --pretend")))
                    .test(format!("on a copy of real data: `{}`, use the app, then `{}`", l.artisan("migrate"), l.artisan("migrate:rollback --step=1")))
                    .help("expand, then contract: first ship code that no longer depends on it, drop or rename in a later release"),
            );
        }

        if matches!(f.status, Status::Modified | Status::Renamed)
            && let Some(first) = f.added().find(|a| !is_comment(&a.text) && !a.text.trim().is_empty())
        {
            out.push(
                Finding::new("LAR002", Level::Warn, "an existing migration was edited")
                    .at(&f.path, first, "", "will not run where this migration already ran")
                    .note("staging, production, CI caches and your teammates keep the old schema: `migrate` skips files it has already run")
                    .test(format!("`{}` shows whether it has run; on a database that ran the old version, `{}` changes nothing", l.artisan("migrate:status"), l.artisan("migrate")))
                    .help("unless it has never left your machine, add a new migration that alters the table"),
            );
        }

        if added_file {
            let lines: Vec<&Line> = f.added().collect();
            if let Some(line) = lines.iter().find(|a| a.text.contains("Schema::")).or(lines.first()) {
                out.push(
                    Finding::new("LAR003", Level::Note, format!("new migration `{}`", file_name(&f.path)))
                        .at(&f.path, line, "", "schema change")
                        .check("a NOT NULL column without a default fails on a table that already has rows; large tables can lock while altering")
                        .check("foreign keys: is `onDelete` what you want? columns you filter or join on: are they indexed?")
                        .test(format!("`{}` and read the SQL", l.artisan("migrate --pretend")))
                        .test(format!("`{}`, then `{}`, then migrate again: all three must succeed", l.artisan("migrate"), l.artisan("migrate:rollback --step=1")))
                        .test(format!("on a throwaway database: `{}` builds everything from nothing", l.artisan("migrate:fresh --seed"))),
                );
            }
            if let Some(line) = empty_down(&lines) {
                out.push(
                    Finding::new("LAR003", Level::Warn, "`down()` is empty")
                        .at(&f.path, line, "function down", "rollback will not undo this migration")
                        .note("`migrate:rollback` reports success but leaves the schema changed, and migrating again then fails")
                        .help("reverse what `up()` does, or remove `down()` if this migration is one-way on purpose"),
                );
            }
        }
    }
}

// --- routes --------------------------------------------------------------------------------

const MUTATING: &[&str] = &["post", "put", "patch", "delete", "any", "match", "resource", "apiResource"];
const READING: &[&str] = &["get", "view", "redirect", "fallback", "resources", "singleton"];
const GUARDS: &[&str] = &["middleware(", "auth", "can:", "->can(", "sanctum", "verified"];

/// `Route::post('/x', ...)` on a line: (verb, uri, byte offset).
fn route_call(text: &str) -> Option<(&str, String, usize)> {
    let at = text.find("Route::")?;
    let rest = &text[at + 7..];
    let verb = &rest[..rest.find('(')?];
    if !MUTATING.contains(&verb) && !READING.contains(&verb) {
        return None;
    }
    let mut from = at + 7 + verb.len();
    // `match(['get', 'post'], '/x', ...)`: the address comes after the list of methods.
    if verb == "match" {
        from += text[from..].find(']').unwrap_or(0);
    }
    let uri = string_at(text, from).map(|(s, e, _)| text[s + 1..e - 1].to_string()).unwrap_or_default();
    Some((verb, uri, at))
}

fn routes(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    for f in
        live(cx).filter(|f| f.path.starts_with("routes/") && ext(&f.path) == "php" && f.path != "routes/console.php")
    {
        let mut count = 0;
        let mut first: Option<(&Line, String)> = None;
        let mut unguarded = 0;
        for (h, _, line) in added_in(f) {
            if is_comment(&line.text) {
                continue;
            }
            let Some((verb, uri, at)) = route_call(&line.text) else { continue };
            count += 1;
            first.get_or_insert((line, uri.clone()));
            // A guard can sit on the route or on a group around it; all we can see is the hunk.
            let guarded = h
                .lines
                .iter()
                .filter(|x| x.kind != Kind::Removed)
                .any(|x| !is_comment(&x.text) && GUARDS.iter().any(|g| x.text.contains(g)));
            if !MUTATING.contains(&verb) || guarded || unguarded >= 5 {
                continue;
            }
            unguarded += 1;
            let filter = uri.trim_start_matches('/').split('/').next().unwrap_or("");
            out.push(
                Finding::new("LAR004", Level::Warn, format!("`{} {uri}` changes data and no auth middleware is in sight", verb.to_uppercase()))
                    .at(&f.path, line, &line.text[at..at + 7 + verb.len()], "no `middleware(...)` near this route")
                    .note("it may be protected by a group further up, or by RouteServiceProvider / bootstrap/app.php: verify, do not assume")
                    .test(format!("`{}` and read the Middleware column", l.artisan(&format!("route:list -v --path={filter}"))))
                    .test("send the request logged out (expect 401 or a login redirect) and as a user who should not be allowed (expect 403)"),
            );
        }
        if let Some((line, uri)) = first {
            let filter = uri.trim_start_matches('/').split('/').next().unwrap_or("");
            out.push(
                Finding::new("LAR004", Level::Note, format!("{count} route(s) added or changed"))
                    .at(&f.path, line, "", "first of them")
                    .check("order matters: an earlier `{param}` route can swallow a new fixed path such as `/x/create`")
                    .test(format!("`{}`", l.artisan(&format!("route:list --path={filter}"))))
                    .test("call each with valid input, a missing record (expect 404) and another user's record id (expect 403 or 404)"),
            );
        }
    }
}

// --- models --------------------------------------------------------------------------------

fn models(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| {
        ext(&f.path) == "php"
            && (f.path.starts_with("app/Models/") || f.added().any(|a| a.text.contains("extends Model")))
    }) {
        let model = file_name(&f.path).trim_end_matches(".php");
        for line in f.added() {
            let squeezed = line.text.replace(' ', "");
            if squeezed.contains("$guarded=[]") {
                out.push(
                    Finding::new("LAR005", Level::Risk, format!("`{model}` accepts mass assignment of every column"))
                        .at(&f.path, line, "$guarded", "nothing is guarded")
                        .note("`Model::create($request->all())` would then let a request set any column, such as `is_admin` or `user_id`")
                        .test("send a create and an update request with an extra field (`is_admin=1`, someone else's `user_id`): it must be ignored")
                        .help("list what may be assigned in `$fillable`, and pass `$request->validated()` rather than `all()`"),
                );
            }
        }
        if let Some(line) = f.added().find(|a| a.text.contains("$fillable")) {
            out.push(
                Finding::new("LAR005", Level::Warn, format!("`{model}` changes what can be mass assigned"))
                    .at(&f.path, line, "$fillable", "review every name in this list")
                    .check("roles, ownership, money, status and timestamps should not be settable from a request")
                    .test("send a create and an update request that also sets a sensitive column: it must be ignored or rejected"),
            );
        }
        if let Some(line) = f
            .added()
            .chain(f.removed())
            .find(|a| a.text.contains("$hidden") || a.text.contains("$visible") || a.text.contains("$appends"))
        {
            out.push(
                Finding::new("LAR005", Level::Warn, format!("`{model}` changes what its JSON exposes"))
                    .at(&f.path, line, "", "serialization changed")
                    .test(format!("`{}`, then `App\\Models\\{model}::first()->toArray()`: no password, token or internal field may show", l.artisan("tinker")))
                    .check("API responses, Inertia props and queued payloads all serialize the model"),
            );
        }
    }
}

// --- raw SQL -------------------------------------------------------------------------------

const RAW_SQL: &[&str] = &[
    "DB::raw(",
    "whereRaw(",
    "orWhereRaw(",
    "selectRaw(",
    "orderByRaw(",
    "havingRaw(",
    "groupByRaw(",
    "fromRaw(",
    "DB::select(",
    "DB::statement(",
    "DB::unprepared(",
    "DB::insert(",
    "DB::update(",
    "DB::delete(",
];

/// Whether a PHP variable ends up inside the SQL text of the call at `from`: interpolated
/// into a double-quoted string, or joined on with `.`. Bound parameters are fine.
fn sql_injection(text: &str, from: usize) -> Option<(usize, usize)> {
    let args = &text[from..];
    let lead = args.len() - args.trim_start().len();
    // `whereRaw($sql)`: a variable that is the whole statement cannot be judged here.
    let (s, e, quote) = string_at(text, from)?;
    if s != from + lead {
        return None;
    }
    let literal = &text[s + 1..e - 1];
    let interpolated = quote == '"'
        && literal.match_indices('$').any(|(i, _)| {
            !literal[..i].ends_with('\\')
                && literal[i + 1..].starts_with(|c: char| c.is_alphabetic() || c == '_' || c == '{')
        });
    let interpolated = interpolated || (quote == '"' && literal.contains("{$"));
    let after = text[e..].trim_start();
    let joined = after.starts_with('.') && after.split([',', ';']).next().is_some_and(|a| a.contains('$'));
    (interpolated || joined).then_some((s, if joined { text.trim_end().len() } else { e }))
}

fn raw_sql(cx: &Cx, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| ext(&f.path) == "php" && !is_test_path(&f.path) && !is_migration(&f.path)) {
        for line in f.added().filter(|a| !is_comment(&a.text)) {
            let hit =
                RAW_SQL.iter().find_map(|n| line.text.find(n).and_then(|i| sql_injection(&line.text, i + n.len())));
            if let Some((s, e)) = hit {
                out.push(
                    Finding::new("LAR006", Level::Risk, "possible SQL injection: a variable is put into raw SQL")
                        .at_range(&f.path, line, s, e, "the value becomes part of the SQL text")
                        .check("can any of it come from a request, a header, an import or another user's data? column and direction names need an allow-list, since they cannot be bound")
                        .test("send `'` and `1 OR 1=1` as that input: expect a validation error or unchanged results, never an SQL error or extra rows")
                        .help("bind the value: `whereRaw('total > ?', [$min])`"),
                );
            }
        }
    }
}

// --- Blade ---------------------------------------------------------------------------------

/// Unescaped output that is fine: framework helpers that return safe HTML.
const SAFE_RAW: &[&str] = &["->links(", "csrf_field(", "method_field(", "json_encode(", "vite(", "Vite::"];

fn blade(cx: &Cx, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| f.path.ends_with(".blade.php")) {
        let mut shown = 0;
        for (h, i, line) in added_in(f) {
            if let Some(s) = line.text.find("{!!")
                && shown < 5
                && !SAFE_RAW.iter().any(|ok| line.text.contains(ok))
            {
                shown += 1;
                let e = line.text[s..].find("!!}").map_or(line.text.len(), |n| s + n + 3);
                out.push(
                    Finding::new("LAR007", Level::Warn, "unescaped output in a Blade view")
                        .at_range(&f.path, line, s, e, "printed as raw HTML")
                        .check("can a user influence this value (names, comments, rich text, imported data)?")
                        .test("save `<script>alert(1)</script>` and `\"><img src=x onerror=alert(1)>` into that value and open the page: you must see the text, not an alert")
                        .help("use `{{ }}`; if it must be HTML, sanitize it on the way in with an HTML purifier"),
                );
            }
            let lower = line.text.to_lowercase();
            if lower.contains("<form") && (lower.contains("method=\"post\"") || lower.contains("method='post'")) {
                let has_token = h.lines[i..]
                    .iter()
                    .filter(|x| x.kind != Kind::Removed)
                    .take(6)
                    .any(|x| ["@csrf", "csrf_field", "_token"].iter().any(|t| x.text.contains(t)));
                if !has_token {
                    out.push(
                        Finding::new("LAR012", Level::Warn, "a POST form without `@csrf`")
                            .at(&f.path, line, "<form", "no CSRF token right after it")
                            .test("submit the form: without the token Laravel answers `419 Page Expired`")
                            .help("add `@csrf` inside the form"),
                    );
                }
            }
        }
    }
}

// --- validation ----------------------------------------------------------------------------

const RULE_WORDS: &[&str] = &[
    "required",
    "nullable",
    "sometimes",
    "string|",
    "integer",
    "email",
    "unique:",
    "exists:",
    "Rule::",
    "min:",
    "max:",
    "confirmed",
    "date",
];

fn validation(cx: &Cx, out: &mut Vec<Finding>) {
    let relevant = |p: &str| {
        ["app/Http/Requests/", "app/Http/Controllers/", "app/Livewire/", "app/Http/Livewire/"]
            .iter()
            .any(|d| p.starts_with(d))
    };
    for f in live(cx).filter(|f| relevant(&f.path)) {
        let rule_line = |a: &&Line| {
            !is_comment(&a.text)
                && a.text.contains("=>")
                && RULE_WORDS.iter().any(|w| {
                    a.text.contains(&format!("'{w}"))
                        || a.text.contains(&format!("|{w}"))
                        || w.ends_with("::") && a.text.contains(w)
                })
        };
        let Some(line) = f.added().find(rule_line) else { continue };
        let mut finding = Finding::new("LAR008", Level::Note, "validation rules changed")
            .at(&f.path, line, "", "rules start here")
            .check("every field the code reads is validated, and the code uses `validated()` data")
            .test("submit: nothing at all, each field empty, the wrong type, one below and one above each limit, emoji and very long text")
            .test("each bad request must answer 422 (or return to the form) with the message on the right field, and keep what was typed");
        if f.added().any(|a| a.text.contains("unique:") || a.text.contains("Rule::unique")) {
            finding = finding.test("`unique`: edit an existing record and save it unchanged (it must not clash with itself: `Rule::unique(..)->ignore($model)`), then try another record's value");
        }
        if f.removed().any(|a| a.text.contains("required") || a.text.contains("max:") || a.text.contains("exists:")) {
            finding = finding
                .check("a rule was removed or loosened: can the database and the code cope with what is now allowed?");
        }
        out.push(finding);
    }
}

// --- env() and configuration ---------------------------------------------------------------

/// The variable names read with `env('NAME'...)` on a line.
fn env_names(text: &str) -> Vec<(usize, String)> {
    let mut out = Vec::new();
    for (i, _) in text.match_indices("env(") {
        if text[..i].chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '>' || c == '$') {
            continue;
        }
        if let Some((s, e, _)) = string_at(text, i + 4)
            && text[i + 4..s].trim().is_empty()
        {
            out.push((i, text[s + 1..e - 1].to_string()));
        }
    }
    out
}

fn env_usage(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    // New variables read by config files.
    let removed: Vec<String> =
        cx.diff.files.iter().flat_map(|f| f.removed()).flat_map(|a| env_names(&a.text)).map(|(_, n)| n).collect();
    let example = cx.read(".env.example");
    let example_diff: Vec<&str> =
        cx.file(".env.example").map(|f| f.added().map(|a| a.text.as_str()).collect()).unwrap_or_default();
    let mut seen = Vec::new();
    for f in live(cx).filter(|f| f.path.starts_with("config/") && ext(&f.path) == "php") {
        for line in f.added().filter(|a| !is_comment(&a.text)) {
            for (at, name) in env_names(&line.text) {
                if removed.contains(&name) || seen.contains(&name) {
                    continue;
                }
                seen.push(name.clone());
                let declares = |s: &str| s.trim_start_matches(['#', ' ']).starts_with(&format!("{name}="));
                let documented = example_diff.iter().any(|s| declares(s))
                    || example.as_deref().is_some_and(|e| e.lines().any(declares));
                let know_example = example.is_some() || !example_diff.is_empty();
                let level = if know_example && !documented { Level::Warn } else { Level::Note };
                let mut finding = Finding::new("LAR009", level, format!("new environment variable `{name}`"))
                    .at(&f.path, line, &line.text[at..], "must exist wherever this is deployed")
                    .test(format!("remove `{name}` from your `.env`, run `{}`, and use the feature: it should fail clearly or fall back safely", l.artisan("config:clear")))
                    .check("set it on staging and production before the deploy; if config is cached, rebuild the cache afterwards");
                if level == Level::Warn {
                    finding = finding.help(format!("add `{name}=` to .env.example"));
                }
                out.push(finding);
            }
        }
    }
    // env() anywhere else stops working once the config is cached.
    let outside = |p: &str| ["app/", "routes/", "resources/views/", "database/"].iter().any(|d| p.starts_with(d));
    for f in live(cx).filter(|f| ext(&f.path) == "php" && outside(&f.path)) {
        if let Some((line, (at, name))) = f
            .added()
            .filter(|a| !is_comment(&a.text))
            .find_map(|a| env_names(&a.text).into_iter().next().map(|n| (a, n)))
        {
            out.push(
                Finding::new("LAR009", Level::Warn, "`env()` used outside the config folder")
                    .at_range(&f.path, line, at, at + 4, "returns null once config is cached")
                    .note("after `config:cache`, which most deploys run, `.env` is not loaded and this silently becomes null")
                    .test(format!("`{}`, then exercise this code; afterwards `{}`", l.artisan("config:cache"), l.artisan("config:clear")))
                    .help(format!("read `{name}` in a file under config/ and use `config('...')` here")),
            );
        }
    }
}

// --- queues, scheduler, mail ---------------------------------------------------------------

fn jobs_and_schedule(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| ext(&f.path) == "php") {
        let name = file_name(&f.path).trim_end_matches(".php");
        if f.path.starts_with("app/Jobs/") {
            let shape = |a: &&Line| {
                let t = a.text.trim_start();
                t.contains("function __construct")
                    || (["public ", "protected ", "private ", "public readonly "].iter().any(|v| t.starts_with(v))
                        && t.contains('$')
                        && !t.contains("function "))
            };
            if matches!(f.status, Status::Modified | Status::Renamed)
                && let Some(line) = f.added().find(shape).or_else(|| f.removed().find(shape))
            {
                out.push(
                    Finding::new("LAR010", Level::Warn, format!("queued job `{name}` changes what it stores"))
                        .at(&f.path, line, "", "jobs already queued have the old shape")
                        .note("jobs are serialized when dispatched: ones waiting during the deploy are run by the new class and can fail on missing or renamed properties")
                        .test(format!("on the old code, dispatch the job to a real queue; switch to this branch and run `{}`; `{}` must stay empty", l.artisan("queue:work --once"), l.artisan("queue:failed")))
                        .help("give new properties defaults, or drain the queue before deploying"),
                );
            }
            if let Some(line) = f.added().find(|a| a.text.contains("class ")).or_else(|| f.added().next()) {
                out.push(
                    Finding::new("LAR010", Level::Note, format!("job `{name}` added or changed"))
                        .at(&f.path, line, "", "runs on the queue")
                        .check("safe to run twice (retries)? `$tries`, `$timeout` and `failed()` set as you need?")
                        .test(format!("with a real queue driver (`QUEUE_CONNECTION=database`; `sync` hides serialization and retry bugs): trigger it, then `{}`", l.artisan("queue:work --once")))
                        .test("make it throw once (break its input): check the retry, then what lands in failed jobs"),
                );
            }
        }
        let schedule_line = f.added().find(|a| a.text.contains("$schedule->") || a.text.contains("Schedule::"));
        if f.path.starts_with("app/Console/Commands/") || schedule_line.is_some() {
            let signature = f.lines().find(|a| a.text.contains("$signature")).and_then(|a| {
                string_at(&a.text, 0)
                    .and_then(|(s, e, _)| a.text[s + 1..e - 1].split_whitespace().next().map(str::to_string))
            });
            let Some(line) = schedule_line.or_else(|| f.added().next()) else { continue };
            let mut finding = Finding::new("LAR010", Level::Note, "console command or schedule changed")
                .at(&f.path, line, "", "runs without a user watching")
                .check("overlap (`withoutOverlapping`), timezone, and what happens when a run fails")
                .test(format!("`{}` to see when it runs next", l.artisan("schedule:list")));
            if let Some(sig) = signature {
                finding = finding.test(format!(
                    "`{}`, then run it a second time and check the second run is harmless",
                    l.artisan(&sig)
                ));
            }
            out.push(finding);
        }
        if (f.path.starts_with("app/Mail/") || f.path.starts_with("app/Notifications/"))
            && let Some(line) = f.added().next()
        {
            out.push(
                Finding::new("LAR010", Level::Note, format!("mail or notification `{name}` changed"))
                    .at(&f.path, line, "", "reaches real people")
                    .test("send it with `MAIL_MAILER=log` (or Mailpit) and read it: subject, links with the right host, empty and long values")
                    .check("who receives it, and can it be sent twice?"),
            );
        }
    }
}

// --- authorization -------------------------------------------------------------------------

const AUTH_MARKS: &[&str] = &[
    "authorize(",
    "Gate::allows(",
    "Gate::denies(",
    "->can(",
    "->cannot(",
    "@can",
    "@auth",
    "abort_unless(",
    "abort_if(",
];

fn is_auth_line(text: &str) -> bool {
    !is_comment(text)
        && (AUTH_MARKS.iter().any(|m| text.contains(m))
            || text.contains("middleware(")
                && ["auth", "can:", "verified", "role", "permission"].iter().any(|m| text.contains(m)))
}

fn authorization(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    for f in live(cx).filter(|f| ext(&f.path) == "php" && !is_test_path(&f.path)) {
        // Fewer checks after than before: one was dropped, not merely edited or moved within the file.
        let before: Vec<&Line> = f.removed().filter(|a| is_auth_line(&a.text)).collect();
        let after = f.added().filter(|a| is_auth_line(&a.text)).count();
        if before.len() > after {
            out.push(
                Finding::new("LAR011", Level::Risk, "an authorization check was removed")
                    .at(&f.path, before[0], "", "removed by this change (old line number)")
                    .check("did it move somewhere else (a policy, a FormRequest's `authorize()`, route middleware)? find the replacement before trusting that")
                    .test("call the affected action logged out, as another user (with their record's id), and as the least privileged role: each must get 401, 403 or 404"),
            );
        }
        if f.path.starts_with("app/Policies/")
            && let Some(line) = f.added().find(|a| a.text.contains("function ")).or_else(|| f.added().next())
        {
            out.push(
                Finding::new(
                    "LAR011",
                    Level::Note,
                    format!("policy `{}` changed", file_name(&f.path).trim_end_matches(".php")),
                )
                .at(&f.path, line, "", "decides who may do what")
                .test("walk the matrix for each ability: guest, owner, another user, admin")
                .test(format!(
                    "quick check in `{}`: `Gate::forUser($user)->allows('update', $model)`",
                    l.artisan("tinker")
                )),
            );
        }
    }
}

// --- composer ------------------------------------------------------------------------------

fn composer(cx: &Cx, l: &Laravel, out: &mut Vec<Finding>) {
    let Some(f) = cx.file("composer.json").filter(|f| f.status != Status::Deleted) else { return };
    let dep = |a: &&Line| {
        let t = a.text.trim_start();
        t.starts_with('"')
            && t.split("\":").next().is_some_and(|k| k.contains('/'))
            && t.contains(|c: char| c.is_ascii_digit() || c == '*')
    };
    for line in f.added() {
        let t = line.text.trim_start();
        if t.starts_with("\"php\":") || t.starts_with("\"laravel/framework\":") {
            let what = if t.starts_with("\"php\"") {
                "the PHP version requirement changed"
            } else {
                "the Laravel version changed"
            };
            out.push(
                Finding::new("LAR013", Level::Warn, what)
                    .at(&f.path, line, "", "affects every environment")
                    .check("do CI, staging, production and queue workers run a version that satisfies this? read the upgrade guide for a major bump")
                    .test(format!("`composer install`, `{}`, and click through the main screens with the log open for deprecations", l.test_cmd(None))),
            );
        }
    }
    let names: Vec<String> = f
        .added()
        .filter(dep)
        .filter_map(|a| a.text.trim_start().trim_start_matches('"').split('"').next().map(str::to_string))
        .filter(|n| n != "laravel/framework")
        .collect();
    if let Some(line) = f.added().find(dep)
        && !names.is_empty()
    {
        out.push(
            Finding::new("LAR013", Level::Note, format!("composer packages added or updated: {}", names.join(", ")))
                .at(&f.path, line, "", "dependency change")
                .test("`composer install` on a clean checkout, then `composer audit`")
                .check("does a package ship migrations or config to publish?"),
        );
    }
}

// --- views ---------------------------------------------------------------------------------

fn views(cx: &Cx, out: &mut Vec<Finding>) {
    let ui: Vec<&FileDiff> = live(cx).filter(|f| f.path.starts_with("resources/") && f.added_count() > 0).collect();
    let Some(first) = ui.first() else { return };
    let Some(line) = first.added().find(|a| !a.text.trim().is_empty()) else { return };
    let mut finding = Finding::new("LAR012", Level::Note, format!("the UI changed in {} file(s)", ui.len()))
        .at(&first.path, line, "", "check it in a browser")
        .check("empty state, one item and many items; very long text; validation errors; a narrow window; dark mode if you have it")
        .test("open each changed screen with the browser console open: no errors, no failed requests");
    if let Some(n) = cx.node().filter(|n| n.scripts.iter().any(|s| s == "build")) {
        finding = finding
            .test(format!("`{}` must succeed (it catches missing imports the dev server forgives)", n.run("build")));
    }
    out.push(finding);
}

#[cfg(test)]
mod tests {
    use super::super::testing::*;
    use super::*;
    use crate::review::project::Project;
    use crate::review::testutil::Scratch;

    const MIG: &str = "database/migrations/2024_01_01_000000_change_users.php";

    #[test]
    fn destructive_in_up_but_not_in_down() {
        let f = review(&[add(
            MIG,
            &[
                "public function up(): void",
                "{",
                "    Schema::table('users', fn ($t) => $t->dropColumn('legacy'));",
                "}",
                "public function down(): void",
                "{",
                "    Schema::dropIfExists('x');",
                "}",
            ],
        )]);
        let risks: Vec<_> = f.iter().filter(|f| f.code == "LAR001").collect();
        assert_eq!(risks.len(), 1);
        assert_eq!(risks[0].span.as_ref().unwrap().line, 3);
        assert!(risks[0].test[0].contains("php artisan migrate --pretend"));
        assert!(has(&f, "LAR003"));
        assert!(!has(&f, "LAR002"));
    }

    #[test]
    fn empty_down_and_edited_migration() {
        let f = review(&[add(
            MIG,
            &[
                "public function up(): void",
                "{",
                "    Schema::create('a', fn ($t) => $t->id());",
                "}",
                "public function down(): void",
                "{",
                "    // later",
                "}",
            ],
        )]);
        assert!(f.iter().any(|f| f.code == "LAR003" && f.title.contains("empty")));
        let g = review(&[edit(MIG, &["-$t->string('a');", "+$t->string('a')->unique();"])]);
        assert_eq!(get(&g, "LAR002").level, Level::Warn);
    }

    #[test]
    fn mutating_route_without_auth_warns_and_guarded_does_not() {
        let f = review(&[edit("routes/web.php", &["+Route::post('/invoices', [InvoiceController::class, 'store']);"])]);
        assert!(f.iter().any(|f| f.code == "LAR004" && f.level == Level::Warn && f.title.contains("POST /invoices")));
        let g = review(&[edit(
            "routes/web.php",
            &[
                "Route::middleware('auth')->group(function () {",
                "+    Route::delete('/x/{id}', [C::class, 'destroy']);",
                "});",
            ],
        )]);
        assert!(!g.iter().any(|f| f.code == "LAR004" && f.level == Level::Warn));
        let h = review(&[edit("routes/web.php", &["+Route::get('/about', fn () => view('about'));"])]);
        assert!(h.iter().all(|f| f.code != "LAR004" || f.level == Level::Note));
        assert_eq!(route_call("Route::match(['get', 'post'], '/s', X::class);").unwrap().1, "/s");
    }

    #[test]
    fn mass_assignment() {
        let f = review(&[edit("app/Models/User.php", &["+    protected $guarded = [];"])]);
        assert_eq!(get(&f, "LAR005").level, Level::Risk);
        let g = review(&[edit(
            "app/Models/User.php",
            &["-    protected $hidden = ['password'];", "+    protected $hidden = [];"],
        )]);
        assert!(get(&g, "LAR005").title.contains("JSON"));
    }

    #[test]
    fn raw_sql_with_variables_only() {
        let bad = [
            "$q->whereRaw(\"name = '$name'\");",
            "$q->orderByRaw('id ' . $dir);",
            "DB::select(\"select * from t where id = {$request->id}\");",
        ];
        for line in bad {
            assert!(has(&review(&[edit("app/Services/S.php", &[&format!("+{line}")])]), "LAR006"), "{line}");
        }
        let fine = [
            "$q->whereRaw('total > ?', [$min]);",
            "$q->selectRaw(\"count(*) as n\");",
            "DB::raw('price * 2');",
            "$q->whereRaw($sql);",
            "DB::select('select ?', [$a . 'x']);",
        ];
        for line in fine {
            assert!(!has(&review(&[edit("app/Services/S.php", &[&format!("+{line}")])]), "LAR006"), "{line}");
        }
    }

    #[test]
    fn blade_raw_output_and_missing_csrf() {
        let f = review(&[add(
            "resources/views/a.blade.php",
            &["<p>{!! $user->bio !!}</p>", "{!! $items->links() !!}", "<form method=\"POST\">", "  <input>", "</form>"],
        )]);
        assert_eq!(f.iter().filter(|f| f.code == "LAR007").count(), 1);
        assert!(f.iter().any(|f| f.code == "LAR012" && f.title.contains("@csrf")));
        let g = review(&[add("resources/views/b.blade.php", &["<form method=\"POST\">", "  @csrf", "</form>"])]);
        assert!(!g.iter().any(|f| f.title.contains("@csrf")));
    }

    #[test]
    fn validation_changes_mention_the_unique_trap() {
        let f = review(&[edit(
            "app/Http/Requests/UserRequest.php",
            &["+            'email' => ['required', 'email', 'unique:users'],"],
        )]);
        assert!(get(&f, "LAR008").test.iter().any(|t| t.contains("ignore($model)")));
    }

    #[test]
    fn env_outside_config_and_undocumented_variables() {
        let f = review(&[edit("app/Services/S.php", &["+$k = env('STRIPE_KEY');"])]);
        assert!(get(&f, "LAR009").title.contains("outside"));
        let s = Scratch::new("laravel-env");
        s.write("artisan", "");
        s.write("composer.json", r#"{"require":{"laravel/framework":"^11"}}"#);
        s.write(".env.example", "APP_NAME=x\nKNOWN=\n");
        let p = Project::detect(&s.0);
        let g = review_with(
            &[edit("config/services.php", &["+    'a' => env('KNOWN'),", "+    'b' => env('SECRET_THING'),"])],
            &p,
            None,
        );
        let v: Vec<_> = g.iter().filter(|f| f.code == "LAR009").map(|f| (f.level, f.title.clone())).collect();
        assert_eq!(v.len(), 2);
        assert!(v.iter().any(|(l, t)| *l == Level::Warn && t.contains("SECRET_THING")));
        assert!(v.iter().any(|(l, t)| *l == Level::Note && t.contains("KNOWN")));
    }

    #[test]
    fn job_shape_and_removed_authorization() {
        let f = review(&[edit(
            "app/Jobs/SendInvoice.php",
            &[
                "-    public function __construct(public int $id) {}",
                "+    public function __construct(public Invoice $invoice) {}",
            ],
        )]);
        assert!(f.iter().any(|f| f.code == "LAR010" && f.level == Level::Warn));
        let g = review(&[edit(
            "app/Http/Controllers/C.php",
            &["-        $this->authorize('update', $post);", "         $post->save();"],
        )]);
        assert_eq!(get(&g, "LAR011").level, Level::Risk);
        let moved = review(&[edit(
            "app/Http/Controllers/C.php",
            &["-        $this->authorize('update', $post);", "+        Gate::authorize('update', $post);"],
        )]);
        assert!(!has(&moved, "LAR011"));
    }

    #[test]
    fn nothing_laravel_in_other_projects() {
        assert!(
            !review(&[add("src/main.rs", &["fn main() { env(\"X\"); }"])]).iter().any(|f| f.code.starts_with("LAR"))
        );
    }
}