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);
}
fn live<'a>(cx: &'a Cx) -> impl Iterator<Item = &'a FileDiff> {
cx.diff.files.iter().filter(|f| f.status != Status::Deleted)
}
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)))
}
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"),
];
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)
}
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, ..)| {
!(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"),
);
}
}
}
}
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"];
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();
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()));
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)"),
);
}
}
}
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"),
);
}
}
}
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(",
];
fn sql_injection(text: &str, from: usize) -> Option<(usize, usize)> {
let args = &text[from..];
let lead = args.len() - args.trim_start().len();
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])`"),
);
}
}
}
}
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"),
);
}
}
}
}
}
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);
}
}
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>) {
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);
}
}
}
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")),
);
}
}
}
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?"),
);
}
}
}
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)) {
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")
)),
);
}
}
}
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?"),
);
}
}
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"))
);
}
}